### Basic Layout Setup Example Source: https://github.com/galacean/engine/blob/main/docs/en/UI/quickStart/transform.mdx Demonstrates how to initialize and configure a UITransform component for basic UI layout. ```APIDOC ### Basic Layout Setup ```typescript import { UITransform, HorizontalAlignmentMode, VerticalAlignmentMode } from "@galacean/engine"; // Get the Transform component of the UI element const uiTransform = entity.getComponent(UITransform); // Set size uiTransform.size = new Vector2(200, 100); // Set pivot to center uiTransform.pivot = new Vector2(0.5, 0.5); ``` ``` -------------------------------- ### Install Project Dependencies and Run Local Server Source: https://github.com/galacean/engine/blob/main/docs/en/xr/quickStart/debug.mdx Use these commands to install project dependencies and start a local HTTPS server for WebXR development. HTTPS is required for WebXR. ```bash npm install npm run https ``` -------------------------------- ### Basic Layout Setup Example Source: https://github.com/galacean/engine/blob/main/docs/en/UI/quickStart/transform.mdx Demonstrates setting the size and pivot for a UI element using the UITransform component. Ensure the necessary imports are included. ```typescript import { UITransform, HorizontalAlignmentMode, VerticalAlignmentMode } from "@galacean/engine"; // Get the Transform component of the UI element const uiTransform = entity.getComponent(UITransform); // Set size uiTransform.size = new Vector2(200, 100); // Set pivot to center uiTransform.pivot = new Vector2(0.5, 0.5); ``` -------------------------------- ### Galacean Engine Basic Usage Example Source: https://github.com/galacean/engine/blob/main/packages/galacean/README.md A comprehensive example demonstrating the creation of an engine instance, scene setup, adding entities with lights, cameras, and meshes, and running the engine. Ensure the HTML canvas element with 'canvas-id' exists. ```typescript // Create engine by passing in the HTMLCanvasElement id and adjust canvas size const engine = await WebGLEngine.create({ canvas: "canvas-id" }); engine.canvas.resizeByClientSize(); // Get scene and create root entity const scene = engine.sceneManager.activeScene; const rootEntity = scene.createRootEntity("Root"); // Create light const lightEntity = rootEntity.createChild("Light"); const directLight = lightEntity.addComponent(DirectLight); lightEntity.transform.setRotation(-45, -45, 0); directLight.intensity = 0.4; // Create camera const cameraEntity = rootEntity.createChild("Camera"); cameraEntity.addComponent(Camera); cameraEntity.transform.setPosition(0, 0, 12); // Create sphere const meshEntity = rootEntity.createChild("Sphere"); const meshRenderer = meshEntity.addComponent(MeshRenderer); const material = new BlinnPhongMaterial(engine); meshRenderer.setMaterial(material); meshRenderer.mesh = PrimitiveMesh.createSphere(engine, 1); // Run engine engine.run(); ``` -------------------------------- ### Install @galacean/engine-ui Source: https://github.com/galacean/engine/blob/main/packages/ui/README.md Install the @galacean/engine-ui library using npm. ```bash npm install @galacean/engine-ui ``` -------------------------------- ### Getting Started with @galacean/engine-ui Source: https://github.com/galacean/engine/blob/main/packages/ui/README.md Initialize the Galacean engine, set up a scene with a camera, create a UI canvas, and add an Image component. Ensure the image texture is loaded before assigning it to the sprite. ```typescript import { AssetType, Camera, Sprite, Texture2D, Vector3, WebGLEngine } from "@galacean/engine"; import { CanvasRenderMode, Image, ResolutionAdaptationMode, UICanvas } from "@galacean/engine-ui"; // Initialize engine and scene const engine = await WebGLEngine.create({ canvas: "canvas" }); const scene = engine.sceneManager.activeScene; const rootEntity = scene.createRootEntity(); // Create camera const cameraEntity = rootEntity.createChild("Camera"); cameraEntity.transform.position = new Vector3(0, 0, 10); const camera = cameraEntity.addComponent(Camera); camera.farClipPlane = 200; camera.nearClipPlane = 0.3; // Create canvas const canvasEntity = rootEntity.createChild("canvas"); const canvas = canvasEntity.addComponent(UICanvas); canvas.renderMode = CanvasRenderMode.ScreenSpaceCamera; canvas.resolutionAdaptationMode = ResolutionAdaptationMode.HeightAdaptation; canvas.distance = 100; canvas.renderCamera = camera; // Create Image const imageEntity = canvasEntity.createChild("image"); const image = imageEntity.addComponent(Image); engine.resourceManager .load({ url: "https://xxx.png", type: AssetType.Texture2D }) .then((texture) => { image.sprite = new Sprite(engine, texture); }); // Run the engine engine.run(); ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/galacean/engine/blob/main/docs/en/platform/wechatMiniGame.mdx Run this command in the root directory after exporting the project to install necessary dependencies. ```bash npm i ``` -------------------------------- ### Install Physics Lite Package Source: https://github.com/galacean/engine/blob/main/packages/physics-lite/README.md Use npm to install the physics lite package. ```sh npm install @galacean/engine-physics-lite ``` -------------------------------- ### Dependency Installation Source: https://github.com/galacean/engine/blob/main/docs/en/graphics/2D/lottie.mdx Command to install the necessary Galacean Lottie package. ```APIDOC ### Dependency Installation Install the required package: ```bash npm i @galacean/engine-lottie --save ``` ``` -------------------------------- ### Install Browsers for E2E Tests Source: https://github.com/galacean/engine/blob/main/e2e/README.md Manually installs the required browsers for running end-to-end tests. ```bash npm run e2e:install ``` -------------------------------- ### Complete Shader Example with UIScript and Macros Source: https://github.com/galacean/engine/blob/main/docs/en/graphics/material/examples/shaderlab-03-ui-script.mdx A full shader example integrating the Editor module for properties, UIScript for interaction logic, and macro definitions for conditional compilation in both vertex and fragment shaders. ```glsl Shader "Tutorial/03-UIScript" { // The Editor module defines the material panel properties and interactions Editor { Properties { // Basic properties material_BaseColor("Base Color", Color) = (1, 1, 1, 1); material_BaseTexture("Base Texture", Texture2D); // Grouped properties Header("Effects") { material_UseTexture("Use Texture", Boolean) = true; material_Brightness("Brightness", Range(0, 2, 0.01)) = 1.0; material_Contrast("Contrast", Range(0, 2, 0.01)) = 1.0; } Header("Animation") { material_EnableAnimation("Enable Animation", Boolean) = false; material_AnimSpeed("Animation Speed", Range(0, 5, 0.1)) = 1.0; } } } SubShader "Default" { Pass "Forward" { mat4 renderer_MVPMat; float renderer_Time; vec4 material_BaseColor; sampler2D material_BaseTexture; float material_Brightness; float material_Contrast; float material_AnimSpeed; struct a2v { vec4 POSITION; vec2 TEXCOORD_0; }; struct v2f { vec2 uv; }; VertexShader = vert; FragmentShader = frag; v2f vert(a2v input) { v2f output; vec4 pos = input.POSITION; // Add vertex animation effect if animation is enabled #ifdef ENABLE_ANIMATION pos.y += sin(pos.x * 3.0 + renderer_Time * material_AnimSpeed) * 0.2; #endif gl_Position = renderer_MVPMat * pos; output.uv = input.TEXCOORD_0; return output; } void frag(v2f input) { vec4 color = material_BaseColor; // Sample texture if texture is enabled #ifdef USE_TEXTURE vec4 texColor = texture2D(material_BaseTexture, input.uv); color *= texColor; #endif // Apply brightness and contrast adjustments color.rgb *= material_Brightness; color.rgb = (color.rgb - 0.5) * material_Contrast + 0.5; gl_FragColor = color; } } } } ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/galacean/engine/blob/main/docs/en/platform/h5.mdx Install project dependencies using npm or pnpm. This command is necessary before running development or build commands. ```bash npm i 或者 pnpm i ``` -------------------------------- ### Pro Code Development Example Source: https://github.com/galacean/engine/blob/main/docs/en/graphics/2D/lottie.mdx Example of loading and playing Lottie animations in a Pro Code workflow using an `.atlas` file. ```APIDOC ### Pro Code Development For Pro Code workflows, use [tools-atlas-lottie](https://www.npmjs.com/package/@galacean/tools-atlas-lottie) to generate an `.atlas` file from the JSON: ```typescript import { LottieAnimation } from "@galacean/engine-lottie"; engine.resourceManager.load({ urls: [ "https://gw.alipayobjects.com/os/bmw-prod/b46be138-e48b-4957-8071-7229661aba53.json", "https://gw.alipayobjects.com/os/bmw-prod/6447fc36-db32-4834-9579-24fe33534f55.atlas" ], type: 'lottie' }).then((lottieEntity) => { root.addChild(lottieEntity); const lottie = lottieEntity.getComponent(LottieAnimation); lottie.isLooping = true; lottie.speed = 1; lottie.play(); }); ``` ``` -------------------------------- ### Install Galacean Engine Source: https://github.com/galacean/engine/blob/main/README.md Install the Galacean Engine using npm. This is the first step for projects using pure code implementation. ```sh npm install @galacean/engine ``` -------------------------------- ### Implement Basic Functionality in Fragment Shader Source: https://github.com/galacean/engine/blob/main/docs/en/graphics/material/examples/shaderlab-05-advance.mdx Start with the most basic functionality for your fragment shader. This example sets the fragment color to the base material color. ```glsl // First, implement basic functionality void frag() { gl_FragColor = material_BaseColor; } ``` -------------------------------- ### Install Galacean ShaderLab Source: https://github.com/galacean/engine/blob/main/packages/shader-lab/README.md Install the ShaderLab package using npm. This is the first step to using ShaderLab in your project. ```sh npm install @galacean/engine-shaderlab ``` -------------------------------- ### Example Code Snippet with Highlight Source: https://github.com/galacean/engine/blob/main/docs/zh/how-to-contribute.mdx This is an example of code that has been highlighted using the `/specularTexture/` syntax. ```typescript engine.resourceManager .load({ type: AssetType.Env, url: "https://gw.alipayobjects.com/os/bmw-prod/6470ea5e-094b-4a77-a05f-4945bf81e318.bin", }) .then((ambientLight) => { scene.ambientLight = ambientLight; skyMaterial.texture = ambientLight.specularTexture; skyMaterial.textureDecodeRGBM = true; openDebug(ambientLight.specularTexture); engine.run(); }); ``` -------------------------------- ### Create a New Test Case Source: https://github.com/galacean/engine/blob/main/e2e/README.md Example of creating a new test case file in TypeScript, initializing the WebGLEngine, and setting up for screenshots. ```typescript // e2e/case/my-new-test.ts WebGLEngine.create({ canvas: "canvas" }).then((engine) => { // Your test implementation updateForE2E(engine); initScreenshot(engine, camera); }); ``` -------------------------------- ### Install Git LFS Source: https://github.com/galacean/engine/blob/main/e2e/README.md Installs and pulls necessary baseline images for e2e tests using Git LFS. ```bash git lfs install git lfs pull ``` -------------------------------- ### Scripting: Basic Configuration Source: https://github.com/galacean/engine/blob/main/docs/zh/physics/collider/characterController.mdx Example TypeScript code for setting up a CharacterController component and its initial properties. ```typescript import { CharacterController, CapsuleColliderShape, Vector3, Script } from '@galacean/engine'; // Assuming 'entity' is a valid Entity object const controller = entity.addComponent(CharacterController); // Add a capsule collider shape const capsule = new CapsuleColliderShape(); capsule.radius = 0.5; capsule.height = 2; controller.addShape(capsule); // Configure controller properties controller.stepOffset = 0.5; // Set step height controller.slopeLimit = 45; // Set max walkable slope angle controller.upDirection = new Vector3(0, 1, 0); // Set up direction ``` -------------------------------- ### Install @galacean/engine-xr Source: https://github.com/galacean/engine/blob/main/packages/xr/README.md Use npm to install the XR implementation layer for developing XR applications. ```sh npm install @galacean/engine-xr ``` -------------------------------- ### Install PhysX Physics Engine Source: https://github.com/galacean/engine/blob/main/packages/physics-physx/README.md Use this npm command to install the PhysX physics engine package. ```sh npm install @galacean/engine-physics-physx ``` -------------------------------- ### Install @galacean/engine-xr-webxr Source: https://github.com/galacean/engine/blob/main/packages/xr-webxr/README.md Use npm to install the WebXR implementation backend for the Galacean engine. This package is required for applications using the WebXR standard. ```sh npm install @galacean/engine-xr-webxr ``` -------------------------------- ### Install CLI Packaging Tool Source: https://github.com/galacean/engine/blob/main/docs/en/graphics/2D/spriteAtlas.mdx Installs the Galacean CLI tools for packaging sprite atlases globally. Use this command to enable command-line operations for atlas creation and management. ```bash # Install globally npm i @galacean/tools-atlas -g ``` -------------------------------- ### Launch E2E Case Page Source: https://github.com/galacean/engine/wiki/How-to-write-an-e2e-Test-for-runtime Run this command to launch the case page for debugging e2e tests. Ensure git-lfs is installed and configured. ```bash npm run e2e:case ``` -------------------------------- ### Scripting: Slope and Step Adjustments Source: https://github.com/galacean/engine/blob/main/docs/zh/physics/collider/characterController.mdx Examples of how to adjust `slopeLimit` and `stepOffset` to control the character's ability to navigate slopes and steps. ```typescript import { CharacterController, ControllerNonWalkableMode } from '@galacean/engine'; // Assuming 'controller' is an instance of CharacterController // 1. Slope Walking Adjustments // Allow walking on steeper slopes controller.slopeLimit = 60; // Define behavior on non-walkable slopes controller.nonWalkableMode = ControllerNonWalkableMode.PreventClimbingAndForceSliding; // Will slide down steep slopes // 2. Step Walking Adjustments // Adjust the maximum step height the character can climb controller.stepOffset = 0.3; // Allows climbing smaller steps controller.stepOffset = 0.5; // Allows climbing larger steps ``` -------------------------------- ### Engine Initialization Source: https://github.com/galacean/engine/blob/main/docs/en/core/engine.mdx Demonstrates how to initialize the WebGLEngine with various configuration options. ```APIDOC ## Initialization To facilitate users directly creating a web engine, we provide the [WebGLEngine](/apis/rhi-webgl/#WebGLEngine), which supports WebGL1.0 and WebGL2.0. ```typescript const engine = await WebGLEngine.create({ canvas: "canvas-id", colorSpace: {...}, graphicDeviceOptions: {...}, gltf: {...}, ktx2Loader: {...} }); ``` Below is a description of the [configuration](/apis/galacean/#WebGLEngineConfiguration) types passed when creating the engine: | Configuration | | ------------------------------------------------------------ | | canvas | | [graphicDeviceOptions](/apis/galacean/#WebGLGraphicDeviceOptions) | | [colorSpace](/apis/galacean/#ColorSpace) | | gltf | | ktx2Loader | For more related configuration information, please refer to [Physics System](/en/docs/physics/overall), [Interaction System](/en/docs/input/input/), [XR System](/en/docs/xr/overall). ``` -------------------------------- ### Lottie Animation Slice Definition Source: https://github.com/galacean/engine/blob/main/docs/zh/graphics/2D/lottie.mdx Example JSON structure for defining animation slices with name, start, and end frames. ```json "lolitaAnimations": [ { "name": "clip1", "start": 0, "end": 30 }, { "name": "clip2", "start": 50, "end": 100 }, ] ``` -------------------------------- ### Efficient Pass State Setup Source: https://github.com/galacean/engine/blob/main/docs/en/graphics/material/examples/shaderlab-02-render-state.mdx This example demonstrates an efficient way to set render states within a single pass to minimize state switching overhead. Avoid frequent state switching within loops. ```glsl // Good: Minimize state changes Pass "Efficient" { // Set all required states once BlendState { /* ... */ } DepthState { /* ... */ } RasterState { /* ... */ } } ``` -------------------------------- ### Create and Manage Entities and Components Source: https://context7.com/galacean/engine/llms.txt Demonstrates creating entities, adding components, finding entities by name or path, and managing entity lifecycle. Ensure the engine is initialized before use. ```typescript import { Entity, MeshRenderer, Camera, DirectLight, PrimitiveMesh, BlinnPhongMaterial, Vector3 } from "@galacean/engine"; // Create root entity in scene const scene = engine.sceneManager.scenes[0]; const rootEntity = scene.createRootEntity("root"); // Create child entities const cubeEntity = rootEntity.createChild("cube"); const cameraEntity = rootEntity.createChild("camera"); const lightEntity = rootEntity.createChild("light"); // Alternative: Create detached entity and add to parent const detachedEntity = new Entity(engine, "detached"); rootEntity.addChild(detachedEntity); // Add components to entities const meshRenderer = cubeEntity.addComponent(MeshRenderer); meshRenderer.mesh = PrimitiveMesh.createCuboid(engine, 2, 2, 2); meshRenderer.setMaterial(new BlinnPhongMaterial(engine)); const camera = cameraEntity.addComponent(Camera); cameraEntity.transform.setPosition(0, 5, 10); cameraEntity.transform.lookAt(new Vector3(0, 0, 0)); const light = lightEntity.addComponent(DirectLight); light.color.set(1, 1, 1, 1); lightEntity.transform.setRotation(-45, -45, 0); // Find entities const foundEntity = scene.findEntityByName("cube"); const entityByPath = scene.findEntityByPath("root/cube"); const child = rootEntity.findByName("cube"); const childByPath = rootEntity.findByPath("parent/child/grandson"); // Get components const renderer = cubeEntity.getComponent(MeshRenderer); const components = []; cubeEntity.getComponents(MeshRenderer, components); cubeEntity.getComponentsIncludeChildren(MeshRenderer, components); // Entity lifecycle cubeEntity.isActive = false; // Deactivate entity and components rootEntity.removeChild(cubeEntity); // Remove from hierarchy cubeEntity.destroy(); // Destroy entity and children ``` -------------------------------- ### Create and Initialize Quaternions Source: https://github.com/galacean/engine/blob/main/docs/en/core/math.mdx Demonstrates creating default and initialized Quaternions, and setting their values. Ensure necessary imports are included. ```typescript import { Vector3, Quaternion, MathUtil } from '@galacean/engine-math'; // 创建默认四元数,即 x,y,z 分量均为0,w 分量为1 const q1 = new Quaternion(); // 创建四元数,并用给定值初始化 x,y,z,w 分量 const q2 = new Quaternion(1, 2, 3, 4); // 设置指定值 q1.set(1, 2, 3, 4); ``` -------------------------------- ### Install Build Dependencies with PNPM Source: https://github.com/galacean/engine/blob/main/README.md Install the necessary build dependencies for the Galacean Engine using PNPM. This requires Node.js v15.0.0+ and PNPM installed globally. ```sh pnpm install ``` -------------------------------- ### Build Project for Deployment Source: https://github.com/galacean/engine/blob/main/docs/en/platform/h5.mdx Execute the build command to generate production-ready assets. The output is typically placed in a 'dist' folder and can be deployed to a CDN or published. ```bash npm run build ``` -------------------------------- ### Initialize Galacean WebGLEngine Source: https://context7.com/galacean/engine/llms.txt Create and configure the WebGLEngine, the entry point for Galacean applications. It manages the render loop, scene, resources, and subsystems. Configure refresh rate and access engine subsystems. ```typescript import { WebGLEngine, Camera, DirectLight, MeshRenderer, PrimitiveMesh, BlinnPhongMaterial } from "@galacean/engine"; // Create engine with canvas and optional configurations const engine = await WebGLEngine.create({ canvas: "canvas-id", // Canvas element ID or HTMLCanvasElement graphicDeviceOptions: { webGLMode: 2, // WebGL 2.0 alpha: true, antialias: true }, colorSpace: ColorSpace.Linear }); // Configure refresh rate (default: vertical sync) engine.vSyncCount = 1; // Sync with screen refresh rate // Or disable vertical sync and set target frame rate // engine.vSyncCount = 0; // engine.targetFrameRate = 60; // Access engine subsystems const resourceManager = engine.resourceManager; const sceneManager = engine.sceneManager; const inputManager = engine.inputManager; // Start the render loop engine.run(); // Control render loop engine.pause(); // Pause rendering engine.resume(); // Resume rendering engine.destroy(); // Clean up and destroy engine ``` -------------------------------- ### Create a Simple Scene with Galacean Engine Source: https://github.com/galacean/engine/blob/main/README.md Example of creating a basic scene in Galacean Engine using TypeScript. This includes setting up the engine, adding a light, camera, and a sphere with a material. ```typescript import { BlinnPhongMaterial, Camera, DirectLight, MeshRenderer, WebGLEngine, PrimitiveMesh } from "@galacean/engine"; // Create engine by passing in the HTMLCanvasElement id and adjust canvas size const engine = await WebGLEngine.create({ canvas: "canvas-id" }); engine.canvas.resizeByClientSize(); // Get scene and create root entity const scene = engine.sceneManager.activeScene; const rootEntity = scene.createRootEntity("Root"); // Create light const lightEntity = rootEntity.createChild("Light"); const directLight = lightEntity.addComponent(DirectLight); lightEntity.transform.setRotation(-45, -45, 0); directLight.intensity = 0.4; // Create camera const cameraEntity = rootEntity.createChild("Camera"); cameraEntity.addComponent(Camera); cameraEntity.transform.setPosition(0, 0, 12); // Create sphere const meshEntity = rootEntity.createChild("Sphere"); const meshRenderer = meshEntity.addComponent(MeshRenderer); const material = new BlinnPhongMaterial(engine); meshRenderer.setMaterial(material); meshRenderer.mesh = PrimitiveMesh.createSphere(engine, 1); // Run engine engine.run(); ``` -------------------------------- ### Implement Lighting Types in Galacean Source: https://context7.com/galacean/engine/llms.txt Demonstrates the setup for directional, point, spot, and ambient lights. Ensure necessary classes like Color and Vector3 are imported. ```typescript import { DirectLight, PointLight, SpotLight, AmbientLight, Color, Vector3 } from "@galacean/engine"; // Directional Light - simulates sunlight const sunEntity = rootEntity.createChild("sun"); const directLight = sunEntity.addComponent(DirectLight); directLight.color.set(1, 0.95, 0.8, 1); sunEntity.transform.setRotation(-45, -45, 0); // Point Light - emits in all directions const pointLightEntity = rootEntity.createChild("pointLight"); const pointLight = pointLightEntity.addComponent(PointLight); pointLight.color.set(1, 0.5, 0, 1); pointLight.distance = 10; // Effective range pointLightEntity.transform.setPosition(0, 5, 0); // Spot Light - cone-shaped light const spotLightEntity = rootEntity.createChild("spotLight"); const spotLight = spotLightEntity.addComponent(SpotLight); spotLight.color.set(1, 1, 1, 1); spotLight.distance = 20; spotLight.angle = Math.PI / 6; // Outer cone angle (radians) spotLight.penumbra = 0.2; // Soft edge transition spotLightEntity.transform.setPosition(0, 10, 0); spotLightEntity.transform.setRotation(-90, 0, 0); // Scene Ambient Light const scene = engine.sceneManager.scenes[0]; const ambientLight = scene.ambientLight; ambientLight.diffuseSolidColor.set(0.3, 0.3, 0.4, 1); ``` -------------------------------- ### Initialize Physics Backends Source: https://context7.com/galacean/engine/llms.txt Initialize the engine with either LitePhysics for collision detection or PhysX for full physics simulation. Ensure the canvas element is available. ```typescript import { WebGLEngine, StaticCollider, DynamicCollider, CharacterController, BoxColliderShape, SphereColliderShape, CapsuleColliderShape, HitResult, Ray, Vector3 } from "@galacean/engine"; import { LitePhysics } from "@galacean/engine-physics-lite"; import { PhysXPhysics } from "@galacean/engine-physics-physx"; // Initialize with lightweight physics (collision detection only) const engine = await WebGLEngine.create({ canvas: "canvas", physics: new LitePhysics() }); // Or use PhysX for full physics simulation const enginePhysX = await WebGLEngine.create({ canvas: "canvas", physics: new PhysXPhysics() }); ``` -------------------------------- ### Install Galacean Engine Source: https://github.com/galacean/engine/blob/main/docs/en/basics/overview.mdx Install the core Galacean Engine package using NPM. Ensure consistent major versions between the engine and toolkit packages. ```bash npm install --save @galacean/engine ``` -------------------------------- ### Install Lottie Engine Dependency Source: https://github.com/galacean/engine/blob/main/docs/en/graphics/2D/lottie.mdx Install the necessary Lottie package for Galacean using npm. This command adds the Lottie engine integration to your project dependencies. ```bash npm i @galacean/engine-lottie --save ``` -------------------------------- ### Build for Release Source: https://github.com/galacean/engine/blob/main/docs/en/platform/wechatMiniGame.mdx Run this command to build the project for release. This command removes source map files and compresses the code for a smaller footprint. ```bash npm run release ``` -------------------------------- ### Initialize XR Engine and Enter Session Source: https://context7.com/galacean/engine/llms.txt Initialize the WebGLEngine with XR support using WebXRDevice. Access the xrManager to enter immersive VR or AR sessions, specifying required and optional features. Check for XR support and exit sessions when done. ```typescript import { WebGLEngine, Camera } from "@galacean/engine"; import { XRManager, XRSessionMode } from "@galacean/engine-xr"; import { WebXRDevice } from "@galacean/engine-web-xr"; // Initialize engine with XR support const engine = await WebGLEngine.create({ canvas: "canvas", xrDevice: new WebXRDevice() }); // Access XR manager const xrManager = engine.xrManager; // Start VR session await xrManager.enterXR(XRSessionMode.ImmersiveVR, { requiredFeatures: ["local-floor"], optionalFeatures: ["hand-tracking"] }); // Start AR session await xrManager.enterXR(XRSessionMode.ImmersiveAR, { requiredFeatures: ["hit-test"] }); // Check XR support if (xrManager.isSupported(XRSessionMode.ImmersiveVR)) { console.log("VR is supported"); } // Exit XR session await xrManager.exitXR(); ``` -------------------------------- ### Initialize Engine with Lite Physics Backend Source: https://github.com/galacean/engine/blob/main/docs/en/physics/overall.mdx Use this when initializing the engine for lightweight scenarios. Ensure LitePhysics is imported. ```typescript import {LitePhysics} from "@galacean/engine-physics-lite"; const engine = await WebGLEngine.create({ canvas: htmlCanvas, physics: new LitePhysics(), }); ``` -------------------------------- ### Queue Animations with Delay Source: https://github.com/galacean/engine/blob/main/docs/en/graphics/2D/spine/add-and-use.mdx Use addAnimation to queue animations after the current one finishes. The delay parameter controls when the next animation starts relative to the previous one's start or end. ```typescript state.setAnimation(0, 'animationA', false); // Play animation A on track 0 state.addAnimation(0, 'animationB', true, 0); // Queue animation B after A with looping ``` -------------------------------- ### Initialize WebGLEngine Source: https://github.com/galacean/engine/blob/main/docs/zh/core/engine.mdx Creates a new WebGLEngine instance. Configuration options include canvas ID or element, color space, graphics device settings, and loader configurations for glTF and KTX2. ```typescript const engine = await WebGLEngine.create({ canvas: "canvas-id", colorSpace: {...}, graphicDeviceOptions: {...}, gltf: {...}, ktx2Loader: {...} }); ``` -------------------------------- ### Getting Camera Component Source: https://github.com/galacean/engine/blob/main/docs/en/graphics/camera/component.mdx Methods for obtaining the Camera component instance. ```APIDOC ## Getting Camera Component ### Get Camera via Entity If you know which node the camera component is mounted on, you can directly get it through `getComponent` or `getComponentsIncludeChildren`: ```typescript // Get camera component from the node it's mounted on const camera = entity.getComponent(Camera); // Get camera component from the parent node of the node it's mounted on (not recommended) const cameras = entity.getComponentsIncludeChildren(Camera, []); ``` ### Get All Cameras in Scene If you are not sure which node the camera component is mounted on, you can also get all the camera components in the scene through a more hacky way: ```typescript // Get all camera components in this scene (not recommended) const cameras = scene._componentsManager._activeCameras; ``` ``` -------------------------------- ### Get Child Entities Source: https://github.com/galacean/engine/blob/main/docs/en/core/entity.mdx Access all direct child entities of a given entity. ```typescript const childrenEntity = newEntity.children; ``` -------------------------------- ### Create Transformation Matrices from Components Source: https://github.com/galacean/engine/blob/main/docs/en/core/math.mdx Demonstrates how to create individual matrices for rotation (from quaternion and axis-angle), scaling, and translation, and how to combine them using affine transformation. ```typescript // 根据四元数生成旋转矩阵 const m9 = new Matrix(); Matrix.rotationQuaternion(qua, m9); // 根据旋转角度生成旋转矩阵 const m10 = new Matrix(); Matrix.rotationAxisAngle(new Vector3(0, 0, 1), Math.PI * 0.5, m10); // 根据缩放生成缩放矩阵 const m11 = new Matrix(); Matrix.scaling(scale, m11); // 根据位移生成位移矩阵 const m12 = new Matrix(); Matrix.translation(translate, m12); ``` ```typescript // 根据旋转、缩放、位移生成矩阵 const m13 = new Matrix(); Matrix.affineTransformation(scale, qua, translate, m13); ``` -------------------------------- ### Create and Set Material Properties Source: https://github.com/galacean/engine/blob/main/docs/en/graphics/material/overview.mdx Demonstrates how to create a new material with a specified shader and set its properties like base color and texture. Ensure the engine and shader are initialized before use. ```typescript const material = new Material(engine, shader); material.shaderData.setColor("material_BaseColor", new Color(1, 0, 0, 1)); material.shaderData.setTexture("material_BaseTexture", texture); ``` -------------------------------- ### Camera Component Scripting Source: https://github.com/galacean/engine/blob/main/docs/en/graphics/camera/component.mdx Examples of how to access and modify camera component properties via script. ```APIDOC ## Camera Component Scripting ### Description Access and modify camera component properties using TypeScript. ### Code Example ```typescript // Get the camera component from the node where the camera is mounted const camera = entity.getComponent(Camera); // Enable post-processing camera.enablePostProcess = true; // Enable HDR camera.enableHDR = true; // Enable FXAA camera.antiAliasing = AntiAliasing.FXAA; // Preserve the alpha channel in the output camera.isAlphaOutputRequired = true; ``` ``` -------------------------------- ### Instantiate a Prefab from URL Source: https://github.com/galacean/engine/blob/main/docs/en/core/prefab.mdx Load a prefab asset by its URL and then instantiate it into the scene. Ensure the asset is loaded with the correct type. ```typescript engine.resourceManager .load({ url: "Prefab's URL", type: AssetType.Prefab }) .then((prefab: PrefabResource) => { const prefabInstanceEntity = prefab.instantiate(); scene.addRootEntity(prefabInstanceEntity); }); ``` -------------------------------- ### Find Child Entity by Name Source: https://github.com/galacean/engine/blob/main/docs/en/core/entity.mdx Search for a child or descendant entity by its name, starting from the current entity. ```typescript newEntity.findByName("model"); ``` -------------------------------- ### Create and Transform Bounding Boxes Source: https://github.com/galacean/engine/blob/main/docs/en/core/math.mdx Demonstrates various methods for creating BoundingBox instances, including from center and extent, points, and spheres. Also shows how to transform a bounding box using a matrix and merge two bounding boxes. ```typescript import { BoundingBox, BoundingSphere, Matrix, Vector3 } from "@galacean/engine-math"; // 通过不同的方式创建同样的包围盒 const box1 = new BoundingBox(); const box2 = new BoundingBox(); const box3 = new BoundingBox(); // 通过中心点和盒子范围来创建 BoundingBox.fromCenterAndExtent(new Vector3(0, 0, 0), new Vector3(1, 1, 1), box1); // 通过很多点来创建 const points = [ new Vector3(0, 0, 0), new Vector3(-1, 0, 0), new Vector3(1, 0, 0), new Vector3(0, 1, 0), new Vector3(0, 1, 1), new Vector3(1, 0, 1), new Vector3(0, 0.5, 0.5), new Vector3(0, -0.5, 0.5), new Vector3(0, -1, 0.5), new Vector3(0, 0, -1), ]; BoundingBox.fromPoints(points, box2); // 通过包围球来创建 const sphere = new BoundingSphere(new Vector3(0, 0, 0), 1); BoundingBox.fromSphere(sphere, box3); // 通过矩阵来对包围盒进行变换 const box = new BoundingBox(new Vector3(-1, -1, -1), new Vector3(1, 1, 1)); const matrix = new Matrix( 2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 2, 0, 1, 0.5, -1, 1 ); const newBox = new BoundingBox(); BoundingBox.transform(box, matrix, newBox); // 合并两个包围盒 box1, box2 成为一个新的包围盒 box BoundingBox.merge(box1, box2, box); // 获取包围盒的中心点和范围 const center = new Vector3(); box.getCenter(center); const extent = new Vector3(); box.getExtent(extent); // 获取包围盒的8个顶点 const corners = [ new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3() ]; box.getCorners(corners); ``` -------------------------------- ### Initialize Engine and Enter XR Source: https://github.com/galacean/engine/blob/main/packages/xr/README.md Initialize the WebGLEngine with XR support and provide a button click handler to enter an XR session (AR mode). ```typescript import { WebXRDevice } from "@galacean/engine-xr-webxr"; import { XRHitTest, XRSessionMode } from "@galacean/engine-xr"; // Create engine by passing in the HTMLCanvasElement WebGLEngine.create({ canvas: "canvas", xrDevice: new WebXRDevice(), }).then((engine) => { // Users need to actively click the button to enter XR XRButton.onClick = function () { this.engine.xrManager.enterXR(XRSessionMode.AR).then( () => { console.log("Enter AR"); }, (error) => { console.log("Not supported AR", error); } ); }; }); ```