-
-
Notifications
You must be signed in to change notification settings - Fork 394
docs: add scripting doc for llm #2832
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Conversation
WalkthroughAdds numerous new documentation pages under docs/scripting covering engine subsystems: animation, assets/loading, audio, physics, input, rendering, math, particles, scene/engine configuration, entities/components, memory/performance, build tooling, XR, and 2D systems. No runtime code or public API signatures are changed. Changes
Sequence Diagram(s)sequenceDiagram
autonumber
actor App
participant RM as ResourceManager
participant Loader as Loader (by type)
participant Cache as Cache
App->>RM: load(items, options)
RM->>Cache: check/useCache
alt hit
RM-->>App: resolved AssetPromise (from cache)
else miss
loop per item
RM->>Loader: load(LoadItem)
Loader-->>RM: progress/update
Loader-->>RM: asset or error
end
RM->>Cache: store asset(s)
RM-->>App: AssetPromise (then/catch/finally)
end
App-->>RM: cancel() (optional)
sequenceDiagram
autonumber
participant Engine
participant Animator
participant Controller as AnimatorController
participant State as AnimatorStateMachine
participant Script as StateMachineScript
loop each frame
Engine->>Animator: update(deltaTime)
Animator->>Controller: evaluate parameters
Controller->>State: update transitions
State-->>Animator: active state
alt on enter/exit/update
Animator->>Script: onStateEnter/Update/Exit
end
end
sequenceDiagram
autonumber
participant Game as Game Code
participant Phys as PhysicsScene
participant World as Physics World
Game->>Phys: raycast(origin, dir, maxDist, mask?)
Phys->>World: query
World-->>Phys: HitResult | null
Phys-->>Game: result
opt onCollision/Trigger
World-->>Game: enter/exit/stay events
end
Estimated code review effort🎯 2 (Simple) | ⏱️ ~12 minutes Poem
Pre-merge checks and finishing touches✅ Passed checks (3 passed)
✨ Finishing touches🧪 Generate unit tests
Tip 👮 Agentic pre-merge checks are now available in preview!Pro plan users can now enable pre-merge checks in their settings to enforce checklists before merging PRs.
Please see the documentation for more information. Example: reviews:
pre_merge_checks:
custom_checks:
- name: "Undocumented Breaking Changes"
mode: "warning"
instructions: |
Pass/fail criteria: All breaking changes to public APIs, CLI flags, environment variables, configuration keys, database schemas, or HTTP/GraphQL endpoints must be documented in the "Breaking Change" section of the PR description and in CHANGELOG.md. Exclude purely internal or private changes (e.g., code not exported from package entry points or explicitly marked as internal).Please share your feedback with us on this Discord post. Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #2832 +/- ##
==========================================
- Coverage 80.27% 79.42% -0.85%
==========================================
Files 852 852
Lines 93108 93108
Branches 9344 9342 -2
==========================================
- Hits 74744 73953 -791
- Misses 18220 19010 +790
- Partials 144 145 +1
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 36
🧹 Nitpick comments (65)
docs/scripting/base-systems.md (2)
83-89: Clarify units and property availability.Add “(seconds)” to all time properties and ensure elapsedTime/actualElapsedTime actually exist; if not, drop them.
- Important properties: + Important properties (all times in seconds): - - `deltaTime` / `elapsedTime`: ... - - `actualDeltaTime` / `actualElapsedTime`: ... + - `deltaTime`: ... + - `actualDeltaTime`: ...
50-66: Logger defaults confirmed — document level behavior
- Logging is disabled by default; Logger.enable()/Logger.disable() exist and Logger.isEnabled mirrors the current state.
- Update docs/scripting/base-systems.md to either enumerate supported log levels or explicitly state there is no level-filtering and that enable/disable toggles console methods (debug/info/warn/error).
docs/scripting/physics.md (2)
40-45: Await initialize() for consistency with the Promise API.The API returns Promise; the Lite example should await too.
-// Initialize the physics manager with the LitePhysics backend -engine.physicsManager.initialize(LitePhysics); +// Initialize the physics manager with the LitePhysics backend +await engine.physicsManager.initialize(LitePhysics);
11-18: Fix MD007 list indentation.Indent nested list items by 2 spaces to satisfy markdownlint.
- - **Pros**: Very small, fast for basic cases, no external dependencies. - - **Cons**: Limited features; no rigid body dynamics, joints, or advanced colliders. + - **Pros**: Very small, fast for basic cases, no external dependencies. + - **Cons**: Limited features; no rigid body dynamics, joints, or advanced colliders. - - **Pros**: Full-featured rigid body dynamics, complex colliders (mesh, convex), joints, and stable stacking. - - **Cons**: Larger package size due to the required WASM module. + - **Pros**: Full‑featured rigid body dynamics, complex colliders (mesh, convex), joints, and stable stacking. + - **Cons**: Larger package size due to the required WASM module.Also applies to: 19-27
docs/scripting/component-dependencies.md (2)
47-53: Don’t claim exact error strings.Avoid quoting literal engine error messages unless guaranteed. Prefer generic phrasing.
-entity.addComponent(MeshRenderer); // ❌ Throws error: "Should add MeshRenderer before adding MaterialController" +entity.addComponent(MeshRenderer); // ❌ Throws an error indicating MeshRenderer must be added first
96-99: Confirm Joint → DynamicCollider (AutoAdd); clarify backend requirementVerified — DynamicCollider and Joint (FixedJoint / SpringJoint / HingeJoint) exist and the @dependentComponents(DynamicCollider, DependentMode.AutoAdd) declaration is accurate; however, full joint + dynamic-collider physics requires the PhysX (WASM) backend (the Lite backend only provides basic collision). Update docs to state this.
Location: docs/scripting/component-dependencies.md lines 96–99
docs/scripting/Math.md (2)
9-9: Add language to any bare code fences.markdownlint MD040 flagged a fence missing a language. Ensure all fences specify “typescript” (or appropriate).
671-691: Caution on fast inverse sqrt.In JS/TS this micro‑opt is often slower and less precise than 1/Math.sqrt(x). Add a warning or drop it.
- static fastInverseSqrt(number: number): number { + // Note: In JS/TS this is typically slower than 1/Math.sqrt(x). Prefer standard math unless profiled. + static fastInverseSqrt(number: number): number {docs/scripting/Text.md (2)
123-132: Avoid assigning null unless the type allows it.If font is not nullable, prefer undefined or a clear release API.
-textRenderer.font = null; // Decrements reference, auto-cleanup when count reaches 0 +textRenderer.font = undefined; // Or call a provided release/dispose method if available
183-198: RTL/bidi and shaping caveat.Right‑aligning is insufficient for Arabic/Hebrew; note bidi and shaping requirements or provide a link to localization guidance.
docs/scripting/component.md (2)
3-3: Fix cross‑doc links to scripting path.Update docs/llm/... to docs/scripting/...
- Most gameplay logic is implemented by extending `Script`—see `docs/llm/script-system.md` for the full scripting guide. + Most gameplay logic is implemented by extending `Script`—see `docs/scripting/script-system.md` for the full scripting guide. - - `docs/llm/script-system.md` – 编写脚本、生命周期、事件回调 - - `docs/llm/renderer.md` – 渲染组件详解 - - `docs/llm/physics-scene.md` / `docs/llm/collider.md` – 物理组件 + - `docs/scripting/script-system.md` – Scripting, lifecycle, callbacks + - `docs/scripting/renderer.md` – Rendering components + - `docs/scripting/physics-scene.md` / `docs/scripting/collider.md` – PhysicsAlso applies to: 85-90
70-71: Unify language.Avoid mixed Chinese/English in this page or provide a localized version.
Also applies to: 87-90
docs/scripting/mesh-geometry.md (4)
95-99: SubMesh arguments are index-based, not “vertex count”.addSubMesh(0, 3) is documented as “Start at vertex 0, render 3 vertices”, but SubMesh ranges are typically in index space (start, count of indices). Please correct the description and example to avoid confusion.
198-202: SkinnedMeshRenderer is used but not imported.Add the missing import for SkinnedMeshRenderer to keep the snippet self-contained.
-import { WebGLEngine, ModelMesh, PrimitiveMesh, MeshRenderer } from "@galacean/engine"; +import { WebGLEngine, ModelMesh, PrimitiveMesh, MeshRenderer, SkinnedMeshRenderer } from "@galacean/engine";
111-122: Mixed time APIs (elapsedTime vs totalTime).You use engine.time.elapsedTime and engine.time.totalTime interchangeably. Standardize on one to avoid confusion (typically totalTime for absolute animation, deltaTime for per-frame).
Also applies to: 814-825
484-493: Bounds recompute guidance is off.uploadData(true) marks CPU data as not accessible; it’s not needed to “force” bounds recompute. Bounds update on setPositions; calling uploadData with true then expecting further CPU-side edits is contradictory. Clarify the intent.
docs/scripting/meshrenderer.md (1)
394-454: Camera lookup pattern: prefer a canonical helper (or document custom search once).This recursive scene scan is heavy and duplicated across docs. If the engine exposes a recommended way (e.g., a tagged main camera or scene.find(Camera)), use it; otherwise, encapsulate this into a helper and reference it once.
docs/scripting/AudioSystem.md (1)
348-375: Autoplay policy: add a one‑liner on user gesture timing.Good coverage. Consider adding that the resume() call must be triggered within the same task of a trusted user gesture per browser policy to avoid being blocked.
docs/scripting/Loader.md (1)
175-217: resourceLoader decorator: wrong type identifier.Registering CustomAssetLoader with AssetType.Buffer will hijack Buffer loads. Use a unique type string for your custom asset and map the “custom” extension to it.
-@resourceLoader(AssetType.Buffer, ["custom"]) +@resourceLoader("CustomAsset", ["custom"], true) export class CustomAssetLoader extends Loader<CustomAsset> { constructor() { super(true); // Enable caching }docs/scripting/AnimationClip.md (1)
262-273: Expose internals cautiously.Showing _sampleAnimation internals with private naming may encourage reliance on non-API behavior. Either move to a high-level description or clearly mark it as implementation notes subject to change.
docs/scripting/AssetManagement.md (1)
95-104: Clarify whichrequestis used (top-level helper vs ResourceManager)ResourceManager does not expose a public request(); the repo exports a top-level request (packages/core/src/asset/request.ts) which supports "image" and resolves to an HTMLImageElement. Update docs/scripting/AssetManagement.md (lines 95–104) to either show the import for the helper (e.g. import { request } from '@galacean/engine-core') or replace the example with a resourceManager.load(...) usage that returns a Texture2D. Also update any docs that reference resourceManager.request (e.g. docs/scripting/Loader.md) to match the public API.
docs/scripting/clone-system.md (2)
80-87: Avoid private APIs in docs (Entity._getEntityHierarchyPath/_getEntityByHierarchyPath).These underscore-prefixed helpers are internal; recommending them in public docs is risky. Prefer a public-path approach (e.g., compute a name path and use
findByPath) or show remapping via your own helper. Example replacement:- const path: number[] = []; - if (Entity._getEntityHierarchyPath(srcRoot, this.weapon.owner, path)) { - target.weapon = new Weapon(this.weapon.id); - target.weapon.owner = Entity._getEntityByHierarchyPath(targetRoot, path); - } + const getPath = (root: Entity, node: Entity): string => { + const names: string[] = []; + for (let e: Entity | null = node; e && e !== root; e = e.parent) names.push(e.name); + return names.reverse().join("/"); + }; + const path = getPath(srcRoot, this.weapon.owner); + target.weapon = new Weapon(this.weapon.id); + target.weapon.owner = targetRoot.findByPath(path);
25-26: Clarify resource-clone guidance.Consider a one-liner noting how to deep‑clone materials/meshes properly (API calls or factory methods) to avoid accidentally duplicating GPU resources.
docs/scripting/XRManager.md (2)
413-416: Camera flags helper may not exist everywhere.
cameraManager.getIgnoreClearFlagsmight be implementation‑specific. Add a safe fallback:- return this.cameraManager.getIgnoreClearFlags(this.mainCamera.cameraType); + return this.cameraManager?.getIgnoreClearFlags?.(this.mainCamera.cameraType) + ?? CameraClearFlags.All;
339-342: Method existence checks for haptics.
controller.triggerHaptic(0.5, 100)may not be universal. Gate with capability checks in the snippet to avoid misleading readers.docs/scripting/entity.md (2)
46-48: Confirm indexed addChild overload.
addChild(0, enemy)suggests an index overload. Please verify this exists; otherwise document the actual API (addChildAt,setSiblingIndex, etc.).
101-104: Avoid referencing internal fields in public docs.Remove mention of internal
isActiveInSceneto keep the page strictly on public API.-- `isActiveInHierarchy` reflects whether all ancestors are active; `isActiveInScene` (internal) tracks scene-level activation. +- `isActiveInHierarchy` reflects whether all ancestors are active.docs/scripting/memory-management.md (6)
169-171: Typo: isLopping → isLooping.Rename the getter.
- get isLopping(): boolean { + get isLooping(): boolean { return this._loopCounter > 0; }
177-186: Use undefined for holes and maintain type safety.Setting
nullcan violateTconstraints; preferundefined.- elements[lastIndex] = null; + elements[lastIndex] = undefined as any;
159-213: DisorderedArray is missing indexOf used later.Examples call
indexOf, but the class doesn’t implement it. Add it.class DisorderedArray<T> { @@ add(element: T): void { this._elements[this.length++] = element; } + indexOf(element: T): number { + for (let i = 0; i < this.length; i++) if (this._elements[i] === element) return i; + return -1; + }
41-53: Initialize _elements in base pool.Avoid undefined access in
garbageCollection().constructor(type: new () => T) { this._type = type; + this._elements = []; }
429-449: PoolProfiler: avoid divide-by-zero in report.Guard when
getCountis 0.- console.log(`Pool ${name}: ${getCount} gets, ${createCount} creates, ${((createCount/getCount)*100).toFixed(1)}% miss rate`); + const rate = getCount ? ((createCount / getCount) * 100).toFixed(1) : '0.0'; + console.log(`Pool ${name}: ${getCount} gets, ${createCount} creates, ${rate}% miss rate`);
216-238: Sample consistency.
ComponentManagerandEntityexamples rely onindexOf(added above). Consider also showing the “store index on element” pattern (as you did in UI examples) for O(1) removals without search.docs/scripting/AnimationCurve.md (2)
291-295: Fix “CubicSpine” → “CubicSpline” (guidance).-4. **CubicSpine**: Suitable for complex curves that require smooth continuity. +4. **CubicSpline**: Suitable for complex curves that require smooth continuity.
21-35: markdownlint: add blank lines around the table.Insert a blank line before and after the table to satisfy MD058.
-### Concrete Implementation Classes -| Class | Value type | Interpolation support | Notes | +### Concrete Implementation Classes + +| Class | Value type | Interpolation support | Notes | @@ -| `AnimationRefCurve` | `ReferResource` | Step only | Switches resource references such as textures or prefabs. | +| `AnimationRefCurve` | `ReferResource` | Step only | Switches resource references such as textures or prefabs. | +docs/scripting/InputManager.md (2)
28-33: Add blank lines around the table.Surround the methods table with blank lines for markdownlint MD058.
-## Keyboard Input +## Keyboard Input + @@ -| Method | Meaning | +| Method | Meaning | @@ -| `isKeyUp(key?)` | Key transitioned to released during the current frame. | +| `isKeyUp(key?)` | Key transitioned to released during the current frame. | +
68-76: Add blank lines around the pointers field table as well.-Key fields on `Pointer`: +Key fields on `Pointer`: + @@ -| `pressedButtons` | Bit mask of all buttons currently held (`PointerButton`). | +| `pressedButtons` | Bit mask of all buttons currently held (`PointerButton`). | +docs/scripting/batching-system.md (1)
89-97: Vertex layout math is fine; add stride calculation note.36 bytes = 9 floats × 4. Consider adding this one-liner to prevent confusion.
Also applies to: 109-116
docs/scripting/advanced-rendering.md (2)
247-250: Texture2DArray WebGL2 guard is good; also mention feature detection helper if available.Minor doc enhancement.
101-126: Unify MSAASamples usage — remove doc-local enum and use the canonical enum everywhereRepository already defines the canonical enum at packages/core/src/enums/MSAASamples.ts; Camera is typed to that enum, but the docs duplicate the enum and some code/tests use raw numeric literals. Replace duplicates and numeric literals with the enum and ensure the Camera public API enforces/accepts MSAASamples.
- docs/scripting/advanced-rendering.md (lines 101–126): remove the inline enum; import and use MSAASamples from packages/core/src/enums/MSAASamples.ts.
- e2e/case/multi-camera-no-clear.ts (lines ~52, ~72): replace camera.msaaSamples = 1 with camera.msaaSamples = MSAASamples.None.
- packages/core/src/RenderPipeline/BasicRenderPipeline.ts (lines ~102, ~109): replace numeric checks (msaaSamples === 1) with msaaSamples === MSAASamples.None for clarity.
- packages/core/src/Camera.ts (line ~148): already uses MSAASamples (private _msaaSamples); make the public setter/signature strictly accept MSAASamples (or add a runtime assertion) so callers don’t pass raw numbers.
docs/scripting/camera.md (2)
86-97: Missing imports and undefined variables.Add imports for HitResult and Layer; also declare
inputManager = engine.inputManagerbefore use.-import { Vector2, Vector3, Ray } from "@galacean/engine-math"; +import { Vector2, Vector3, Ray } from "@galacean/engine-math"; +import { HitResult, Layer } from "@galacean/engine"; @@ -const mousePosition = new Vector2(inputManager.pointers[0].position.x, inputManager.pointers[0].position.y); +const inputManager = engine.inputManager; +const mousePosition = new Vector2(inputManager.pointers[0].position.x, inputManager.pointers[0].position.y); @@ -if (scene.physics.raycast(ray, Number.MAX_VALUE, Layer.Default, hitResult)) { +if (scene.physics.raycast(ray, Number.MAX_VALUE, Layer.Layer0, hitResult)) {
150-158: MSAA type consistency.This page uses a raw number; other pages use
MSAASamples. Unify the type shown to users.Also applies to: 226-228
docs/scripting/background-system.md (2)
49-56: Missing imports (AssetType).Examples use AssetType without importing it.
-import { BackgroundMode, SkyBoxMaterial, TextureCube } from "@galacean/engine"; +import { BackgroundMode, SkyBoxMaterial, TextureCube, AssetType } from "@galacean/engine"; @@ -import { BackgroundMode, BackgroundTextureFillMode, Texture2D } from "@galacean/engine"; +import { BackgroundMode, BackgroundTextureFillMode, Texture2D, AssetType } from "@galacean/engine";Also applies to: 84-93
169-172: Avoid private canvas hooks (_sizeUpdateFlagManager).Recommend a public resize event or a window ResizeObserver example.
- this.engine.canvas._sizeUpdateFlagManager.addListener(() => { + window.addEventListener("resize", () => { this.updateBackgroundForDevice(); - }); + });docs/scripting/engine.md (2)
313-329: Mark forceLoseDevice/forceRestoreDevice as testing/internal-only in docs and APIThey are public helpers to simulate device loss (packages/core/src/Engine.ts:401,409; implemented in packages/rhi-webgl/src/WebGLGraphicDevice.ts:535,540) and are only used in tests/examples (tests/src/rhi-webgl/WebGLEngine.test.ts; examples/src/device-restore.ts); update the docs snippet to state they are for testing-only and add a JSDoc/@internal marker on the Engine methods.
60-69: Use the WebGLMode enum (not string literals) for webGLModewebGLMode is typed as WebGLMode — replace
webGLMode: "auto"withwebGLMode: WebGLMode.Autoand import/qualify WebGLMode as needed (examples/tests useWebGLMode.*).
File: docs/scripting/engine.md (lines 60–69)docs/scripting/lighting.md (6)
18-23: Add missing imports in Quick Start.Vector3 is used later but not imported.
-import { WebGLEngine, DirectLight, PointLight, SpotLight, AmbientLight, DiffuseMode, ShadowType } from "@galacean/engine"; +import { WebGLEngine, DirectLight, PointLight, SpotLight, AmbientLight, DiffuseMode, ShadowType, Vector3 } from "@galacean/engine";
206-233: TextureCube example likely needs format/import fixes.TextureFormat.R8G8B8 may be invalid; commonly R8G8B8A8 is supported. Also add TextureCubeFace to imports.
-import { ... TextureCube } from "@galacean/engine"; +import { ... TextureCube, TextureFormat, TextureCubeFace } from "@galacean/engine"; -const envTexture = new TextureCube(engine, 512, TextureFormat.R8G8B8); +const envTexture = new TextureCube(engine, 512, TextureFormat.R8G8B8A8);
730-740: Remove undefined variable usage in debug snippet.activePasses is referenced but never defined. Either show how to obtain it or drop the log.
- console.log("- Active passes:", activePasses.length); + // TODO: expose active passes via a public API before logging themAlso applies to: 871-876
250-255: Shadow distance property name inconsistent across docs.This page uses engine.shadowManager.maxDistance; performance-optimization.md uses engine.shadowManager.shadowDistance. Unify on the actual API name.
Also applies to: 716-721
290-314: AO API may not live on scene directly.scene.ambientOcclusion and AmbientOcclusionQuality enums need confirmation; Post-processing docs suggest AO is managed via the PostProcess pipeline. Align with the real surface.
Also applies to: 315-353
146-162: Verify advanced light matrices API.light.viewMatrix/inverseViewMatrix look internal. Document only if public/stable, or move to an “Advanced/Internal” note.
docs/scripting/PostProcess.md (4)
23-31: Import omissions in Quick Start.WebGLEngine and PostProcess are used but not imported.
-import { BloomEffect, TonemappingEffect, TonemappingMode } from "@galacean/engine"; +import { WebGLEngine, PostProcess, BloomEffect, TonemappingEffect, TonemappingMode } from "@galacean/engine";
670-681: Undefined variable in CustomPass example.postProcessManager is used without being defined in scope.
- override onRender(camera: Camera, srcTexture: Texture2D, destTarget: RenderTarget): void { - const material = this.createMaterial(); - const effect = postProcessManager.getBlendEffect(CustomEffect); + override onRender(camera: Camera, srcTexture: Texture2D, destTarget: RenderTarget): void { + const material = this.createMaterial(); + const postProcessManager = camera.scene.postProcessManager; + const effect = postProcessManager.getBlendEffect(CustomEffect);
631-640: Don’t document underscored/internal methods._postfix methods (_update, _render, _isValid) shouldn’t be in public docs unless officially supported. Move to an internal notes section or remove.
Also applies to: 969-977
853-876: Undefined variable usage in debug snippet.activePasses referenced though retrieval is commented out. Remove the log or show a public API to access it.
- console.log("- Active passes:", activePasses.length); + // TODO: expose active passes info via public API before loggingdocs/scripting/Joint.md (2)
46-56: Fix table cell parsing (MD056: extra columns).Inline types with “|” split the table. Escape pipes or rephrase to avoid extra columns.
-| `connectedCollider` | `Collider | null` | Target collider. `null` means the anchors are interpreted in world space. | +| `connectedCollider` | `Collider | null` | Target collider. `null` means the anchors are interpreted in world space. |(Repeat for any “| null” types in this table.)
87-97: Fix table cell parsing for HingeJoint types.Escape the “|” in
JointMotor | nullandJointLimits | null.-| `motor` | `JointMotor | null` | ... -| `limits` | `JointLimits | null` | ... +| `motor` | `JointMotor | null` | ... +| `limits` | `JointLimits | null` | ...docs/scripting/engine-configuration.md (1)
84-88: Flagging internal options._forceFlush and _maxAllowSkinUniformVectorCount look internal. Mark them experimental or move out of public surface to avoid locking in.
docs/scripting/PhysicsScene.md (1)
9-17: Add language to fenced code block (MD040).Specify a language to satisfy linters; use text for diagrams.
-``` +```text Scene ↓ PhysicsScene (Physics World Manager) ...docs/scripting/performance-optimization.md (1)
716-729: Shadow distance property name inconsistent across docs.Here: shadowDistance; in lighting.md: maxDistance. Align with the actual API.
Also applies to: 250-255
docs/scripting/Collider.md (1)
9-15: Add language to fenced code block (MD040).Specify text for the class hierarchy diagram.
-``` +```text Component ↓ Collider (Abstract Base Class) ...docs/scripting/environment-probe.md (1)
217-233: Emphasize capture throttling.Add a note that leaving probes enabled captures every frame; recommend disabling after capture for static scenes (you already do this in ProbeManager—surface it earlier).
Also applies to: 239-260
docs/scripting/Animator.md (2)
56-57: Clarify trigger parameter auto-reset behavior.The documentation states that triggers auto-reset but doesn't specify when this occurs. This is important for understanding trigger lifecycle.
Consider adding clarification about when triggers auto-reset:
- Triggers are just boolean parameters flagged as trigger; `activateTriggerParameter` writes `true`, `deactivateTriggerParameter` resets it to `false`. + Triggers are boolean parameters that auto-reset to `false` after being consumed by a transition. `activateTriggerParameter` writes `true`, `deactivateTriggerParameter` manually resets it to `false`.
163-168: Import statement inconsistency.The advanced section imports
AnimatorConditionModeseparately, but the main example doesn't include it. This creates inconsistency in documentation patterns.Consider using consistent import patterns throughout the document, either importing everything needed upfront or consistently showing imports for each code section.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (40)
docs/scripting/AnimationClip.md(1 hunks)docs/scripting/AnimationCurve.md(1 hunks)docs/scripting/Animator.md(1 hunks)docs/scripting/AssetManagement.md(1 hunks)docs/scripting/AudioSystem.md(1 hunks)docs/scripting/Collider.md(1 hunks)docs/scripting/InputManager.md(1 hunks)docs/scripting/Joint.md(1 hunks)docs/scripting/Loader.md(1 hunks)docs/scripting/Math.md(1 hunks)docs/scripting/ParticleSystem.md(1 hunks)docs/scripting/PhysicsScene.md(1 hunks)docs/scripting/PostProcess.md(1 hunks)docs/scripting/Shadow.md(1 hunks)docs/scripting/Sprite.md(1 hunks)docs/scripting/Text.md(1 hunks)docs/scripting/XRManager.md(1 hunks)docs/scripting/advanced-rendering.md(1 hunks)docs/scripting/background-system.md(1 hunks)docs/scripting/base-systems.md(1 hunks)docs/scripting/batching-system.md(1 hunks)docs/scripting/build-development-tools.md(1 hunks)docs/scripting/camera.md(1 hunks)docs/scripting/clone-system.md(1 hunks)docs/scripting/component-dependencies.md(1 hunks)docs/scripting/component.md(1 hunks)docs/scripting/engine-configuration.md(1 hunks)docs/scripting/engine-scene.md(1 hunks)docs/scripting/engine.md(1 hunks)docs/scripting/entity.md(1 hunks)docs/scripting/environment-probe.md(1 hunks)docs/scripting/graphics-2d.md(1 hunks)docs/scripting/layer-system.md(1 hunks)docs/scripting/lighting.md(1 hunks)docs/scripting/material.md(1 hunks)docs/scripting/memory-management.md(1 hunks)docs/scripting/mesh-geometry.md(1 hunks)docs/scripting/meshrenderer.md(1 hunks)docs/scripting/performance-optimization.md(1 hunks)docs/scripting/physics.md(1 hunks)
🧰 Additional context used
🪛 markdownlint-cli2 (0.17.2)
docs/scripting/physics.md
12-12: Unordered list indentation
Expected: 2; Actual: 4
(MD007, ul-indent)
13-13: Unordered list indentation
Expected: 2; Actual: 4
(MD007, ul-indent)
16-16: Unordered list indentation
Expected: 2; Actual: 4
(MD007, ul-indent)
17-17: Unordered list indentation
Expected: 2; Actual: 4
(MD007, ul-indent)
docs/scripting/Collider.md
9-9: Fenced code blocks should have a language specified
(MD040, fenced-code-language)
docs/scripting/AnimationCurve.md
21-21: Tables should be surrounded by blank lines
(MD058, blanks-around-tables)
docs/scripting/Joint.md
48-48: Table column count
Expected: 3; Actual: 4; Too many cells, extra data will be missing
(MD056, table-column-count)
95-95: Table column count
Expected: 3; Actual: 4; Too many cells, extra data will be missing
(MD056, table-column-count)
96-96: Table column count
Expected: 3; Actual: 4; Too many cells, extra data will be missing
(MD056, table-column-count)
docs/scripting/Math.md
9-9: Fenced code blocks should have a language specified
(MD040, fenced-code-language)
docs/scripting/PhysicsScene.md
9-9: Fenced code blocks should have a language specified
(MD040, fenced-code-language)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
- GitHub Check: e2e (22.x, 3/4)
- GitHub Check: e2e (22.x, 4/4)
- GitHub Check: codecov
🔇 Additional comments (63)
docs/scripting/Text.md (2)
99-118: Confirmed: Font.createFromOS exists & Font resources are reference-counted
Font.createFromOS(engine, name) is documented; Font assets are cached by the ResourceManager with reference-counting and can be released via engine.resourceManager.gc(). System fonts are not guaranteed across platforms—add fallbacks or bundle fonts if deterministic availability is required.
285-310: Confirm TextUtils public API vs doc-only helpers.Official TextUtils provides measureText, updateText, textContext and TextMetrics; the snippet uses measureChar / getNativeFontString (and mentions measureTextWithWrap / measureFont) which are not part of the documented engine surface — replace with measureText + TextMetrics/updateText or mark those functions as doc-only helpers. File: docs/scripting/Text.md (lines 285–310).
docs/scripting/Math.md (1)
239-287: Confirm or replace illustrative math APIs in Math.mdFindings: @galacean/engine does export Matrix3x3, Matrix (4×4), Quaternion (rotationYawPitchRoll/rotationEuler/rotationX/Y/Z and conversions), Vector2/3/4, MathUtil, Plane, Ray, BoundingBox/BoundingSphere/BoundingFrustum and CollisionUtil — but Color has no documented HSV helpers and classes like FastMath/SpatialMath appear illustrative.
Action: keep examples that use real APIs; replace Color.fromHSV/other non‑documented helpers and illustrative classes with actual API calls or mark them explicitly as pseudocode.Applies to: docs/scripting/Math.md lines 239–287, 540–600, 671–714, 921–927.
docs/scripting/physics.md (1)
69-70: Double‑check WASM filename/path guidance and add bundler copy examples.
- Docs currently claim
physx.release.wasmlives at node_modules/@galacean/engine-physics-physx/libs — verify and replace with a general, accurate line: "The PhysX WASM binary (commonly named physx.wasm or physx.release.wasm) is shipped in the package (often under wasm/, libs/ or dist/). Copy the .wasm file from the package into your app's public/static output at build time so it can be fetched at runtime."- Add minimal bundler copy examples (patterns only): Webpack (copy-webpack-plugin) — from
node_modules/@galacean/engine-physics-physx/wasm/*.wasm→wasm/[name][ext]; Vite (vite-plugin-static-copy) — srcnode_modules/@galacean/engine-physics-physx/wasm/*.wasm→ destwasm.- Confirm the package version or attach package.json to pin the exact filename/path in the docs.
docs/scripting/base-systems.md (2)
39-47: Confirm engine event names.Verify the Engine actually emits the exact strings "run", "shutdown", "devicelost", and "devicerestored". If any differ, either correct the literals in the doc or mark the list as examples.
32-38: Verify EventDispatcher API names/signatures.Docs/examples use .on(...) and .dispatch(...). (galacean.antgroup.com) Confirm the exact public SDK method names/signatures for: on, once, off, removeAllEventListeners(event?), hasEvent | hasListener | hasEventListener, eventNames, listenerCount, and dispatch(event, data?) — update docs if any names or signatures differ.
docs/scripting/AssetManagement.md (2)
145-145: Stray control character in footnote.The line starts with a non-printable char before “*Caching…”. Remove it to avoid rendering glitches.
[raise_nitpick_refactor]-�*Caching is determined by the loader. Built-in Text/JSON/Buffer loaders opt out of caching; all other shipped loaders set `useCache = true`. +*Caching is determined by the loader. Built-in Text/JSON/Buffer loaders opt out of caching; all other shipped loaders set `useCache = true`.
60-62: getAssetPath exists and expects a numeric instanceId (internal id)packages/core/src/asset/ResourceManager.ts:132 — getAssetPath(instanceId: number): string. Use the internal numeric instanceId (not a URL).
docs/scripting/material.md (3)
246-261: Per‑pass setters exist in BaseMaterial — no change required.setIsTransparent (packages/core/src/material/BaseMaterial.ts:143), setBlendMode (…:172) and setRenderFace (…:202) are implemented; call sites at lines 63, 91, 119, 244 — using material.setIsTransparent(0,..) / setBlendMode(0,..) / setRenderFace(0,..) is valid.
235-236: Incorrect — example is valid; enableMacro accepts ShaderMacroThe call shaderData.enableMacro(ShaderMacro.getByName("POINT_LIGHT_COUNT","4")) is valid — ShaderData.enableMacro has overloads for (name[, value]) and (ShaderMacro) (strings are converted via ShaderMacro.getByName). For consistency with most call sites you can use shaderData.enableMacro("POINT_LIGHT_COUNT", "4").
Likely an incorrect or invalid review comment.
134-161: Confirm advanced PBR properties are implemented or mark them ExperimentalDocs list clearCoat*, sheen*, anisotropy*, transmission/refraction on PBRMaterial — verification in the sandbox produced no code hits. Manually confirm these properties exist on the shipped PBRMaterial API (and which version added them); if they are not universally available, move this content to an "Experimental/Planned" section or add explicit version/gating notes.
File: docs/scripting/material.md (lines 134–161)docs/scripting/graphics-2d.md (2)
150-188: Confirm TextRenderer API names (enableWrapping, overflowMode, lineSpacing) — verified. Property names and related enums (OverflowMode, TextHorizontalAlignment, TextVerticalAlignment, FontStyle) match the Galacean Engine docs. (galacean.antgroup.com)
76-80: Incorrect — atlasRegion / atlasRegionOffset / atlasRotated are public APIThese properties have public getters/setters in packages/core/src/2d/sprite/Sprite.ts, are used by packages/loader/src/SpriteAtlasLoader.ts, packages/core/src/2d/sprite/SpriteRenderer.ts and UI Image, and are covered by tests (tests/src/core/Sprite.test.ts); keep them documented unless you intend an API change.
Likely an incorrect or invalid review comment.
docs/scripting/mesh-geometry.md (1)
149-160: Incorrect — ModelMesh supports both overloads of setVertexBufferBindingModelMesh and BufferMesh declare two public overloads: setVertexBufferBinding(vertexBuffer: Buffer, stride: number, index?: number) and setVertexBufferBinding(vertexBufferBinding: VertexBufferBinding, index?: number). Primitive exposes setVertexBufferBinding(index: number, binding: VertexBufferBinding). The docs example mesh.setVertexBufferBinding(posBuffer, 12, 0) is valid and no additional VertexBufferBinding import is required. See packages/core/src/mesh/ModelMesh.ts (overloads at ~502–515), packages/core/src/mesh/BufferMesh.ts (~52–64), and packages/core/src/graphic/Primitive.ts (index-first API at ~106).
Likely an incorrect or invalid review comment.
docs/scripting/AnimationClip.md (1)
129-147: Verify or remove method-call path examples with $valueThe Property Path Syntax section in docs/scripting/AnimationClip.md (approx. lines 129–147) includes examples like "setPosition('x', $value)". No code evidence of path-parser support for method-call bindings was found; document these only if the parser actually implements method-call setters — otherwise remove or mark them as editor-only to avoid misuse.
docs/scripting/Loader.md (1)
108-115: primitive:// URL scheme is implemented — no change required. PrimitiveMeshLoader handles primitive:// URLs and maps them to PrimitiveMesh.create* (see packages/loader/src/PrimitiveMeshLoader.ts); the docs example (docs/scripting/Loader.md, lines 108–115) is correct.docs/scripting/meshrenderer.md (2)
320-331: Bounds API is getCenter/getExtent (singular) — no change requiredVerified: BoundingBox defines getCenter(out: Vector3) and getExtent(out: Vector3); docs and tests use these exact names (packages/math/src/BoundingBox.ts:143; docs/scripting/meshrenderer.md:321–323).
Likely an incorrect or invalid review comment.
183-188: ModelMesh.calculateTangents exists — keep the explicit uploadData call.ModelMesh.calculateTangents() is defined (packages/core/src/mesh/ModelMesh.ts:679) and is invoked from PrimitiveMesh (packages/core/src/mesh/PrimitiveMesh.ts:1418). Leave mesh.uploadData(false) after calculateTangents(); if you want to avoid the separate upload step, move the upload into calculateTangents or provide a helper that computes tangents and uploads.
docs/scripting/AudioSystem.md (1)
9-24: Audio API exists in engine — no doc change requiredAudioManager, AudioSource and AudioClip and the referenced members (playOnEnabled, playbackRate, mute, time, isAudioContextRunning, getGainNode, getContext) are implemented in the engine — see packages/core/src/audio/AudioManager.ts, packages/core/src/audio/AudioSource.ts, packages/core/src/audio/AudioClip.ts (tests: tests/src/core/audio/AudioSource.test.ts).
docs/scripting/clone-system.md (1)
38-49: Confirm decorator exports and TS config.Verify
ignoreClone,shallowClone,deepCloneare exported from@galacean/engineand note thatexperimentalDecoratorsmust be enabled in tsconfig for these examples to work.docs/scripting/XRManager.md (1)
1-849: Overall XR docs read well.Comprehensive and coherent. With the small fixes above, this will be very useful.
docs/scripting/entity.md (1)
1-234: Solid coverage.Examples and API summary are clear and actionable.
docs/scripting/ParticleSystem.md (2)
303-306: Constructor shape of ParticleCompositeCurve.Examples use numeric min/max constructor overloads. Please confirm the actual API supports this shorthand; otherwise, show explicit
mode+ constants/curves construction.
1-388: Good coverage.Clear structure and practical examples.
docs/scripting/InputManager.md (1)
1-185: Good doc.Clear and practical guidance; examples map well to engine usage.
docs/scripting/build-development-tools.md (2)
30-46: Confirmed: rollup plugins and dev server port are correct.rollup.config.js imports @rollup/plugin-node-resolve, @rollup/plugin-commonjs, ./rollup-plugin-glsl, rollup-plugin-serve, @rollup/plugin-replace, rollup-plugin-swc3 and rollup-plugin-jscc; serve() is configured with port: 9999 (imports at rollup.config.js lines 4–10; serve config around lines 56–58).
8-27: Verified: documented pnpm scripts match package.jsonAll scripts referenced in the docs (dev, watch, watch:umd, build, b:module, b:umd, b:types, b:all, clean, lint, test, coverage, e2e, e2e:debug, examples, release) are present in the workspace package.json; "pnpm install" is a CLI command (not a package script).
docs/scripting/background-system.md (2)
237-245: Good memory hygiene snippet.Keeping explicit destroy() and clearing references is solid.
61-72: SkyProceduralMaterial is present in the core package — no change required. Exported in packages/core/src/sky/index.ts and implemented at packages/core/src/sky/SkyProceduralMaterial.ts.docs/scripting/layer-system.md (3)
41-52: Masks and helpers section is clear.Concise guidance on bitwise ops; keep it.
71-86: Keep postProcessMask doc; remove/rephrase the LightManager 32→16 implementation detail.Camera.postProcessMask is a public API used by PostProcessManager — keep that sentence. The 32→16 culling-mask split is implemented (packages/core/src/lighting/LightManager.ts and per-light code in DirectLight.ts / PointLight.ts / SpotLight.ts) but is an internal implementation detail — drop or rephrase in docs to avoid leaking internals.
Likely an incorrect or invalid review comment.
92-118: Collision-layer API names & mask behavior verifiedDynamicCollider exists; PhysicsScene exposes setColliderLayerCollision/getColliderLayerCollision; raycast/overlap APIs accept a layer mask (bitwise OR of Layer values) for filtering. Collider.collisionLayer, however, only accepts a single layer (power-of-two) and will throw if given a combined mask.
docs/scripting/advanced-rendering.md (2)
34-57: Incorrect — enum names in docs match the codebase.
The repo defines/uses TextureFormat.R11G11B10_UFloat, R16G16B16A16, R32G32B32A32 (see packages/core/src/texture/enums/TextureFormat.ts) and Camera.ts already uses these constants (packages/core/src/Camera.ts ~lines 782–784). No change required.Likely an incorrect or invalid review comment.
131-145: Clarify RenderTarget constructor overloads (depth arg may be Texture2D or depth-format enum).Docs show the depth attachment as a TextureFormat, but the codebase also calls RenderTarget with a Texture2D and with RenderBufferDepthFormat/TextureFormat in different places — update the doc snippet to match the actual constructor overload(s) (or document both overloads) to avoid misleading users.
Check/update: docs/scripting/advanced-rendering.md (131-145) and caller sites: packages/core/src/texture/RenderTarget.ts, packages/core/src/RenderPipeline/PipelineUtils.ts, tests/src/core/texture/RenderTarget.test.ts, examples/src/screenshot.ts.
docs/scripting/engine.md (4)
285-306: Engine-level post-process API exists — original concern incorrect.
PostProcessPass and engine-level APIs are implemented in packages/core (packages/core/src/postProcess/PostProcessPass.ts and packages/core/src/Engine.ts) and exercised by tests (tests/src/core/postProcess/PostProcessPass.test.ts, tests/src/core/postProcess/PostProcess.test.ts) and e2e (e2e/case/postProcess-customPass.ts).Likely an incorrect or invalid review comment.
343-346: Ignore —rootEntitiesCountexists; no change required.
Scene exposes get rootEntitiesCount(): number (packages/core/src/Scene.ts:235–237) and tests reference it (tests/src/core/Scene.test.ts:202).Likely an incorrect or invalid review comment.
262-280: Confirmed — Engine exposes these events and the callback receives the engine instance.Engine dispatches "devicelost" / "devicerestored" with the engine as payload (packages/core/src/Engine.ts:641, 661); tests/examples attach listeners with engine.on / engine.once (tests/src/rhi-webgl/WebGLEngine.test.ts:83–84, tests/src/core/DeviceLost.test.ts:63–69, examples/src/device-restore.ts:32–39).
82-84: physicsManager.initialize expects the physics class (constructor); await it and pass wasmPath for PhysXinitialize(physics: IPhysics, options?: any): Promise — pass the class (LitePhysics / PhysXPhysics). For PhysX the call should be awaited and include wasmPath. Update docs/scripting/engine.md (L82–84):
Replace:
engine.physicsManager.initialize(PhysXPhysics);With:
await engine.physicsManager.initialize(PhysXPhysics, { wasmPath: "/path/to/physx.release.wasm" });Likely an incorrect or invalid review comment.
docs/scripting/engine-scene.md (2)
147-158: Ambient occlusion API verified — no change required.
scene.ambientOcclusion is a Scene property (packages/core/src/Scene.ts), AmbientOcclusion and AmbientOcclusionQuality are exported (packages/core/src/lighting/index.ts), and the feature is used by ScalableAmbientObscurancePass.ts and BasicRenderPipeline.ts and exercised in e2e/case/camera-ssao.ts.
189-205: engine.renderCount is internal; forceLoseDevice/forceRestoreDevice are public (simulation-only)
- engine.renderCount is not a public API — the runtime uses engine._renderCount internally (see packages/core/src/RenderPipeline/RenderQueue.ts). Update the docs to reference engine._renderCount or add a public getter before documenting engine.renderCount.
- engine.forceLoseDevice() / engine.forceRestoreDevice() are public Engine methods (packages/core/src/Engine.ts) and implemented in packages/rhi-webgl/src/WebGLGraphicDevice.ts; examples/tests call them (examples/src/device-restore.ts, tests/src/rhi-webgl/WebGLEngine.test.ts). Document them only as simulation/testing helpers (not required in normal projects).
Likely an incorrect or invalid review comment.
docs/scripting/batching-system.md (3)
212-236: Docs: use public ShaderTagKey and guard shaderPasses (docs/scripting/batching-system.md:212-236)shaderPasses is a public ReadonlyArray on SubRenderElement and tag APIs are public; replace the literal "DisableBatch" with ShaderTagKey.getByName("spriteDisableBatching") (or the BatchUtils constant) and add a null/length check before accessing shaderPasses[0].
Likely an incorrect or invalid review comment.
36-55: RenderQueueType: docs and implementation mismatch — fix enum or docs.RenderQueueType is defined at packages/core/src/shader/enums/RenderQueueType.ts and exported from packages/core/src/shader/index.ts; it is declared without explicit numeric assignments (so it uses TypeScript’s default 0,1,2), not 1000/2000/3000. Update the docs to match the actual enum values or add explicit numeric values to the enum and audit all consumers (changing these values is API‑breaking).
363-383: SetDataOptions.Discard and Buffer.setData parameter order are correct. Buffer.setData signature is (data, bufferByteOffset, dataOffset, dataLength, options) and GLBuffer checks SetDataOptions.Discard — the snippet matches the codebase (packages/core/src/graphic/Buffer.ts, packages/rhi-webgl/src/GLBuffer.ts, packages/core/src/RenderPipeline/PrimitiveChunk.ts).docs/scripting/camera.md (1)
162-164: isAlphaOutputRequired — name/behavior verified (no change needed)
Camera.ts defines isAlphaOutputRequired = false and _getInternalColorTextureFormat() picks R11G11B10_UFloat only when HDR && engine._hardwareRenderer.isWebGL2 && !isAlphaOutputRequired; otherwise it uses RGBA R16G16B16A16, so setting camera.isAlphaOutputRequired = true forces RGBA. See packages/core/src/Camera.ts:110, 781.docs/scripting/Shadow.md (2)
262-290: Confirm shadow macros/params exist before publishing.Sandbox search returned no matches for SHADOW_VSM, PCSS_SHADOWS, CONTACT_SHADOWS or shadow-related shader params; cannot verify implementation — ensure the macros and shader uniforms used in the snippet (shadowPCFKernel, shadowMapTexelSize, shadowMinVariance, shadowLightBleedingReduction, contactShadowLength, contactShadowDistanceScaleFactor, contactShadowSampleCount) are defined and referenced in shader code/runtime or update the docs.
Location: docs/scripting/Shadow.md lines 262–290; also applies to 439–465 and 470–502.
662-668: Defaults verified — castShadows = true, receiveShadows = true.
Defined on Renderer: castShadows = true (packages/core/src/Renderer.ts:122), _receiveShadows = true (packages/core/src/Renderer.ts:87); MeshRenderer extends Renderer (packages/core/src/mesh/MeshRenderer.ts:13).docs/scripting/lighting.md (1)
102-106: Confirm point/spot shadow support.Examples set shadowType on PointLight/SpotLight. If unsupported, mark as “directional only” or add caveats.
docs/scripting/PostProcess.md (2)
75-81: camera.postProcessMask needs confirmation.Ensure this property exists and is the intended way to filter post-processing by layer.
928-937: removeEffect return type.Docs say removeEffect returns the instance; many APIs return void/boolean. Confirm and correct if needed.
docs/scripting/Joint.md (1)
63-69: Use Vector3.set for consistency.Elsewhere docs use .set(x,y,z). Replace setValue with set.
[raise_nitpick_refactor]-joint.anchor.setValue(0, 0.5, 0); +joint.anchor.set(0, 0.5, 0); ... -joint.connectedAnchor.setValue(0, -0.5, 0); +joint.connectedAnchor.set(0, -0.5, 0);docs/scripting/engine-configuration.md (1)
258-266: Event names verification.engine.on('devicelost'/'devicerestored') may differ from actual emitter names. Confirm and align.
docs/scripting/environment-probe.md (2)
346-358: onBeginRender hook usage.Confirm Script.onBeginRender is the intended/public hook for per-camera updates; if not, switch to a supported callback.
Also applies to: 371-379
221-232: Minor: add imports where used.Vector3 is used in resolution and blending examples but not imported.
[raise_nitpick_refactor]-import { CubeProbe, Entity } from '@galacean/engine'; +import { CubeProbe, Entity, Vector3 } from '@galacean/engine';Also applies to: 265-289
docs/scripting/Animator.md (10)
1-14: Well-structured overview with good architectural breakdown.The overview clearly explains the Animator's role and the core architecture section provides excellent context for understanding the system hierarchy. The component relationships are well-defined.
18-28: API documentation is clear and well-organized.The property documentation effectively explains each field's purpose and includes helpful defaults and behavioral notes.
32-40: Clarify the "first frame" behavior for manual playback calls.The note about playing the first frame with
deltaTime = 0when called from script is unclear. This seems to suggest potential timing issues or frame-skipping behavior that developers should be aware of.Could you clarify what "to avoid skipping" means in this context? Does this mean:
- The animator immediately evaluates one frame to show the transition?
- There's a potential race condition with the engine's update loop?
- This prevents missing the first frame of a transition?
Understanding this behavior is important for developers who need precise animation timing control.
194-222: Excellent detailed transition configuration examples.This section provides comprehensive examples of transition setup with conditions, timing, and blending parameters. The multi-condition example is particularly valuable.
370-426: Excellent StateMachineScript implementation example.This provides a comprehensive example of state lifecycle management with practical use cases like weapon trails, hit detection, and parameter management. The code structure and logic flow are well-designed.
144-149: Valuable best practices section.The best practices provide actionable guidance for performance, organization, and correct usage patterns. These recommendations align well with typical animation system optimization strategies.
150-155: Important operational notes.The notes about threading, culling, reference counting, and script lifecycle provide crucial information for production usage and memory management.
270-281: AnimatorLayerMask API verified — docs match the implementation.createByEntity(entity) exists and populates path masks, setPathMaskActive(path, active, includeChildren) is present and used in tests, and AnimatorControllerLayer.mask accepts an AnimatorLayerMask. No documentation change required.
312-325: Animation events API — verified.Supports both patterns: AnimationEvent class (packages/core/src/animation/AnimationEvent.ts) and AnimationClip.addEvent overloads (packages/core/src/animation/AnimationClip.ts) — accepts either an AnimationEvent or (functionName, time, parameter).
327-342: Animation events invoke Script methods on the Animator's entity — keeping CharacterController extends Script is correct.
- Animator builds event handlers from Script components on the Animator's entity (Animator._saveAnimatorEventHandlers uses this._entity.getComponents(Script) and binds script[functionName]). — packages/core/src/animation/Animator.ts.
- StateMachineScript is separate (onStateEnter/onStateUpdate/onStateExit) and is not used for AnimationEvent dispatch. — packages/core/src/animation/StateMachineScript.ts.
- Ensure the script with the handler is added to the same entity that has the Animator (AnimationClip.addEvent dispatches _updateFlagManager so Animator rebuilds handlers). — packages/core/src/animation/AnimationClip.ts, packages/core/src/animation/Animator.ts.
| const rhi = engine._hardwareRenderer; | ||
| const supportsHDR = rhi.isWebGL2 || rhi.canIUse(GLCapabilityType.textureHalfFloat); | ||
|
|
||
| if (!supportsHDR) { | ||
| console.warn("HDR not supported on this device"); | ||
| camera.enableHDR = false; | ||
| } | ||
| ``` |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
🧩 Analysis chain
Avoid using _hardwareRenderer in public docs.
Replace with supported capability checks or move to “internal details.”
🏁 Script executed:
#!/bin/bash
rg -nP --type=ts '_hardwareRenderer|GLCapabilityType\.textureHalfFloat'Length of output: 8671
Avoid referencing internal engine._hardwareRenderer in public docs.
Replace the snippet in docs/scripting/advanced-rendering.md (lines 20–27) with public capability checks or move it to an "Internal details" section — it references a private API (see packages/core/src/Camera.ts:392).
| #### Animation Event Management | ||
| ```typescript | ||
| // Add an animation event - created via parameters | ||
| addEvent(functionName: string, time: number, parameter: Object | undefined): void | ||
|
|
||
| // Add an animation event - by passing the event object directly | ||
| addEvent(event: AnimationEvent): void | ||
|
|
||
| // Clear all events | ||
| clearEvents(): void | ||
|
|
||
| // Example usage | ||
| clip.addEvent("onFootStep", 0.5, { footIndex: 0 }); | ||
| clip.addEvent("onAttackHit", 0.8, { damage: 50 }); | ||
| clip.addEvent("onJumpLand", 1.1, undefined); // Explicitly pass undefined when no payload is needed | ||
| ``` |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
🧩 Analysis chain
APIs and overloads need hard verification.
addEvent(functionName, time, parameter), multiple addCurveBinding overloads (with get/set paths and componentIndex) and the AnimationEvent/Binding shapes look more extensive than typical. Confirm all overloads and field names exist publicly; otherwise, scope to the supported forms.
Also applies to: 52-90, 92-127
🏁 Script executed:
#!/bin/bash
rg -nP --type=ts "\\bclass\\s+AnimationClip\\b.*?(addEvent|addCurveBinding|clearCurveBindings|events\\b|curveBindings\\b)" -nPU -C2
rg -nP --type=ts "\\binterface\\s+AnimationEvent\\b|\\bclass\\s+AnimationEvent\\b" -nPU -C2Length of output: 833
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "rg version:"
rg --version || true
echo
echo "Searching for 'class AnimationClip'..."
rg -n --type ts -C2 'class\s+AnimationClip\b' || true
echo
echo "Searching for addEvent / addCurveBinding / clearEvents / clearCurveBindings / events / curveBindings..."
rg -n --type ts -C2 '\b(addEvent|addCurveBinding|clearEvents|clearCurveBindings|events|curveBindings)\b' || true
echo
echo "Searching for AnimationEvent interface/class..."
rg -n --type ts -C2 '\b(interface|class)\s+AnimationEvent\b' || trueLength of output: 31019
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "=== AnimationEvent.ts ==="
sed -n '1,200p' packages/core/src/animation/AnimationEvent.ts || true
echo
echo "=== AnimationClip.ts addCurveBinding overloads ==="
sed -n '100,200p' packages/core/src/animation/AnimationClip.ts || trueLength of output: 5166
APIs verified — docs/typing mismatch for addEvent parameter
- Confirmed: AnimationClip exposes both overloads (addEvent(functionName: string, time: number, parameter: Object) and addEvent(event: AnimationEvent)) and the implementation accepts an optional parameter. (packages/core/src/animation/AnimationClip.ts)
- Confirmed: AnimationEvent has fields time, functionName, parameter. (packages/core/src/animation/AnimationEvent.ts)
- Confirmed: Multiple addCurveBinding overloads exist (propertyPath / set+get property / componentIndex) and implementation supports them. (packages/core/src/animation/AnimationClip.ts)
- Action: Fix the docs example that passes explicit undefined — either remove the third arg (clip.addEvent("onJumpLand", 1.1)) or update the public overload to accept undefined (parameter?: Object or Object | undefined) in packages/core/src/animation/AnimationClip.ts (around the addEvent overload on line ~58) so the example compiles under strict null checks.
🤖 Prompt for AI Agents
In docs/scripting/AnimationClip.md around lines 33 to 48 the example calls
clip.addEvent("onJumpLand", 1.1, undefined) which doesn't match the public
TypeScript overload; update the public overload in
packages/core/src/animation/AnimationClip.ts (around the addEvent overload ~line
58) to accept an optional parameter (e.g., parameter?: Object or parameter:
Object | undefined) so the call with undefined compiles under strictNullChecks,
or alternatively update the docs example to call clip.addEvent("onJumpLand",
1.1) and remove the explicit undefined; implement the code change by adjusting
the overload/signature and keeping the implementation that already accepts an
optional parameter.
| | Class | Value type | Interpolation support | Notes | | ||
| | --- | --- | --- | --- | | ||
| | `AnimationFloatCurve` | `number` | Linear, CubicSpine, Hermite, Step | Default choice for scalar properties. | | ||
| | `AnimationVector2Curve` | `Vector2` | Linear, CubicSpine, Hermite, Step | Interpolates component-wise. | | ||
| | `AnimationVector3Curve` | `Vector3` | Linear, CubicSpine, Hermite, Step | Works for positions, scales, etc. | | ||
| | `AnimationVector4Curve` | `Vector4` | Linear, CubicSpine, Hermite, Step | Useful for homogeneous data. | | ||
| | `AnimationColorCurve` | `Color` | Linear, CubicSpine, Hermite, Step | Internally treats colors as `Vector4`. | | ||
| | `AnimationQuaternionCurve` | `Quaternion` | Linear, CubicSpine, Hermite, Step | Manages quaternion keyframes without gimbal lock. | | ||
| | `AnimationArrayCurve` | `number[]` | Linear, CubicSpine, Hermite, Step | Arrays must keep a fixed length across keys. | | ||
| | `AnimationFloatArrayCurve` | `Float32Array` | Linear, CubicSpine, Hermite, Step | Allocates internal buffers based on the first key. | | ||
| | `AnimationRectCurve` | `Rect` | Step only | Suited for rectangle swaps; smoothing is not supported. | | ||
| | `AnimationBoolCurve` | `boolean` | Step only | For on/off style toggles. | | ||
| | `AnimationStringCurve` | `string` | Step only | Useful for state labels or shader keywords. | | ||
| | `AnimationRefCurve` | `ReferResource` | Step only | Switches resource references such as textures or prefabs. | | ||
|
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Fix “CubicSpine” → “CubicSpline” (table).
Spelling error in interpolation name across the table.
-| `AnimationFloatCurve` | `number` | Linear, CubicSpine, Hermite, Step | Default choice for scalar properties. |
+| `AnimationFloatCurve` | `number` | Linear, CubicSpline, Hermite, Step | Default choice for scalar properties. |
@@
-| `AnimationVector2Curve` | `Vector2` | Linear, CubicSpine, Hermite, Step | Interpolates component-wise. |
+| `AnimationVector2Curve` | `Vector2` | Linear, CubicSpline, Hermite, Step | Interpolates component-wise. |
@@
-| `AnimationVector3Curve` | `Vector3` | Linear, CubicSpine, Hermite, Step | Works for positions, scales, etc. |
+| `AnimationVector3Curve` | `Vector3` | Linear, CubicSpline, Hermite, Step | Works for positions, scales, etc. |
@@
-| `AnimationVector4Curve` | `Vector4` | Linear, CubicSpine, Hermite, Step | Useful for homogeneous data. |
+| `AnimationVector4Curve` | `Vector4` | Linear, CubicSpline, Hermite, Step | Useful for homogeneous data. |
@@
-| `AnimationColorCurve` | `Color` | Linear, CubicSpine, Hermite, Step | Internally treats colors as `Vector4`. |
+| `AnimationColorCurve` | `Color` | Linear, CubicSpline, Hermite, Step | Internally treats colors as `Vector4`. |
@@
-| `AnimationArrayCurve` | `number[]` | Linear, CubicSpine, Hermite, Step | Arrays must keep a fixed length across keys. |
+| `AnimationArrayCurve` | `number[]` | Linear, CubicSpline, Hermite, Step | Arrays must keep a fixed length across keys. |
@@
-| `AnimationFloatArrayCurve` | `Float32Array` | Linear, CubicSpine, Hermite, Step | Allocates internal buffers based on the first key. |
+| `AnimationFloatArrayCurve` | `Float32Array` | Linear, CubicSpline, Hermite, Step | Allocates internal buffers based on the first key. |Committable suggestion skipped: line range outside the PR's diff.
🧰 Tools
🪛 markdownlint-cli2 (0.17.2)
21-21: Tables should be surrounded by blank lines
(MD058, blanks-around-tables)
🤖 Prompt for AI Agents
In docs/scripting/AnimationCurve.md around lines 21 to 35, the interpolation
name "CubicSpine" is misspelled across the table; replace every occurrence of
"CubicSpine" with the correct "CubicSpline" so the table accurately reflects
supported interpolation methods for each curve class.
| enum InterpolationType { | ||
| Linear, // Linear interpolation | ||
| CubicSpine, // Cubic spline interpolation | ||
| Step, // Step interpolation (no transition) | ||
| Hermite // Hermite interpolation | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Fix “CubicSpine” → “CubicSpline” (enum).
- CubicSpine, // Cubic spline interpolation
+ CubicSpline, // Cubic spline interpolation📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| enum InterpolationType { | |
| Linear, // Linear interpolation | |
| CubicSpine, // Cubic spline interpolation | |
| Step, // Step interpolation (no transition) | |
| Hermite // Hermite interpolation | |
| } | |
| enum InterpolationType { | |
| Linear, // Linear interpolation | |
| CubicSpline, // Cubic spline interpolation | |
| Step, // Step interpolation (no transition) | |
| Hermite // Hermite interpolation | |
| } |
🤖 Prompt for AI Agents
In docs/scripting/AnimationCurve.md around lines 102 to 107, the enum member
name "CubicSpine" is misspelled; change it to "CubicSpline" in the enum
declaration and update all references in this file (and any linked
docs/examples) to use the corrected name, preserving the comment ("Cubic spline
interpolation") and ensuring consistency across the documentation.
|
|
||
| ## Usage Example | ||
| ```typescript | ||
| import { Animator, AnimatorController, AnimatorControllerLayer, AnimatorLayerBlendingMode } from '@galacean/engine'; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Add missing import for example code.
The usage example references AnimatorConditionMode and WrapMode but these aren't included in the import statement.
- import { Animator, AnimatorController, AnimatorControllerLayer, AnimatorLayerBlendingMode } from '@galacean/engine';
+ import {
+ Animator,
+ AnimatorController,
+ AnimatorControllerLayer,
+ AnimatorLayerBlendingMode,
+ AnimatorConditionMode,
+ WrapMode
+ } from '@galacean/engine';📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| import { Animator, AnimatorController, AnimatorControllerLayer, AnimatorLayerBlendingMode } from '@galacean/engine'; | |
| import { | |
| Animator, | |
| AnimatorController, | |
| AnimatorControllerLayer, | |
| AnimatorLayerBlendingMode, | |
| AnimatorConditionMode, | |
| WrapMode | |
| } from '@galacean/engine'; |
🤖 Prompt for AI Agents
In docs/scripting/Animator.md around line 108, the example import only includes
Animator, AnimatorController, AnimatorControllerLayer, AnimatorLayerBlendingMode
but the example also uses AnimatorConditionMode and WrapMode; update the import
statement to include AnimatorConditionMode and WrapMode from '@galacean/engine'
so the example compiles and all referenced enums are available.
| // Tiled mode - repeating texture pattern | ||
| spriteRenderer.drawMode = SpriteDrawMode.Tiled; | ||
| spriteRenderer.tileMode = SpriteTileMode.Continuous; | ||
| spriteRenderer.tiledAdaptiveThreshold = 0.5; | ||
| ``` |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🧩 Analysis chain
Verify tiling API.
SpriteTileMode.Adaptive and tiledAdaptiveThreshold need confirmation.
🌐 Web query:
SpriteRenderer tiling API in Galacean: supported modes and properties (Adaptive? tiledAdaptiveThreshold?).
💡 Result:
Short answer:
- Galacean's SpriteRenderer supports drawMode values: normal, nine-slice, and tiled. [1][2]
- Galacean's documentation does not document a Sprite tileMode (Continuous/Adaptive) or an adaptive/tiled threshold property (e.g., adaptiveModeThreshold / tiledAdaptiveThreshold). I could not find any Galacean API docs exposing an "Adaptive" tiling mode or threshold property. [1][7]
For comparison (if you meant Unity-style behaviour): Unity exposes SpriteTileMode (Continuous / Adaptive) and SpriteRenderer.adaptiveModeThreshold. Galacean's docs do not show equivalent properties. [3][9]
Sources:
- Galacean Engine — SpriteRenderer (drawMode, properties). [https://galacean.antgroup.com/engine/en/docs/graphics/2D/spriteRenderer/] [1]
- Galacean Engine — Image / UI draw modes (Normal, Nine-Patch, Tiled). [https://galacean.antgroup.com/engine/en/docs/UI/quickStart/image/] [2]
- Unity docs — SpriteTileMode (Continuous / Adaptive). [https://docs.unity3d.com/ScriptReference/SpriteTileMode.html] [3]
- Unity docs — SpriteRenderer.adaptiveModeThreshold. [https://docs.unity3d.com/2022.1/Documentation/ScriptReference/SpriteRenderer-adaptiveModeThreshold.html] [4]
If you want, I can search the Galacean repo/examples or contact their changelog for a more definitive confirmation.
Remove Unity-specific tiling properties (tileMode / tiledAdaptiveThreshold).
Galacean's SpriteRenderer supports drawMode = Tiled but does not expose SpriteTileMode (Continuous/Adaptive) or a tiledAdaptiveThreshold — those are Unity APIs. Keep spriteRenderer.drawMode = SpriteDrawMode.Tiled; and remove the tileMode and tiledAdaptiveThreshold lines or replace them with a Galacean-supported implementation. File: docs/scripting/Sprite.md (lines 69–73).
🤖 Prompt for AI Agents
In docs/scripting/Sprite.md around lines 69 to 73, remove the Unity-specific
properties spriteRenderer.tileMode and spriteRenderer.tiledAdaptiveThreshold and
keep only the Galacean-supported call spriteRenderer.drawMode =
SpriteDrawMode.Tiled; — if you need to document equivalent Galacean behavior,
replace the removed lines with the Galacean-supported approach (e.g.,
instructions to adjust UV/tile scale via the engine's supported properties or
functions), otherwise delete those two lines entirely.
| ```typescript | ||
| // Create mask component | ||
| const spriteMask = entity.addComponent(SpriteMask); | ||
| spriteMask.sprite = maskSprite; | ||
| spriteMask.alphaCutoff = 0.5; // Alpha threshold | ||
| spriteMask.influenceLayers = SpriteMaskLayer.UI; // Affected layers | ||
|
|
||
| // Mask positioning and sizing | ||
| spriteMask.width = 200; | ||
| spriteMask.height = 150; | ||
| spriteMask.flipX = false; | ||
| spriteMask.flipY = false; | ||
| ``` | ||
|
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🧩 Analysis chain
Validate SpriteMask surface.
Confirm properties (alphaCutoff, influenceLayers, flipX/Y, width/height) and enum names.
🌐 Web query:
SpriteMask component API and enum names (SpriteMaskLayer, SpriteMaskInteraction) in "@galacean/engine".
💡 Result:
Summary — SpriteMask API and enums in @galacean/engine
- SpriteMask (component)
- Properties:
- sprite: Sprite (the sprite used as the mask). (galacean.antgroup.com) [1]
- influenceLayers: number (bitmask of SpriteMaskLayer, defaults to SpriteMaskLayer.Everything). (galacean.antgroup.com) [1]
- SpriteRenderer (related properties)
- maskInteraction: SpriteMaskInteraction (controls how the renderer interacts with masks). (galacean.antgroup.com) [2]
- maskLayer: SpriteMaskLayer (the mask layer(s) the sprite belongs to). (galacean.antgroup.com) [2]
- Enums (names & intent)
- SpriteMaskLayer — enum of 32 bit flags (Layer0 = 0x1, Layer1 = 0x2, …, Layer31 = 0x80000000, Everything = 0xffffffff). (galacean.antgroup.com) [1]
- SpriteMaskInteraction — enum values: None, VisibleInsideMask, VisibleOutsideMask. (galacean.antgroup.com) [1]
Sources
[1] Galacean blog / SpriteMask (API examples & enums). (galacean.antgroup.com)
[2] Galacean docs / SpriteRenderer (maskInteraction, maskLayer properties). (galacean.antgroup.com)
If you want, I can paste the exact TypeScript enum/class declarations from the repo/docs.
Citations:
- 1: https://galacean.antgroup.com/engine/en/blog/sprite_mask/?utm_source=openai
- 2: https://galacean.antgroup.com/engine/en/blog/sprite_mask/?utm_source=openai
- 3: https://galacean.antgroup.com/engine/en/docs/graphics/2D/spriteRenderer/?utm_source=openai
- 4: https://galacean.antgroup.com/engine/en/docs/graphics/2D/spriteRenderer/?utm_source=openai
- 5: https://galacean.antgroup.com/engine/en/blog/sprite_mask/?utm_source=openai
- 6: https://galacean.antgroup.com/engine/en/blog/sprite_mask/?utm_source=openai
- 7: https://galacean.antgroup.com/engine/en/blog/sprite_mask/?utm_source=openai
- 8: https://galacean.antgroup.com/engine/en/docs/graphics/2D/spriteRenderer/?utm_source=openai
Fix SpriteMask API usage in docs/scripting/Sprite.md (lines 98–111).
- SpriteMask only exposes sprite and influenceLayers (bitmask; default SpriteMaskLayer.Everything). Enum names SpriteMaskLayer and SpriteMaskInteraction are correct. (galacean.com)
- Remove alphaCutoff from the SpriteMask example — Galacean’s SpriteMask does not expose alphaCutoff (that property exists on Unity’s SpriteMask). (galacean.com)
- Move width/height/flipX/flipY to the SpriteRenderer example — those are SpriteRenderer properties, not SpriteMask properties. (galacean.antgroup.com)
🤖 Prompt for AI Agents
In docs/scripting/Sprite.md around lines 98–111, the SpriteMask example
incorrectly uses alphaCutoff and includes SpriteRenderer properties; update the
SpriteMask snippet to only set sprite and influenceLayers (use the
SpriteMaskLayer bitmask; note default is SpriteMaskLayer.Everything) and remove
alphaCutoff, width, height, flipX and flipY from this block; then move the
width/height/flipX/flipY property examples into the SpriteRenderer example
elsewhere in the document so those properties are shown on the correct
component; keep the enum names SpriteMaskLayer and SpriteMaskInteraction as-is.
| // Atlas sprite creation from SpriteAtlas | ||
| const spriteAtlas = await engine.resourceManager.load("atlas.json"); | ||
| const sprite = spriteAtlas.getSprite("character_idle"); | ||
|
|
||
| // Manual atlas configuration | ||
| const sprite = new Sprite(engine, atlasTexture); | ||
| sprite.atlasRegion = new Rect(0.25, 0.25, 0.5, 0.5); // Use quarter of texture | ||
| sprite.atlasRegionOffset = new Vector4(0.1, 0.1, 0.1, 0.1); // 10% padding | ||
| sprite.atlasRotated = true; // Sprite was rotated 90° during packing | ||
| ``` |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🧩 Analysis chain
Atlas loading example: confirm resource type.
Does resourceManager.load("atlas.json") resolve to a SpriteAtlas with getSprite()? If not, provide the correct loader pattern.
🌐 Web query:
How to load a SpriteAtlas in Galacean and retrieve sprites by name.
💡 Result:
Use engine.resourceManager to load the .atlas file, then call atlas.getSprite(name) or atlas.getSprites(name). Example:
-
Ensure the .atlas and its .png are in the same CDN folder (e.g. https://cdn/.../ui_atlas.atlas and ui_atlas.png). [1][2]
-
Load and retrieve sprites (TypeScript):
engine.resourceManager
.load({
url: "https://cdn.example.com/ui_atlas.atlas",
type: AssetType.SpriteAtlas
})
.then((atlas) => {
const all = atlas.sprites; // all sprites in atlas
const one = atlas.getSprite("hero"); // first sprite named "hero"
const many = atlas.getSprites("coin"); // array of all sprites named "coin"
});
References: Galacean SpriteAtlas docs (runtime usage and API). [1][2]
Atlas loading example: load the .atlas as a SpriteAtlas (specify AssetType.SpriteAtlas)
engine.resourceManager.load("atlas.json") won't reliably return a SpriteAtlas — replace it with something like:
engine.resourceManager.load({ url: "https://cdn.example.com/ui_atlas.atlas", type: AssetType.SpriteAtlas }).then(atlas => atlas.getSprite("name"));
File: docs/scripting/Sprite.md (lines 117-126) — update the atlas loading call.
🤖 Prompt for AI Agents
In docs/scripting/Sprite.md around lines 117 to 126, the example uses
engine.resourceManager.load("atlas.json") which may not return a SpriteAtlas;
update the call to explicitly request a SpriteAtlas by passing a typed load or
an object with url and type (AssetType.SpriteAtlas) and then await or .then the
result before calling getSprite("name") so the load reliably returns a
SpriteAtlas instance.
| ### Memory Management | ||
|
|
||
| ```typescript | ||
| // Sprites are reference-counted resources | ||
| const sprite = new Sprite(engine, texture); | ||
| spriteRenderer.sprite = sprite; // Increments reference count | ||
|
|
||
| // Cleanup | ||
| spriteRenderer.sprite = null; // Decrements reference count | ||
| // Sprite automatically destroyed when reference count reaches 0 | ||
| ``` |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🧩 Analysis chain
Check “reference‑counted” claim.
Verify automatic destruction and reference counting semantics for Sprite.
🌐 Web query:
Resource lifetime/RC behavior for Sprite and Texture in Galacean.
💡 Result:
Short answer — Galacean uses manual reference-counting in ResourceManager: Sprite assets hold a reference to their Texture2D, the ResourceManager caches loaded assets, and you must call the GC API to release cached resources. When you release (or let go of) a Sprite, its Texture's reference count is decremented and the ResourceManager.gc() run will free assets whose ref-count reaches zero (taking dependencies into account). [1][2][3]
Notes / pointers
- Sprite → texture relationship: Sprite.texture is a Texture2D reference. Releasing a Sprite will affect that Texture's ref count. [1]
- Loading/caching: resources loaded through engine.resourceManager are cached; use getFromCache/load to access. [3]
- Releasing: ResourceManager implements reference-counted releases; call engine.resourceManager.gc() to run the release check and free unreferenced assets. Resource dependencies are considered during release. [2]
Sources
- Sprite docs (texture property). [1]
- Releasing assets / ResourceManager GC docs. [2]
- Resource loading & cache behavior. [3]
Clarify reference-counting: resources aren’t freed automatically — ResourceManager.gc() must be run.
Update docs/scripting/Sprite.md (lines 200–210): state that Sprite holds a Texture2D reference and that setting spriteRenderer.sprite = null decrements reference counts but does not immediately destroy cached assets — unreferenced resources are reclaimed only when engine.resourceManager.gc() (or the ResourceManager GC API) runs; link to the ResourceManager GC docs.
🤖 Prompt for AI Agents
In docs/scripting/Sprite.md around lines 200 to 210, the Memory Management
section needs clarification: state that a Sprite holds a Texture2D reference and
that assigning spriteRenderer.sprite = null only decrements reference counts but
does not immediately free cached assets; unreferenced resources are reclaimed
only when the engine.resourceManager.gc() (or the ResourceManager GC API) is
invoked, and add a link to the ResourceManager GC docs for details.
| getSessionInfo() { | ||
| return { | ||
| mode: this.sessionManager.mode, | ||
| state: this.sessionManager.state, | ||
| frameRate: this.sessionManager.frameRate, | ||
| supportedFrameRates: this.sessionManager.supportedFrameRate | ||
| }; | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
🧩 Analysis chain
Property name mismatch: supported frame rates.
getSessionInfo() uses supportedFrameRate (singular). If the API returns multiple rates, rename to supportedFrameRates and adjust type to number[].
Run this to confirm actual identifiers in the repo:
🏁 Script executed:
#!/bin/bash
rg -nP -C2 --type=ts '\bsupportedFrameRate(s)?\b|frameRate\b|XRSessionManager' docs packagesLength of output: 4616
Rename supportedFrameRate → supportedFrameRates and use Float32Array
XRSessionManager exposes get supportedFrameRate (packages/xr/src/session/XRSessionManager.ts) while IXRSession and WebXRSession use supportedFrameRates (packages/design/src/xr/IXRSession.ts, packages/xr-webxr/src/WebXRSession.ts); update XRSessionManager and docs/scripting/XRManager.md to use supportedFrameRates with type Float32Array.
🤖 Prompt for AI Agents
In docs/scripting/XRManager.md around lines 202 to 209, the returned object uses
supportedFrameRate instead of supportedFrameRates and does not ensure the type
is Float32Array; update the property name to supportedFrameRates and make sure
the value is a Float32Array (e.g., convert or cast
this.sessionManager.supportedFrameRates to Float32Array). Also update the source
in packages/xr/src/session/XRSessionManager.ts to rename the exposed getter from
supportedFrameRate to supportedFrameRates and have it return a Float32Array,
keeping IXRSession and WebXRSession signatures consistent.
任务清单
// 探针先忽略
// 拖尾先忽略
Summary by CodeRabbit