lecodes-cli 0.17.2 → 0.18.1

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 (62) hide show
  1. package/README.md +1 -1
  2. package/dist/index.js +2376 -755
  3. package/package.json +4 -4
  4. package/runtime/scene-harness.json +1 -1
  5. package/runtime/sdk/compile/aspectMacro.ts +52 -8
  6. package/runtime/sdk/compile/assetMacro.ts +116 -15
  7. package/runtime/sdk/compile/bundler.ts +39 -4
  8. package/runtime/sdk/compile/compileProject.ts +16 -1
  9. package/runtime/sdk/compile/header.ts +6 -1
  10. package/runtime/sdk/compile/index.ts +31 -0
  11. package/runtime/sdk/compile/liteMaterial.ts +247 -0
  12. package/runtime/sdk/compile/sceneEditor.ts +11 -1
  13. package/runtime/sdk/compile/shaderSchema.ts +202 -0
  14. package/runtime/sdk/compile/shaderTargets.ts +81 -0
  15. package/runtime/sdk/core/Aspect.ts +363 -95
  16. package/runtime/sdk/core/compWrite.ts +42 -0
  17. package/runtime/sdk/core/fields.ts +1 -1
  18. package/runtime/sdk/core/time.ts +81 -0
  19. package/runtime/sdk/g2/Camera2D.ts +8 -1
  20. package/runtime/sdk/g2/CharacterController2D.ts +253 -53
  21. package/runtime/sdk/g2/Node2D.ts +80 -10
  22. package/runtime/sdk/g2/OneWay2D.ts +66 -0
  23. package/runtime/sdk/g2/Physics2D.ts +240 -30
  24. package/runtime/sdk/g2/Scene2D.ts +33 -1
  25. package/runtime/sdk/g2/Shape2D.ts +218 -22
  26. package/runtime/sdk/g2/Trigger2D.ts +42 -12
  27. package/runtime/sdk/g2/groups2d.ts +106 -0
  28. package/runtime/sdk/g2/loop.ts +15 -4
  29. package/runtime/sdk/gl/Camera.ts +41 -0
  30. package/runtime/sdk/gl/CameraPlace.ts +52 -0
  31. package/runtime/sdk/gl/CharacterController.ts +184 -55
  32. package/runtime/sdk/gl/Gearbox.ts +212 -0
  33. package/runtime/sdk/gl/Geometry.ts +70 -9
  34. package/runtime/sdk/gl/IK.ts +193 -174
  35. package/runtime/sdk/gl/Light.ts +64 -2
  36. package/runtime/sdk/gl/Lightmap.ts +179 -0
  37. package/runtime/sdk/gl/Material.ts +36 -0
  38. package/runtime/sdk/gl/Mesh.ts +6 -23
  39. package/runtime/sdk/gl/Model.ts +23 -8
  40. package/runtime/sdk/gl/Node.ts +350 -285
  41. package/runtime/sdk/gl/Physics.ts +222 -126
  42. package/runtime/sdk/gl/Scene.ts +175 -8
  43. package/runtime/sdk/gl/Shape.ts +255 -12
  44. package/runtime/sdk/gl/Trigger.ts +1 -6
  45. package/runtime/sdk/gl/Vehicle.ts +473 -0
  46. package/runtime/sdk/gl/Wheel.ts +240 -0
  47. package/runtime/sdk/gl/{AnimationClip.ts → animation/AnimationClip.ts} +37 -7
  48. package/runtime/sdk/gl/animation/Animator.ts +87 -0
  49. package/runtime/sdk/gl/animation/Layer.ts +29 -0
  50. package/runtime/sdk/gl/animation/Loop.ts +25 -0
  51. package/runtime/sdk/gl/animation/Playback.ts +43 -0
  52. package/runtime/sdk/gl/animation/core.ts +294 -0
  53. package/runtime/sdk/gl/scenarios.ts +291 -349
  54. package/runtime/sdk/inject.ts +186 -162
  55. package/runtime/sdk/runtime/app.ts +13 -0
  56. package/runtime/sdk/runtime/input.ts +169 -6
  57. package/runtime/sdk/scene/defineScene.ts +1227 -1016
  58. package/runtime/sdk/scene/gizmos.ts +148 -0
  59. package/runtime/sdk/scene/material.ts +188 -0
  60. package/runtime/sdk-types.json +1 -1
  61. package/runtime/sdk/gl/Animator.ts +0 -642
  62. package/runtime/sdk/gl/ModelAnimation.ts +0 -95
@@ -0,0 +1,240 @@
1
+ // One wheel of a `Vehicle`, as an aspect on the wheel's own node. The node's position IS the wheel's
2
+ // position (where its centre rests on flat ground), and everything else about it lives here too:
3
+ //
4
+ // const car = new Node('car')
5
+ // .add(body, wheelFL.aspect(Wheel), wheelFR.aspect(Wheel),
6
+ // wheelRL.aspect(Wheel), wheelRR.aspect(Wheel))
7
+ // .aspect(Shape, { box: [0.9, 0.4, 2.1] })
8
+ // .aspect(Vehicle, { mass: 1200 })
9
+ //
10
+ // That is the whole minimum: `Vehicle` collects every `Wheel` under itself, groups them into axles by
11
+ // Z (front first), and the defaults fall out — the front axle steers, the rear one drives and carries
12
+ // the handbrake. Override any of it per wheel.
13
+ //
14
+ // This aspect is also what POSES the wheel: it runs in the LATE phase (after the physics step, before
15
+ // the frame draws) and writes the node's transform from the suspension length, steer angle and spin
16
+ // the engine reports. Nothing else writes that transform — the engine deliberately does not, so a
17
+ // wheel model's own conventions (which way its axle points, how big it looks) are settings here
18
+ // rather than constants in C++, and a part that should steer but NOT spin is simply a sibling node.
19
+ //
20
+ // Chassis space is forward −Z / up +Y, the SDK's own convention (`node.forward`).
21
+
22
+ import { Aspect } from "../core/Aspect"
23
+ import type { FieldMeta } from "../core/fields"
24
+ import { Mat4 } from "../math/mat4"
25
+ import { Quat } from "../math/quat"
26
+ import { Vec3, cx, cy, cz, type Vec3Like } from "../math/vec"
27
+ import { Gizmos } from "../scene/gizmos"
28
+ import { Node } from "./Node"
29
+ import { Shape } from "./Shape"
30
+ import type { Vehicle } from "./Vehicle"
31
+
32
+ /** Floats `vehicleGetState` writes before the per-wheel block: speed, rpm, contacts, vx, vy, vz. */
33
+ export const STATE_HEADER = 6
34
+ /** Floats per wheel: contact, slip, slipAngle, suspensionLength, steerDeg, spin. */
35
+ export const WHEEL_STATE = 6
36
+
37
+ /** How a tire behaves past its grip peak. `road` is Jolt's own curve — grip falls off after the peak,
38
+ * so the car can be made to let go. `arcade` holds the peak all the way out: much harder to spin. */
39
+ export type TireCurve = "road" | "arcade"
40
+
41
+ export interface WheelSuspension {
42
+ /** Total travel in metres, full droop to fully compressed (default 0.4). */
43
+ travel?: number
44
+ /** Spring frequency in Hz — bigger is stiffer (default 1.4; a race car ~2.5, a truck ~1). It also
45
+ * sets the ride-height sag, and the sag is how far the wheel can still extend DOWN. */
46
+ stiffness?: number
47
+ /** Damping ratio 0..1 (default 0.5). Low values pogo. */
48
+ damping?: number
49
+ }
50
+
51
+ export interface WheelTire {
52
+ /** Grip multiplier on the friction curves (default 1). The grip a wheel actually gets is combined
53
+ * with the ground it stands on as `sqrt(tire × groundFriction)`, and a body's friction defaults to
54
+ * 0.6 — so a road a car should really corner on wants `Physics { friction: 1 }`. */
55
+ grip?: number
56
+ /** Which friction curve (default `road`). */
57
+ curve?: TireCurve
58
+ }
59
+
60
+ export interface WheelVisual {
61
+ /** The MODEL's axle direction in its own space (default `[1, 0, 0]`). Set it instead of parenting
62
+ * the mesh under a corrective node when the art points another way. */
63
+ axis?: Vec3Like
64
+ /** Drawn radius, if the art is not exactly the physical `radius` — sinks a wheel into its arch or
65
+ * lets a fat tire overhang, with no effect on the simulation. Default: the physical radius. */
66
+ radius?: number
67
+ /** Let the model spin (default true). `false` keeps the steer angle and suspension travel but not
68
+ * the rotation — a brake caliper. */
69
+ spin?: boolean
70
+ }
71
+
72
+ const DEG2RAD = Math.PI / 180
73
+ const UP = new Vec3(0, 1, 0)
74
+
75
+ export class Wheel extends Aspect<"wheel", Node> {
76
+ static readonly aspect = "wheel"
77
+
78
+ /** Wheel radius in metres. Default: measured from the node's rendered bounds, else 0.35. Too small
79
+ * and the car scrapes, too large and it floats. */
80
+ radius?: number
81
+ /** Wheel width in metres. Default: measured, else 0.25. */
82
+ width?: number
83
+ /** Does this wheel steer? Default: the wheels on the front axle. */
84
+ steer?: boolean
85
+ /** Does the engine drive it? Default: from the vehicle's `drive` layout. */
86
+ drive?: boolean
87
+ /** Foot brake on this wheel. */
88
+ brake = true
89
+ /** Handbrake on this wheel. Default: every non-steering wheel (locking the front wheels of a moving
90
+ * car is not a handbrake turn, it is a crash). */
91
+ handbrake?: boolean
92
+ /** Axle group, front to back. Default: derived from Z. Set it for a car whose wheels are not in neat
93
+ * left/right pairs — an axle's wheels are paired for the differential and the anti-roll bar. */
94
+ axle?: number
95
+ /** Foot-brake torque in N·m (default 1500); the handbrake pulls 3× on the wheels that have it. */
96
+ brakeTorque = 1500
97
+
98
+ suspension: WheelSuspension = { travel: 0.4, stiffness: 1.4, damping: 0.5 }
99
+ tire: WheelTire = { grip: 1, curve: "road" }
100
+ visual: WheelVisual = {}
101
+
102
+ /** Scene-editor inspector. `steer` / `drive` / `handbrake` are deliberately absent: they are
103
+ * tri-state (undefined = derive it from the axle), which a switch cannot express. */
104
+ static fields: FieldMeta<Wheel> = {
105
+ radius: { min: 0.05, step: 0.01 },
106
+ width: { min: 0.02, step: 0.01 },
107
+ axle: { min: 0, step: 1 },
108
+ brake: { label: "Foot brake" },
109
+ brakeTorque: { label: "Brake torque", min: 0, step: 50 },
110
+ suspension: { hidden: true },
111
+ tire: { hidden: true },
112
+ visual: { hidden: true },
113
+ }
114
+ static editor = { rebuild: true }
115
+
116
+ /** @internal Set by `Vehicle` at attach — the car this wheel belongs to, and its index in the blob. */
117
+ _vehicle: Vehicle | null = null
118
+ /** @internal */
119
+ _index = -1
120
+ /** @internal Suspension attachment point in chassis space; the wheel hangs below it. */
121
+ _attach = new Vec3()
122
+ /** @internal Resting centre in chassis space (what the author placed). */
123
+ _rest = new Vec3()
124
+
125
+ private _angle = 0 // integrated spin, radians — the engine reports rate, not angle
126
+ private _scale = new Vec3(1, 1, 1) // the node's own scale, preserved through the pose write
127
+ private _local = true // is the node a direct child of the chassis?
128
+
129
+ onAttach(): void {
130
+ this._scale = this.node.scale
131
+ }
132
+
133
+ onDetach(): void {
134
+ this._vehicle = null
135
+ this._index = -1
136
+ }
137
+
138
+ /** @internal Called by Vehicle once the car exists, with the geometry it resolved. */
139
+ _bind(vehicle: Vehicle, index: number, rest: Vec3, attach: Vec3): void {
140
+ this._vehicle = vehicle
141
+ this._index = index
142
+ this._rest = rest
143
+ this._attach = attach
144
+ this._scale = this.node.scale
145
+ this._local = this.node.parent === vehicle.node
146
+ }
147
+
148
+ // ---- live state ------------------------------------------------------------------------------
149
+ // Every getter reads the car's ONE shared state buffer, which is refreshed once per frame.
150
+
151
+ private _state(k: number): number {
152
+ const v = this._vehicle
153
+ if (!v || this._index < 0) return 0
154
+ return v._wheelState(this._index, k)
155
+ }
156
+
157
+ /** Touching the ground this step. */
158
+ get contact(): boolean { return this._state(0) !== 0 }
159
+ /** Longitudinal slip RATIO: 0 = rolling in sync with the ground, ~1 = spinning up or locked.
160
+ * Unsigned — smoke, tire marks and wheelspin sound key off this. */
161
+ get slip(): number { return this._state(1) }
162
+ /** Slip ANGLE in degrees: how far the tire's travel direction is off from where it points.
163
+ * Unsigned, 0..90 — past the curve's peak (~3°) the tire is sliding sideways. Drift particles. */
164
+ get slipAngle(): number { return this._state(2) }
165
+ /** Steer angle in degrees, positive to the right. */
166
+ get steerAngle(): number { return this._state(4) }
167
+ /** Wheel spin in rad/s (× radius ≈ the speed the tire is laying down). */
168
+ get spin(): number { return this._state(5) }
169
+ /** Suspension compression, 0 = fully extended (drooping) … 1 = fully compressed. */
170
+ get compression(): number {
171
+ const travel = this.suspension.travel ?? 0.4
172
+ if (travel <= 0) return 0
173
+ const len = this._state(3)
174
+ const min = travel * 0.4
175
+ return Math.max(0, Math.min(1, (travel - len) / (travel - min)))
176
+ }
177
+
178
+ // ---- the visual ------------------------------------------------------------------------------
179
+
180
+ /** LATE phase: after the step and the transform sync, right before the frame draws. */
181
+ update(dt: number): void {
182
+ const v = this._vehicle
183
+ if (!v || this._index < 0 || !v.id) return
184
+
185
+ if (this.visual.spin !== false) this._angle += this._state(5) * dt
186
+
187
+ // Down the suspension from the attachment point by however far it currently hangs.
188
+ const length = this._state(3)
189
+ const centre = new Vec3(this._attach.x, this._attach.y - length, this._attach.z)
190
+
191
+ // Steer about the chassis' up axis, then spin about the MODEL's own axle in the steered frame.
192
+ // Both reports are negated, for the same reason: the engine describes them in the DRIVER's terms
193
+ // and the scene is right-handed with forward on −Z. Steer is reported right-positive while a yaw
194
+ // about +Y turns left. Spin is reported positive-means-forward, but a positive turn about the
195
+ // right-hand axle carries the top of the wheel to +Z — which rolls the car backwards.
196
+ const steer = Quat.fromAxisAngle(UP, -this._state(4) * DEG2RAD)
197
+ const axis = this.visual.axis ?? [1, 0, 0]
198
+ const rotation = this.visual.spin === false ? steer : steer.mul(Quat.fromAxisAngle(axis, -this._angle))
199
+
200
+ // A model that draws bigger or smaller than it collides scales on top of the node's own scale.
201
+ const vr = this.visual.radius
202
+ const k = vr !== undefined && this.radius ? vr / this.radius : 1
203
+ const scale = k === 1 ? this._scale : new Vec3(this._scale.x * k, this._scale.y * k, this._scale.z * k)
204
+
205
+ const m = Mat4.compose(centre, rotation, scale)
206
+ // The common case is a direct child of the chassis, where chassis space IS the local space.
207
+ if (this._local) this.node.matrix = m
208
+ else this.node.worldMatrix = new Mat4(v.node.worldMatrix).mul(m)
209
+ }
210
+
211
+ /** Edit mode: this wheel's own circle at its resting height, its travel range, and a mark when the
212
+ * engine drives it — enough to place a wheel without running the game. */
213
+ rebuild(): void {
214
+ const travel = this.suspension.travel ?? 0.4
215
+ const r = this.radius ?? this._measure().radius
216
+ const world = new Mat4(this.node.worldMatrix)
217
+ const P = (x: number, y: number, z: number): Vec3 => world.transformPoint([ x, y, z ])
218
+ const ring: Vec3[] = []
219
+ for (let i = 0; i < 24; i++) {
220
+ const t = (i / 24) * Math.PI * 2
221
+ ring.push(P(0, Math.sin(t) * r, Math.cos(t) * r))
222
+ }
223
+ Gizmos.polyline(ring, { color: this.steer === false ? "#9aa3b2" : "#5b8ef0", closed: true })
224
+ Gizmos.line(P(0, travel * 0.6, 0), P(0, -travel * 0.4, 0), { color: "#59606d" })
225
+ if (this.drive) Gizmos.cross(P(0, 0, 0), r * 0.35, { color: "#e0b25a" })
226
+ }
227
+
228
+ /** @internal Radius/width from the node's rendered bounds, so a placed model needs no numbers. */
229
+ _measure(): { radius: number, width: number } {
230
+ const b = Shape.boundsOf(this.node)
231
+ if (!b) return { radius: 0.35, width: 0.25 }
232
+ const size = new Vec3(cx(b.max) - cx(b.min), cy(b.max) - cy(b.min), cz(b.max) - cz(b.min))
233
+ // A wheel is a disc: its diameter is the larger of the two axes across the axle, and the width is
234
+ // the axle direction itself.
235
+ const axis = this.visual.axis ?? [1, 0, 0]
236
+ const along = Math.abs(cx(axis)) >= Math.abs(cz(axis)) ? size.x : size.z
237
+ const across = Math.max(Math.abs(cx(axis)) >= Math.abs(cz(axis)) ? size.z : size.x, size.y)
238
+ return { radius: across > 0 ? across * 0.5 : 0.35, width: along > 0 ? along : 0.25 }
239
+ }
240
+ }
@@ -1,7 +1,8 @@
1
1
  // AnimationClip — the unit of the animation system: immutable data (name, duration, tracks that
2
2
  // target bone NAMES, not entities). One representation for a GLB's embedded clips (model.anim.clips),
3
3
  // clips loaded from other files (Mixamo: one GLB per animation) and procedural clips built from
4
- // curves. An Animator binds clips to a skeleton by name. See docs/animation-plan.md.
4
+ // curves. An Animator binds clips to a skeleton by name. Clip EVENTS (`addEvent`) live here too —
5
+ // a fact about the clip's timeline, shared wherever it plays. See docs/animator-plan.md.
5
6
  //
6
7
  // const [hero, idle, run] = await Promise.all([
7
8
  // Model.load(asset('./hero.glb')),
@@ -11,9 +12,9 @@
11
12
  // const slash = await AnimationClip.load(asset('./attacks.glb'), 'Slash') // one out of many
12
13
  // const bob = AnimationClip.from({ tracks: { Hips: { position: [[0, [0,0,0]], [1, [0,0.05,0]]] } } })
13
14
 
14
- import { fetch, type FetchResponse } from "../runtime/fetch"
15
- import type { Vec3Like } from "../math/vec"
16
- import type { QuatLike } from "../math/quat"
15
+ import { fetch, type FetchResponse } from "../../runtime/fetch"
16
+ import type { Vec3Like } from "../../math/vec"
17
+ import type { QuatLike } from "../../math/quat"
17
18
 
18
19
  /** A keyframe: `[time (s), value]`. */
19
20
  export type ClipKey<V> = [number, V]
@@ -39,6 +40,8 @@ export type ClipInfo = { name: string, duration: number, trackCount: number }
39
40
  const PATH = { position: 0, rotation: 1, scale: 2 } as const
40
41
  const INTERP = { linear: 0, step: 1 } as const
41
42
 
43
+ const setCache = new Map<number, AnimationClip[]>()
44
+
42
45
  const readInfo = (setId: number): ClipInfo[] =>
43
46
  ((_creator.getClipSetInfo(setId) ?? []) as ClipInfo[]).map((c) => ({ name: c.name, duration: c.duration, trackCount: c.trackCount ?? 0 }))
44
47
 
@@ -61,6 +64,8 @@ export class AnimationClip {
61
64
  readonly _set: number
62
65
  /** @internal */
63
66
  readonly _index: number
67
+ /** @internal events: seconds + name, sorted (the engine gets them normalized via setClipEvents). */
68
+ _events: { t: number, name: string }[] = []
64
69
 
65
70
  private constructor(set: number, index: number, info: ClipInfo) {
66
71
  this._set = set
@@ -70,10 +75,32 @@ export class AnimationClip {
70
75
  this.trackCount = info.trackCount
71
76
  }
72
77
 
73
- /** @internal — wrap a clip of an existing native set (a GLB's embedded clips). */
78
+ /** @internal — a placeholder for a Playback that never started (unknown clip). */
79
+ static _none(): AnimationClip { return new AnimationClip(0, 0, { name: "", duration: 0, trackCount: 0 }) }
80
+
81
+ /** @internal — wrap the clips of an existing native set (a GLB's embedded clips). Cached per set
82
+ * so every model / clone sharing the set gets the SAME objects (events added on one apply to all —
83
+ * as they do in the engine). */
74
84
  static _ofSet(setId: number): AnimationClip[] {
75
85
  if (!setId) return []
76
- return readInfo(setId).map((info, i) => new AnimationClip(setId, i, info))
86
+ let clips = setCache.get(setId)
87
+ if (!clips) { clips = readInfo(setId).map((info, i) => new AnimationClip(setId, i, info)); setCache.set(setId, clips) }
88
+ return clips
89
+ }
90
+
91
+ /** Mark a moment of the clip (SECONDS from its start) with an event name: `kick.addEvent(0.4, 'hit')`
92
+ * → `anim.on('hit', (clip, layer) => …)` fires when the playhead crosses it, loops included.
93
+ * Events are part of the clip: every model playing it gets them; `slice()` keeps the ones inside
94
+ * the range, re-timed. Chainable. */
95
+ addEvent(time: number, name: string): this {
96
+ this._events.push({ t: Math.min(Math.max(0, time), this.duration), name })
97
+ this._events.sort((a, b) => a.t - b.t)
98
+ this._pushEvents()
99
+ return this
100
+ }
101
+ private _pushEvents(): void {
102
+ const d = this.duration
103
+ _creator.setClipEvents(this._set, this._index, new Float32Array(this._events.map((e) => (d > 0 ? e.t / d : 0))))
77
104
  }
78
105
 
79
106
  /** Load ONE clip from a GLB: the file's only/first clip, or the one named / at the given index. */
@@ -147,7 +174,10 @@ export class AnimationClip {
147
174
  const setId = _creator.sliceClip(this._set, this._index, st, e)
148
175
  if (setId === 0) throw new Error(`AnimationClip.slice: bad range ${start}${end !== undefined ? `–${end}` : ""} of '${this.name}' (${this.duration.toFixed(2)}s)`)
149
176
  const info = readInfo(setId)[0] ?? { name: this.name, duration: e - st, trackCount: this.trackCount }
150
- return new AnimationClip(setId, 0, info)
177
+ const out = new AnimationClip(setId, 0, info)
178
+ // the engine re-timed the event TIMES; carry the names the same way
179
+ out._events = this._events.filter((ev) => ev.t >= st - 1e-6 && ev.t <= e + 1e-6).map((ev) => ({ t: Math.min(Math.max(0, ev.t - st), e - st), name: ev.name }))
180
+ return out
151
181
  }
152
182
 
153
183
  private static _label(source: string | FetchResponse): string {
@@ -0,0 +1,87 @@
1
+ // Animator — THE animation system, reached as `node.anim`. Every Model carries one pre-attached (its
2
+ // clip list = the GLB's embedded clips; nothing native exists until the first play()). The whole
3
+ // per-frame loop — fades, blend spaces, one-shot fade-back, root motion — runs in the engine; the
4
+ // SDK only issues calls. See docs/animator-plan.md.
5
+ //
6
+ // const hero = await Model.load(asset('./hero.glb'))
7
+ // hero.anim.playLoop('Idle') // the layer's LOOP: what it rests on
8
+ // await hero.anim.play('Jump', { fadeIn: 0.1, fadeOut: 0.2 }) // a one-shot over it, back to the loop after
9
+ //
10
+ // hero.anim.addClip('slash', slash) // clips from other files / procedural / sliced
11
+ // const loco = hero.anim.playLoop({ Idle: 0, Walking: 2, 'Fast Run': 6 }) // a blend as the loop
12
+ // loco.value = hero.controller.velocity.length // where we are on the blend axis
13
+ // const kick = hero.anim.play('slash', { fadeIn: 0.1, fadeOut: 0.3 }) // resolves at its hand-over
14
+ // kick.clip.addEvent(0.4, 'hit'); hero.anim.on('hit', () => …)
15
+ // if (await kick) hero.anim.playLoop('Crouch', { fade: 0.3 }) // resolved at the hand-over: what you start now is what it fades into
16
+ // const upper = hero.anim.addLayer({ mask: 'Spine1' })
17
+ // upper.playLoop('Aim', { fade: 0.3 }) // arms aim, legs keep walking
18
+ //
19
+ // Any Node hierarchy works, not just Models: tracks bind to child names (a robot arm of meshes).
20
+
21
+ import { Aspect } from "../../core/Aspect"
22
+ import type { Node } from "../Node"
23
+ import type { AnimationClip } from "./AnimationClip"
24
+ import { Core, type ClipEventHandler, type LayerOptions, type LoopDef, type LoopOptions, type PlayOptions, type StopOptions } from "./core"
25
+ import type { Loop } from "./Loop"
26
+ import type { Layer } from "./Layer"
27
+ import type { Playback } from "./Playback"
28
+
29
+ export class Animator extends Aspect<"anim", Node> {
30
+ static readonly aspect = "anim"
31
+ private _c!: Core
32
+ private _rootMotion = false
33
+
34
+ onAttach(): void { this._c = new Core(this.node) }
35
+ onDetach(): void { this._c.destroy() }
36
+
37
+ // ---- clips ----
38
+ /** The clip list, in order: the GLB's embedded clips (file order), then the clips you added. An
39
+ * added clip with an embedded clip's name takes its place. */
40
+ get clips(): readonly AnimationClip[] { return this._c.clips() }
41
+ /** One clip by name, or by index into `clips` — e.g. to `slice()` it. `undefined` if there is none. */
42
+ clip(ref: string | number): AnimationClip | undefined { return this._c.resolveClip(ref)?.[1] }
43
+ /** Add a clip under a name (default: its own `name`) — from another file, procedural, or sliced.
44
+ * Overrides an embedded clip of the same name. Chainable. */
45
+ addClip(name: string | AnimationClip, clip?: AnimationClip): this {
46
+ const c = typeof name === "string" ? clip : name
47
+ const n = typeof name === "string" ? name : name.name
48
+ if (!c) { console.warn(`Animator.addClip('${n}'): no clip`); return this }
49
+ this._c.addClip(n, c)
50
+ return this
51
+ }
52
+
53
+ // ---- playing (the base layer) ----
54
+ /** Play a one-shot on the base layer — by name, index, or the first clip with no argument.
55
+ * Crossfades per the options (default: cut). Returns a Playback: `await` it — it resolves at the
56
+ * clip's hand-over (`true`; `false` if cut short), and what you start right after is what the clip
57
+ * fades into (another one-shot, `playLoop(next)`; nothing = back to the loop). */
58
+ play(clip?: string | number, options: PlayOptions = {}): Playback { return this._c.play(this._c.layers[0], clip, options) }
59
+ /** Set the base layer's LOOP — what it shows when no one-shot plays: a clip (`playLoop('Idle')`) or
60
+ * a blend space (`playLoop({ Idle: 0, Run: 6 })`, drive the returned object's `value`). Crossfades
61
+ * over `fade` from whatever plays — a one-shot included (it is cut short). `stop()` removes it. */
62
+ playLoop(def: LoopDef, options: LoopOptions = {}): Loop | undefined { return this._c.loop(this._c.layers[0], def, options) }
63
+ /** Fade everything out, on every layer (loops included) → rest pose. */
64
+ stop(options: StopOptions = {}): this { this._c.stopAll(options.fade ?? 0); return this }
65
+ /** The base layer's current loop (the object the last `playLoop()` returned), if any. */
66
+ get loop(): Loop | undefined { return this._c.layers[0].loop?.view }
67
+ /** A one-shot on the base layer hasn't handed over yet. */
68
+ get busy(): boolean { return this._c.busy(this._c.layers[0]) }
69
+
70
+ // ---- layers ----
71
+ /** A new layer on top (masked override / additive). The returned object is its handle. */
72
+ addLayer(options: LayerOptions = {}): Layer { return this._c.addLayer(options) }
73
+
74
+ // ---- clip events (`clip.addEvent(0.4, 'hit')`) ----
75
+ on(event: string, cb: ClipEventHandler): this { this._c.on(event, cb); return this }
76
+ off(event: string, cb: ClipEventHandler): this { this._c.off(event, cb); return this }
77
+
78
+ // ---- props ----
79
+ /** Global playback rate: 0.3 = slow-mo, 0 = pause. */
80
+ get speed(): number { return this._c.speed }
81
+ set speed(v: number) { this._c.setSpeed(v) }
82
+ /** Root motion: the root bone's horizontal travel comes OFF the pose and moves the node instead —
83
+ * or its CharacterController (on this node or an ancestor) as a velocity, so it collides. For
84
+ * clips whose hips actually travel (Mixamo without "In Place", lunges, rolls). */
85
+ get rootMotion(): boolean { return this._rootMotion }
86
+ set rootMotion(on: boolean) { this._rootMotion = on; this._c.setRootMotion(on) }
87
+ }
@@ -0,0 +1,29 @@
1
+ // Layer — one layer of an Animator (`anim.addLayer({ mask: 'Spine1' })` for the upper body,
2
+ // `{ additive: true }` for deltas stacked on top). The Animator's own play/stop/playLoop ARE its base
3
+ // layer; extra layers composite over it in creation order. The object is the layer's only handle.
4
+
5
+ import type { Core, LayerRec, LoopDef, LoopOptions, PlayOptions, StopOptions } from "./core"
6
+ import type { Loop } from "./Loop"
7
+ import type { Playback } from "./Playback"
8
+
9
+ export class Layer {
10
+ private readonly _r: LayerRec
11
+ private readonly _c: Core
12
+ /** @internal — created by the Animator. */
13
+ constructor(rec: LayerRec, core: Core) { this._r = rec; this._c = core }
14
+
15
+ /** Play a one-shot on this layer (crossfading per the options); resolves at its hand-over. */
16
+ play(clip?: string | number, options: PlayOptions = {}): Playback { return this._c.play(this._r, clip, options) }
17
+ /** Set / transition this layer's loop (a clip, or a blend space) — crossfades over `fade` from whatever
18
+ * the layer shows, a one-shot included (it is cut short). */
19
+ playLoop(def: LoopDef, options: LoopOptions = {}): Loop | undefined { return this._c.loop(this._r, def, options) }
20
+ /** Fade everything on this layer out — one-shots and its loop. */
21
+ stop(options: StopOptions = {}): this { this._c.stopLayer(this._r, options.fade ?? 0); return this }
22
+ /** This layer's current loop (the object the last `playLoop()` returned), if any. */
23
+ get loop(): Loop | undefined { return this._r.loop?.view }
24
+ /** Layer contribution 0–1. */
25
+ get weight(): number { return this._r.weight }
26
+ set weight(v: number) { this._r.weight = v; this._c.pushLayer(this._r) }
27
+ /** A one-shot on this layer hasn't handed over yet. */
28
+ get busy(): boolean { return this._c.busy(this._r) }
29
+ }
@@ -0,0 +1,25 @@
1
+ // Loop — a layer's LOOP: what it shows when no one-shot plays (`anim.playLoop('Idle')` — one looping clip,
2
+ // or `anim.playLoop({ Idle: 0, Walking: 2, Run: 6 })` — a blend whose members loop in phase and `value`
3
+ // picks the mix: 1D linear between neighbours, `[x, y]` positions = a 2D gradient band). One-shots fade
4
+ // it out and return to it; `playLoop(next)` crossfades to another; `stop()` removes it. The object
5
+ // returned by `playLoop()` (also `anim.loop`) is the handle; a replaced loop's object goes dead.
6
+
7
+ import type { BlendPosition, Core, LoopRec } from "./core"
8
+
9
+ export class Loop {
10
+ private readonly _r: LoopRec
11
+ private readonly _c: Core
12
+ /** @internal — created by playLoop(). */
13
+ constructor(rec: LoopRec, core: Core) { this._r = rec; this._c = core }
14
+
15
+ /** Position on the axis (number) or plane (`[x, y]`) — units are whatever the positions use. Live
16
+ * even while a one-shot plays (the loop returns at the new mix). */
17
+ get value(): BlendPosition { return this._r.value }
18
+ set value(v: BlendPosition) { this._c.setLoopValue(this._r, v) }
19
+ /** Each member's current contribution, 0–1 (fades included). */
20
+ get weights(): Record<string, number> {
21
+ const out: Record<string, number> = {}
22
+ for (const m of this._r.members) out[m.name] = this._c.slotWeight(m.slot)
23
+ return out
24
+ }
25
+ }
@@ -0,0 +1,43 @@
1
+ // Playback — the handle `play()` returns (docs/animator-plan.md). Thenable: `await anim.play('slash')`
2
+ // resolves at the clip's HAND-OVER — where its fade-back starts (`end − fadeOut`; the end when there
3
+ // is no fadeOut) — with `true`; `false` when it was cut short (replaced / stopped). What
4
+ // you call right after the await is what the clip fades into: `anim.play(next)` (a chained one-shot,
5
+ // crossfaded), `anim.playLoop(next)` — nothing = back to the loop (or hold, on a layer without one).
6
+ // Returning one from an `async` function flattens it into `Promise<boolean>` — return `p.done` (or
7
+ // make the function sync) when the caller needs the handle.
8
+
9
+ import type { AnimationClip } from "./AnimationClip"
10
+ import type { Core, PlaybackRec, StopOptions } from "./core"
11
+ import type { Layer } from "./Layer"
12
+
13
+ export class Playback implements PromiseLike<boolean> {
14
+ private readonly _r: PlaybackRec
15
+ private readonly _c: Core
16
+ /** @internal — created by play(). */
17
+ constructor(rec: PlaybackRec, core: Core) { this._r = rec; this._c = core }
18
+
19
+ /** The clip that plays. */
20
+ get clip(): AnimationClip { return this._r.slot.clip }
21
+ /** The layer it plays on. */
22
+ get layer(): Layer { return this._r.slot.layer.view }
23
+ /** Clock (s). */
24
+ get time(): number { return this._c.slotTime(this._r.slot) }
25
+ /** 0–1 through the clip (the current cycle, when looping). */
26
+ get progress(): number { const d = this.clip.duration; return d > 0 ? this.time / d : 0 }
27
+ /** Not handed over yet (the clip still owns the layer). */
28
+ get playing(): boolean { return this._r.playing }
29
+ /** Current contribution to the pose, 0–1 — moves during crossfades. */
30
+ get weight(): number { return this._r.slot.playback === this._r ? this._c.slotWeight(this._r.slot) : 0 }
31
+ /** Resolves at the hand-over (`true`) or when cut short (`false`) — the promise `await playback`
32
+ * uses; the one to return from async functions or put in `Promise.all`. */
33
+ get done(): Promise<boolean> { return this._r.done }
34
+
35
+ then<A = boolean, B = never>(onFulfilled?: ((v: boolean) => A | PromiseLike<A>) | null, onRejected?: ((e: unknown) => B | PromiseLike<B>) | null): Promise<A | B> {
36
+ return this._r.done.then(onFulfilled, onRejected)
37
+ }
38
+
39
+ /** Move the clock (s). */
40
+ seek(time: number): this { this._c.seek(this._r.slot, time); return this }
41
+ /** Cut this clip short: fade it out (the layer's loop returns if nothing else is coming in). */
42
+ stop(options: StopOptions = {}): this { this._c.stopSlot(this._r.slot, options.fade ?? 0); return this }
43
+ }