lecodes-cli 0.17.2 → 0.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/dist/index.js +1340 -648
  2. package/package.json +3 -3
  3. package/runtime/scene-harness.json +1 -1
  4. package/runtime/sdk/compile/bundler.ts +1 -1
  5. package/runtime/sdk/compile/compileProject.ts +16 -1
  6. package/runtime/sdk/compile/header.ts +6 -1
  7. package/runtime/sdk/compile/index.ts +16 -0
  8. package/runtime/sdk/compile/liteMaterial.ts +247 -0
  9. package/runtime/sdk/compile/shaderTargets.ts +42 -0
  10. package/runtime/sdk/core/Aspect.ts +255 -244
  11. package/runtime/sdk/g2/CharacterController2D.ts +2 -2
  12. package/runtime/sdk/gl/Camera.ts +41 -0
  13. package/runtime/sdk/gl/CameraPlace.ts +51 -0
  14. package/runtime/sdk/gl/CharacterController.ts +3 -2
  15. package/runtime/sdk/gl/IK.ts +193 -174
  16. package/runtime/sdk/gl/Material.ts +11 -0
  17. package/runtime/sdk/gl/Model.ts +7 -6
  18. package/runtime/sdk/gl/Node.ts +270 -285
  19. package/runtime/sdk/gl/Physics.ts +171 -126
  20. package/runtime/sdk/gl/Scene.ts +27 -3
  21. package/runtime/sdk/gl/Shape.ts +214 -10
  22. package/runtime/sdk/gl/Vehicle.ts +519 -0
  23. package/runtime/sdk/gl/{AnimationClip.ts → animation/AnimationClip.ts} +37 -7
  24. package/runtime/sdk/gl/animation/Animator.ts +87 -0
  25. package/runtime/sdk/gl/animation/Layer.ts +29 -0
  26. package/runtime/sdk/gl/animation/Loop.ts +25 -0
  27. package/runtime/sdk/gl/animation/Playback.ts +43 -0
  28. package/runtime/sdk/gl/animation/core.ts +294 -0
  29. package/runtime/sdk/gl/scenarios.ts +26 -58
  30. package/runtime/sdk/inject.ts +18 -9
  31. package/runtime/sdk/runtime/app.ts +13 -0
  32. package/runtime/sdk/runtime/input.ts +169 -6
  33. package/runtime/sdk/scene/defineScene.ts +182 -26
  34. package/runtime/sdk/scene/gizmos.ts +128 -0
  35. package/runtime/sdk-types.json +1 -1
  36. package/runtime/sdk/gl/Animator.ts +0 -642
  37. package/runtime/sdk/gl/ModelAnimation.ts +0 -95
@@ -1,285 +1,270 @@
1
- // Base 3D scene node — an empty transform. Mesh and Light extend it, so every node operation works
2
- // on them. Native (creator-gl) owns the authoritative transform; reads decompose a cached local
3
- // matrix (re-synced lazily, since physics can write the transform from native each frame).
4
- //
5
- // Capabilities are aspects: node.aspect(Physics, …) (→ node.physics), node.aspect(Shape, …).
6
- // A GLB import is the Model node kind (with the ModelAnimation aspect). Hierarchy lives here.
7
-
8
- import { AspectHost } from "../core/Aspect"
9
- import { Registry } from "../core/registry"
10
- import { Vec3, cx, cy, cz, type Vec3Like } from "../math/vec"
11
- import { Quat, cw, type QuatLike } from "../math/quat"
12
- import { Mat4, type Mat4Like } from "../math/mat4"
13
- import type { Geometry } from "./Geometry"
14
- import { registerTouchEndEvent, registerTouchStartEvent } from "./touch"
15
- import { ensurePhysicsEvents } from "./physicsEvents"
16
- import { glState } from "./state"
17
- import type { ClickEvent, TouchStartEvent } from "../runtime/touch"
18
-
19
- /** id → Node, so host callbacks (touch hits, animation events) route back to the owning object. */
20
- export const nodeRegistry = new Registry<Node>()
21
-
22
- export type NodeEvents = {
23
- click: (ev: ClickEvent<Node | null>) => void
24
- touchstart: (ev: TouchStartEvent<Node | null>) => void
25
- /** A looping GLB animation clip wrapped around. */
26
- loopReached: (clip: number) => void
27
- /** A non-looping GLB animation clip finished. */
28
- completed: (clip: number) => void
29
- /** AR anchors only (`scene.root` / `scene.createAnchor()`): the anchor began tracking. */
30
- track: () => void
31
- /** AR anchors only: the anchor lost tracking. */
32
- untrack: () => void
33
- /** A physics contact/trigger overlap began (the other body's node). Needs a Shape + Physics/Trigger. */
34
- enter: (other: Node) => void
35
- /** A physics contact/trigger overlap ended. */
36
- exit: (other: Node) => void
37
- }
38
-
39
- const shortName = (s: string): string => s.slice(s.search(/[^:|]*$/))
40
-
41
- /** Fallback for hosts without `_creator.findNode` (exact name, then short name, first in tree order —
42
- * no skin-joint preference: that needs the host's skin knowledge). 0 when absent. */
43
- const findNodeByWalk = (rootId: number, name: string): number => {
44
- let exact = 0
45
- let loose = 0
46
- const want = shortName(name)
47
- _creator.traverse(rootId, (id) => {
48
- if (exact) return
49
- const n = _creator.getName(id)
50
- if (n === name) exact = id
51
- else if (!loose && shortName(n) === want) loose = id
52
- })
53
- return exact || loose
54
- }
55
-
56
- export class Node extends AspectHost<NodeEvents> {
57
- /** Native entity handle. */
58
- readonly id: number
59
-
60
- /** AR anchors only — whether the anchor is currently being tracked. Kept in step with the
61
- * 'track' / 'untrack' events; `false` for any non-anchor node. */
62
- isTracked = false
63
-
64
- private _matrix?: Float32Array
65
- private _lastSync = 0
66
- private _syncFrame = -1
67
- private _worldMatrix?: Float32Array
68
- private _scaleCache?: [number, number, number]
69
- private _boneCache?: Map<string, Node | null>
70
-
71
- /** @internal — the active animation aspect's clip-complete handler (installed by ModelAnimation). */
72
- _animComplete?: (clipIndex: number) => boolean
73
-
74
- constructor(internalId?: number) {
75
- super()
76
- this.id = internalId ?? _creator.createEntity()
77
- nodeRegistry.set(this.id, this)
78
- }
79
-
80
- /** Geometry, if this node is a Mesh (used by physics auto-shape). Overridden by Mesh. */
81
- get geometry(): Geometry | undefined { return undefined }
82
-
83
- // --- name / visibility ---
84
- get name(): string { return _creator.getName(this.id) }
85
- set name(value: string) { _creator.setName(this.id, value) }
86
- get visible(): boolean { return _creator.isVisible(this.id) }
87
- set visible(value: boolean) { _creator.setVisible(this.id, value) }
88
-
89
- // --- local transform ---
90
- // Native owns the authoritative matrix; we keep a Float32Array cache (re-synced lazily because physics
91
- // can rewrite it each frame). The PUBLIC `matrix` getter hands back a fresh Mat4 *copy* (value
92
- // semantics — mutating it never touches the node until you assign it back). `_sync()` is the internal
93
- // hot path that returns the cache directly for cheap component reads.
94
- private _sync(): Float32Array {
95
- if (!this._matrix) this._matrix = new Float32Array(16)
96
- // stale once per render frame (glState.frame — physics/controllers/animation rewrite transforms
97
- // between frames), or after 10 ms of wall time when no scene loop is running
98
- if (this._lastSync === 0 || this._syncFrame !== glState.frame || Date.now() - this._lastSync > 10) {
99
- _creator.getMatrix(this.id, this._matrix)
100
- this._scaleCache = undefined
101
- this._lastSync = Date.now()
102
- this._syncFrame = glState.frame
103
- }
104
- return this._matrix
105
- }
106
-
107
- get matrix(): Mat4 { return new Mat4(this._sync()) }
108
- set matrix(m: Mat4Like) {
109
- if (!this._matrix) this._matrix = new Float32Array(16)
110
- this._matrix.set(matArr(m))
111
- this._lastSync = Date.now()
112
- _creator.setMatrix(this.id, this._matrix)
113
- }
114
-
115
- get worldMatrix(): Mat4 {
116
- if (this.parent === null) return this.matrix
117
- if (!this._worldMatrix) this._worldMatrix = new Float32Array(16)
118
- _creator.getWorldMatrix(this.id, this._worldMatrix)
119
- return new Mat4(this._worldMatrix)
120
- }
121
- set worldMatrix(m: Mat4Like) {
122
- const p = this.parent
123
- if (p === null) { this.matrix = m; return }
124
- // local = parentWorld⁻¹ · world, composed here: the native setWorldMatrix ignores the parent (it
125
- // wrote the world matrix as the local one — a bone under a rotated Model wrapper read back with the
126
- // ancestors' rotation applied twice)
127
- this.matrix = p.worldMatrix.invert().mul(m)
128
- }
129
-
130
- get position(): Vec3 { const m = this._sync(); return new Vec3(m[12], m[13], m[14]) }
131
- set position(v: Vec3Like) { this._lastSync = 0; _creator.setPosition(this.id, cx(v), cy(v), cz(v)) }
132
-
133
- // Scalar position accessors — the loud, correct way to nudge one axis (`node.x = 3`), so nobody reaches
134
- // for `node.position.x = 3` (a no-op: the getter returns a fresh copy).
135
- get x(): number { return this._sync()[12] }
136
- set x(v: number) { const m = this._sync(); this._lastSync = 0; _creator.setPosition(this.id, v, m[13], m[14]) }
137
- get y(): number { return this._sync()[13] }
138
- set y(v: number) { const m = this._sync(); this._lastSync = 0; _creator.setPosition(this.id, m[12], v, m[14]) }
139
- get z(): number { return this._sync()[14] }
140
- set z(v: number) { const m = this._sync(); this._lastSync = 0; _creator.setPosition(this.id, m[12], m[13], v) }
141
-
142
- get scale(): Vec3 {
143
- if (this._lastSync === 0 || !this._scaleCache) {
144
- const m = this._sync()
145
- this._scaleCache = [ Math.hypot(m[0], m[1], m[2]), Math.hypot(m[4], m[5], m[6]), Math.hypot(m[8], m[9], m[10]) ]
146
- }
147
- return new Vec3(this._scaleCache)
148
- }
149
- set scale(v: Vec3Like | number) {
150
- this._lastSync = 0
151
- if (typeof v === "number") _creator.setScale(this.id, v, v, v)
152
- else _creator.setScale(this.id, cx(v), cy(v), cz(v))
153
- }
154
-
155
- get quaternion(): Quat { return new Mat4(this._sync()).rotation }
156
- set quaternion(v: QuatLike) { this._lastSync = 0; _creator.setQuaternion(this.id, cx(v), cy(v), cz(v), cw(v)) }
157
-
158
- get eulerAngles(): Vec3 { return new Mat4(this._sync()).eulerAngles }
159
- // order 1 = YXZ — the SDK's euler convention (math/quat.ts); the getter also extracts YXZ, so
160
- // the pair round-trips. (Historically this passed 0/XYZ AND the engine stored the euler matrix
161
- // transposed — the setter applied the INVERSE rotation. Both fixed 2026-07-10.)
162
- set eulerAngles(v: Vec3Like) { this._lastSync = 0; _creator.setEulerAngles(this.id, cx(v), cy(v), cz(v), 1) }
163
-
164
- // --- world-space reads ---
165
- get forward(): Vec3 {
166
- const v = new Float32Array(3)
167
- _creator.getWorldDirection(this.id, 2, v)
168
- return new Vec3(-v[0], -v[1], -v[2])
169
- }
170
- get worldPosition(): Vec3 {
171
- const v = new Float32Array(3)
172
- _creator.getWorldPosition(this.id, v)
173
- return new Vec3(v[0], v[1], v[2])
174
- }
175
- get worldScale(): Vec3 { return this.worldMatrix.scaling }
176
- get worldQuaternion(): Quat { return this.worldMatrix.rotation }
177
- get worldEulerAngles(): Vec3 { return this.worldMatrix.eulerAngles }
178
-
179
- // --- hierarchy ---
180
- get parent(): Node | null {
181
- const id = _creator.getParent(this.id)
182
- return id === 0 ? null : (nodeRegistry.get(id) ?? new Node(id))
183
- }
184
- get children(): Node[] {
185
- return _creator.getChildren(this.id).map((id) => nodeRegistry.get(id) ?? new Node(id))
186
- }
187
- get childCount(): number { return _creator.getChildCount(this.id) }
188
- getChild(index: number): Node | null {
189
- const id = _creator.getChild(this.id, index)
190
- return id === 0 ? null : (nodeRegistry.get(id) ?? new Node(id))
191
- }
192
- /** Parent the given nodes under this one. */
193
- add(...children: Node[]): this {
194
- for (const c of children) _creator.setParent(c.id, this.id, false)
195
- return this
196
- }
197
- setParent(parent: Node | null, worldPositionStays = false): this {
198
- if (parent === null) _creator.setParentNull(this.id, worldPositionStays)
199
- else _creator.setParent(this.id, parent.id, worldPositionStays)
200
- if (worldPositionStays) this._lastSync = 0
201
- return this
202
- }
203
- traverse(callback: (node: Node) => void): void {
204
- callback(this)
205
- _creator.traverse(this.id, (id) => callback(nodeRegistry.get(id) ?? new Node(id)))
206
- }
207
- /** Find a descendant by name — bones of a loaded Model included (`hero.bone('RightHand').add(sword)`).
208
- * Same rule the Animator binds clips with: exact name first, then the part after the last `:` / `|`
209
- * (Mixamo `mixamorig:Hips` matches `Hips`); a skinned joint beats a plain node of the same name.
210
- * Cached per name; null if absent. */
211
- bone(name: string): Node | null {
212
- const cache = (this._boneCache ??= new Map<string, Node | null>())
213
- const hit = cache.get(name)
214
- if (hit !== undefined) return hit
215
- const id = _creator.findNode ? _creator.findNode(this.id, name) : findNodeByWalk(this.id, name)
216
- const found = id ? nodeRegistry.get(id) ?? new Node(id) : null
217
- cache.set(name, found)
218
- return found
219
- }
220
-
221
- // --- behaviors are aspects: node.aspect(Shape, …) / node.aspect(Physics, …) ---
222
-
223
- /** Orient the node so the given axis (default "-z", "forward") points at a world point. */
224
- lookAt(point: Vec3Like, mode: "z" | "-z" | "x" | "-x" | "y" | "-y" = "-z", ortho: Vec3Like = [ 0, 1, 0 ]): this {
225
- const world = this.worldMatrix
226
- const pos = world.position
227
- let dir = new Vec3(point).sub(pos)
228
- const len = dir.length()
229
- if (len === 0) return this
230
- let axis: string = mode
231
- if (mode.startsWith("-")) { dir = dir.scale(-1 / len); axis = mode.slice(1) }
232
- else dir = dir.scale(1 / len)
233
-
234
- const o = new Vec3(ortho)
235
- let forward: Vec3, right: Vec3, up: Vec3
236
- if (axis === "x") {
237
- right = dir; up = o.cross(right).normalize(); forward = up.cross(right).normalize()
238
- } else if (axis === "y") {
239
- up = dir; right = o.cross(up).normalize(); forward = up.cross(right).normalize()
240
- } else {
241
- forward = dir; right = o.cross(dir).normalize(); up = dir.cross(right)
242
- }
243
- const s = world.scaling, w = world.m
244
- this.worldMatrix = Float32Array.of(
245
- right.x * s.x, right.y * s.x, right.z * s.x, 0,
246
- up.x * s.y, up.y * s.y, up.z * s.y, 0,
247
- forward.x * s.z, forward.y * s.z, forward.z * s.z, 0,
248
- w[12], w[13], w[14], w[15],
249
- )
250
- return this
251
- }
252
-
253
- // --- events ---
254
- override addEventListener<K extends keyof NodeEvents>(channel: K, callback: NodeEvents[K]): void {
255
- if (channel === "click") registerTouchEndEvent()
256
- else if (channel === "touchstart") registerTouchStartEvent()
257
- else if (channel === "enter" || channel === "exit") ensurePhysicsEvents()
258
- super.addEventListener(channel, callback)
259
- }
260
-
261
- /** @internal — called by the touch system to deliver a hit. */
262
- _dispatchEvent<K extends keyof NodeEvents>(channel: K, ...args: Parameters<NodeEvents[K]>): void {
263
- this.dispatch(channel, ...args)
264
- }
265
-
266
- /** @internal — emit a physics contact/trigger event (the physics-event router can't reach dispatch). */
267
- _emitCollision(channel: "enter" | "exit", other: Node): void { this.dispatch(channel, other) }
268
-
269
- /** @internal — host animation-complete callback; forwards to the ModelAnimation aspect (if any).
270
- * Returns whether the clip should keep playing. */
271
- _onAnimationComplete(clipIndex: number): boolean {
272
- return this._animComplete?.(clipIndex) ?? true
273
- }
274
-
275
- /** @internal — emit a GLB animation event (the ModelAnimation aspect can't reach protected dispatch). */
276
- _emitAnim(channel: "loopReached" | "completed", clip: number): void { this.dispatch(channel, clip) }
277
-
278
- destroy(): void {
279
- nodeRegistry.delete(this.id)
280
- _creator.destroyEntity(this.id)
281
- }
282
- }
283
-
284
- /** Read the raw column-major elements out of a Mat4 wrapper or a plain length-16 array. */
285
- const matArr = (m: Mat4Like): ArrayLike<number> => (m as { m?: ArrayLike<number> }).m ?? (m as ArrayLike<number>)
1
+ // Base 3D scene node — an empty transform. Mesh and Light extend it, so every node operation works
2
+ // on them. Native (creator-gl) owns the authoritative transform; reads decompose a cached local
3
+ // matrix (re-synced lazily, since physics can write the transform from native each frame).
4
+ //
5
+ // Capabilities are aspects: node.aspect(Physics, …) (→ node.physics), node.aspect(Shape, …).
6
+ // A GLB import is the Model node kind (with the Animator aspect at model.anim). Hierarchy lives here.
7
+
8
+ import { AspectHost } from "../core/Aspect"
9
+ import { Registry } from "../core/registry"
10
+ import { Vec3, cx, cy, cz, type Vec3Like } from "../math/vec"
11
+ import { Quat, cw, type QuatLike } from "../math/quat"
12
+ import { Mat4, type Mat4Like } from "../math/mat4"
13
+ import type { Geometry } from "./Geometry"
14
+ import { registerTouchEndEvent, registerTouchStartEvent } from "./touch"
15
+ import { ensurePhysicsEvents } from "./physicsEvents"
16
+ import { glState } from "./state"
17
+ import type { ClickEvent, TouchStartEvent } from "../runtime/touch"
18
+
19
+ /** id → Node, so host callbacks (touch hits, animation events) route back to the owning object. */
20
+ export const nodeRegistry = new Registry<Node>()
21
+
22
+ export type NodeEvents = {
23
+ click: (ev: ClickEvent<Node | null>) => void
24
+ touchstart: (ev: TouchStartEvent<Node | null>) => void
25
+ /** AR anchors only (`scene.root` / `scene.createAnchor()`): the anchor began tracking. */
26
+ track: () => void
27
+ /** AR anchors only: the anchor lost tracking. */
28
+ untrack: () => void
29
+ /** A physics contact/trigger overlap began (the other body's node). Needs a Shape + Physics/Trigger. */
30
+ enter: (other: Node) => void
31
+ /** A physics contact/trigger overlap ended. */
32
+ exit: (other: Node) => void
33
+ }
34
+
35
+ const shortName = (s: string): string => s.slice(s.search(/[^:|]*$/))
36
+
37
+ /** Fallback for hosts without `_creator.findNode` (exact name, then short name, first in tree order —
38
+ * no skin-joint preference: that needs the host's skin knowledge). 0 when absent. */
39
+ const findNodeByWalk = (rootId: number, name: string): number => {
40
+ let exact = 0
41
+ let loose = 0
42
+ const want = shortName(name)
43
+ _creator.traverse(rootId, (id) => {
44
+ if (exact) return
45
+ const n = _creator.getName(id)
46
+ if (n === name) exact = id
47
+ else if (!loose && shortName(n) === want) loose = id
48
+ })
49
+ return exact || loose
50
+ }
51
+
52
+ export class Node extends AspectHost<NodeEvents> {
53
+ /** Native entity handle. */
54
+ readonly id: number
55
+
56
+ /** AR anchors only — whether the anchor is currently being tracked. Kept in step with the
57
+ * 'track' / 'untrack' events; `false` for any non-anchor node. */
58
+ isTracked = false
59
+
60
+ private _matrix?: Float32Array
61
+ private _lastSync = 0
62
+ private _syncFrame = -1
63
+ private _worldMatrix?: Float32Array
64
+ private _scaleCache?: [number, number, number]
65
+ private _boneCache?: Map<string, Node | null>
66
+
67
+ constructor(internalId?: number) {
68
+ super()
69
+ this.id = internalId ?? _creator.createEntity()
70
+ nodeRegistry.set(this.id, this)
71
+ }
72
+
73
+ /** Geometry, if this node is a Mesh (used by physics auto-shape). Overridden by Mesh. */
74
+ get geometry(): Geometry | undefined { return undefined }
75
+
76
+ // --- name / visibility ---
77
+ get name(): string { return _creator.getName(this.id) }
78
+ set name(value: string) { _creator.setName(this.id, value) }
79
+ get visible(): boolean { return _creator.isVisible(this.id) }
80
+ set visible(value: boolean) { _creator.setVisible(this.id, value) }
81
+
82
+ // --- local transform ---
83
+ // Native owns the authoritative matrix; we keep a Float32Array cache (re-synced lazily because physics
84
+ // can rewrite it each frame). The PUBLIC `matrix` getter hands back a fresh Mat4 *copy* (value
85
+ // semantics — mutating it never touches the node until you assign it back). `_sync()` is the internal
86
+ // hot path that returns the cache directly for cheap component reads.
87
+ private _sync(): Float32Array {
88
+ if (!this._matrix) this._matrix = new Float32Array(16)
89
+ // stale once per render frame (glState.frame — physics/controllers/animation rewrite transforms
90
+ // between frames), or after 10 ms of wall time when no scene loop is running
91
+ if (this._lastSync === 0 || this._syncFrame !== glState.frame || Date.now() - this._lastSync > 10) {
92
+ _creator.getMatrix(this.id, this._matrix)
93
+ this._scaleCache = undefined
94
+ this._lastSync = Date.now()
95
+ this._syncFrame = glState.frame
96
+ }
97
+ return this._matrix
98
+ }
99
+
100
+ get matrix(): Mat4 { return new Mat4(this._sync()) }
101
+ set matrix(m: Mat4Like) {
102
+ if (!this._matrix) this._matrix = new Float32Array(16)
103
+ this._matrix.set(matArr(m))
104
+ this._lastSync = Date.now()
105
+ _creator.setMatrix(this.id, this._matrix)
106
+ }
107
+
108
+ get worldMatrix(): Mat4 {
109
+ if (this.parent === null) return this.matrix
110
+ if (!this._worldMatrix) this._worldMatrix = new Float32Array(16)
111
+ _creator.getWorldMatrix(this.id, this._worldMatrix)
112
+ return new Mat4(this._worldMatrix)
113
+ }
114
+ set worldMatrix(m: Mat4Like) {
115
+ const p = this.parent
116
+ if (p === null) { this.matrix = m; return }
117
+ // local = parentWorld⁻¹ · world, composed here: the native setWorldMatrix ignores the parent (it
118
+ // wrote the world matrix as the local one — a bone under a rotated Model wrapper read back with the
119
+ // ancestors' rotation applied twice)
120
+ this.matrix = p.worldMatrix.invert().mul(m)
121
+ }
122
+
123
+ get position(): Vec3 { const m = this._sync(); return new Vec3(m[12], m[13], m[14]) }
124
+ set position(v: Vec3Like) { this._lastSync = 0; _creator.setPosition(this.id, cx(v), cy(v), cz(v)) }
125
+
126
+ // Scalar position accessors — the loud, correct way to nudge one axis (`node.x = 3`), so nobody reaches
127
+ // for `node.position.x = 3` (a no-op: the getter returns a fresh copy).
128
+ get x(): number { return this._sync()[12] }
129
+ set x(v: number) { const m = this._sync(); this._lastSync = 0; _creator.setPosition(this.id, v, m[13], m[14]) }
130
+ get y(): number { return this._sync()[13] }
131
+ set y(v: number) { const m = this._sync(); this._lastSync = 0; _creator.setPosition(this.id, m[12], v, m[14]) }
132
+ get z(): number { return this._sync()[14] }
133
+ set z(v: number) { const m = this._sync(); this._lastSync = 0; _creator.setPosition(this.id, m[12], m[13], v) }
134
+
135
+ get scale(): Vec3 {
136
+ if (this._lastSync === 0 || !this._scaleCache) {
137
+ const m = this._sync()
138
+ this._scaleCache = [ Math.hypot(m[0], m[1], m[2]), Math.hypot(m[4], m[5], m[6]), Math.hypot(m[8], m[9], m[10]) ]
139
+ }
140
+ return new Vec3(this._scaleCache)
141
+ }
142
+ set scale(v: Vec3Like | number) {
143
+ this._lastSync = 0
144
+ if (typeof v === "number") _creator.setScale(this.id, v, v, v)
145
+ else _creator.setScale(this.id, cx(v), cy(v), cz(v))
146
+ }
147
+
148
+ get quaternion(): Quat { return new Mat4(this._sync()).rotation }
149
+ set quaternion(v: QuatLike) { this._lastSync = 0; _creator.setQuaternion(this.id, cx(v), cy(v), cz(v), cw(v)) }
150
+
151
+ get eulerAngles(): Vec3 { return new Mat4(this._sync()).eulerAngles }
152
+ // order 1 = YXZ — the SDK's euler convention (math/quat.ts); the getter also extracts YXZ, so
153
+ // the pair round-trips. (Historically this passed 0/XYZ AND the engine stored the euler matrix
154
+ // transposed — the setter applied the INVERSE rotation. Both fixed 2026-07-10.)
155
+ set eulerAngles(v: Vec3Like) { this._lastSync = 0; _creator.setEulerAngles(this.id, cx(v), cy(v), cz(v), 1) }
156
+
157
+ // --- world-space reads ---
158
+ get forward(): Vec3 {
159
+ const v = new Float32Array(3)
160
+ _creator.getWorldDirection(this.id, 2, v)
161
+ return new Vec3(-v[0], -v[1], -v[2])
162
+ }
163
+ get worldPosition(): Vec3 {
164
+ const v = new Float32Array(3)
165
+ _creator.getWorldPosition(this.id, v)
166
+ return new Vec3(v[0], v[1], v[2])
167
+ }
168
+ get worldScale(): Vec3 { return this.worldMatrix.scaling }
169
+ get worldQuaternion(): Quat { return this.worldMatrix.rotation }
170
+ get worldEulerAngles(): Vec3 { return this.worldMatrix.eulerAngles }
171
+
172
+ // --- hierarchy ---
173
+ get parent(): Node | null {
174
+ const id = _creator.getParent(this.id)
175
+ return id === 0 ? null : (nodeRegistry.get(id) ?? new Node(id))
176
+ }
177
+ get children(): Node[] {
178
+ return _creator.getChildren(this.id).map((id) => nodeRegistry.get(id) ?? new Node(id))
179
+ }
180
+ get childCount(): number { return _creator.getChildCount(this.id) }
181
+ getChild(index: number): Node | null {
182
+ const id = _creator.getChild(this.id, index)
183
+ return id === 0 ? null : (nodeRegistry.get(id) ?? new Node(id))
184
+ }
185
+ /** Parent the given nodes under this one. */
186
+ add(...children: Node[]): this {
187
+ for (const c of children) _creator.setParent(c.id, this.id, false)
188
+ return this
189
+ }
190
+ setParent(parent: Node | null, worldPositionStays = false): this {
191
+ if (parent === null) _creator.setParentNull(this.id, worldPositionStays)
192
+ else _creator.setParent(this.id, parent.id, worldPositionStays)
193
+ if (worldPositionStays) this._lastSync = 0
194
+ return this
195
+ }
196
+ traverse(callback: (node: Node) => void): void {
197
+ callback(this)
198
+ _creator.traverse(this.id, (id) => callback(nodeRegistry.get(id) ?? new Node(id)))
199
+ }
200
+ /** Find a descendant by name — bones of a loaded Model included (`hero.bone('RightHand').add(sword)`).
201
+ * Same rule the Animator binds clips with: exact name first, then the part after the last `:` / `|`
202
+ * (Mixamo `mixamorig:Hips` matches `Hips`); a skinned joint beats a plain node of the same name.
203
+ * Cached per name; null if absent. */
204
+ bone(name: string): Node | null {
205
+ const cache = (this._boneCache ??= new Map<string, Node | null>())
206
+ const hit = cache.get(name)
207
+ if (hit !== undefined) return hit
208
+ const id = _creator.findNode ? _creator.findNode(this.id, name) : findNodeByWalk(this.id, name)
209
+ const found = id ? nodeRegistry.get(id) ?? new Node(id) : null
210
+ cache.set(name, found)
211
+ return found
212
+ }
213
+
214
+ // --- behaviors are aspects: node.aspect(Shape, …) / node.aspect(Physics, …) ---
215
+
216
+ /** Orient the node so the given axis (default "-z", "forward") points at a world point. */
217
+ lookAt(point: Vec3Like, mode: "z" | "-z" | "x" | "-x" | "y" | "-y" = "-z", ortho: Vec3Like = [ 0, 1, 0 ]): this {
218
+ const world = this.worldMatrix
219
+ const pos = world.position
220
+ let dir = new Vec3(point).sub(pos)
221
+ const len = dir.length()
222
+ if (len === 0) return this
223
+ let axis: string = mode
224
+ if (mode.startsWith("-")) { dir = dir.scale(-1 / len); axis = mode.slice(1) }
225
+ else dir = dir.scale(1 / len)
226
+
227
+ const o = new Vec3(ortho)
228
+ let forward: Vec3, right: Vec3, up: Vec3
229
+ if (axis === "x") {
230
+ right = dir; up = o.cross(right).normalize(); forward = up.cross(right).normalize()
231
+ } else if (axis === "y") {
232
+ up = dir; right = o.cross(up).normalize(); forward = up.cross(right).normalize()
233
+ } else {
234
+ forward = dir; right = o.cross(dir).normalize(); up = dir.cross(right)
235
+ }
236
+ const s = world.scaling, w = world.m
237
+ this.worldMatrix = Float32Array.of(
238
+ right.x * s.x, right.y * s.x, right.z * s.x, 0,
239
+ up.x * s.y, up.y * s.y, up.z * s.y, 0,
240
+ forward.x * s.z, forward.y * s.z, forward.z * s.z, 0,
241
+ w[12], w[13], w[14], w[15],
242
+ )
243
+ return this
244
+ }
245
+
246
+ // --- events ---
247
+ override addEventListener<K extends keyof NodeEvents>(channel: K, callback: NodeEvents[K]): void {
248
+ if (channel === "click") registerTouchEndEvent()
249
+ else if (channel === "touchstart") registerTouchStartEvent()
250
+ else if (channel === "enter" || channel === "exit") ensurePhysicsEvents()
251
+ super.addEventListener(channel, callback)
252
+ }
253
+
254
+ /** @internal — called by the touch system to deliver a hit. */
255
+ _dispatchEvent<K extends keyof NodeEvents>(channel: K, ...args: Parameters<NodeEvents[K]>): void {
256
+ this.dispatch(channel, ...args)
257
+ }
258
+
259
+ /** @internal — emit a physics contact/trigger event (the physics-event router can't reach dispatch). */
260
+ _emitCollision(channel: "enter" | "exit", other: Node): void { this.dispatch(channel, other) }
261
+
262
+
263
+ destroy(): void {
264
+ nodeRegistry.delete(this.id)
265
+ _creator.destroyEntity(this.id)
266
+ }
267
+ }
268
+
269
+ /** Read the raw column-major elements out of a Mat4 wrapper or a plain length-16 array. */
270
+ const matArr = (m: Mat4Like): ArrayLike<number> => (m as { m?: ArrayLike<number> }).m ?? (m as ArrayLike<number>)