@margoengine/animation 0.0.0-stage → 0.1.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 (67) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +4 -0
  3. package/README.md +1054 -3
  4. package/dist/batch.d.ts +155 -0
  5. package/dist/clip-utils.d.ts +50 -0
  6. package/dist/clip-utils.js +1 -0
  7. package/dist/clone.d.ts +15 -0
  8. package/dist/deform-readers-DmYAkvBK.js +1 -0
  9. package/dist/deform-readers.d.ts +5 -0
  10. package/dist/deformed-points.d.ts +87 -0
  11. package/dist/deformed-points.js +17 -0
  12. package/dist/discrete-tracks.d.ts +102 -0
  13. package/dist/discrete-tracks.js +1 -0
  14. package/dist/dqs.d.ts +41 -0
  15. package/dist/dqs.js +29 -0
  16. package/dist/errors-t1ewumJS.js +1 -0
  17. package/dist/geometry-cache.d.ts +208 -0
  18. package/dist/geometry-cache.js +4 -0
  19. package/dist/gltf-C2HVNxzB.js +1 -0
  20. package/dist/gltf.d.ts +63 -0
  21. package/dist/group.d.ts +97 -0
  22. package/dist/hdr-format-cmvLFubB.js +1 -0
  23. package/dist/index.d.ts +201 -0
  24. package/dist/index.js +1 -0
  25. package/dist/instanced-morph.d.ts +82 -0
  26. package/dist/instanced-morph.js +13 -0
  27. package/dist/instanced-skin.d.ts +82 -0
  28. package/dist/instanced-skin.js +43 -0
  29. package/dist/interactivity.d.ts +71 -0
  30. package/dist/interactivity.js +4 -0
  31. package/dist/key-cursor.d.ts +23 -0
  32. package/dist/keyframes-BO50xipp.js +4 -0
  33. package/dist/keyframes.d.ts +204 -0
  34. package/dist/lod.d.ts +87 -0
  35. package/dist/lod.js +4 -0
  36. package/dist/material-animation.d.ts +29 -0
  37. package/dist/mixer.d.ts +226 -0
  38. package/dist/mixer.js +4 -0
  39. package/dist/morph-gpu.d.ts +76 -0
  40. package/dist/morph-gpu.js +48 -0
  41. package/dist/playback.d.ts +94 -0
  42. package/dist/playback.js +4 -0
  43. package/dist/point-cache.d.ts +28 -0
  44. package/dist/point-cache.js +1 -0
  45. package/dist/pointer-BOFnz0gk.js +1 -0
  46. package/dist/pointer.d.ts +43 -0
  47. package/dist/pointer.js +1 -0
  48. package/dist/pose-source-MuCl8VDd.js +1 -0
  49. package/dist/pose.d.ts +7 -0
  50. package/dist/require-webgpu-Jrqt3Xy4.js +1 -0
  51. package/dist/retarget.d.ts +107 -0
  52. package/dist/rigid.d.ts +42 -0
  53. package/dist/sampling-DjDWYqt2.js +1 -0
  54. package/dist/sampling.d.ts +112 -0
  55. package/dist/sampling.js +1 -0
  56. package/dist/shader-CgAVFeOl.js +66 -0
  57. package/dist/shader.d.ts +30 -0
  58. package/dist/skeleton-utils.d.ts +2 -0
  59. package/dist/skeleton-utils.js +4 -0
  60. package/dist/skin.d.ts +163 -0
  61. package/dist/src-WGCsukxV.js +4 -0
  62. package/dist/vat-mWaj5B5R.js +50 -0
  63. package/dist/vat.d.ts +178 -0
  64. package/dist/vat.js +1 -0
  65. package/dist/vertex-map-BC_WH7ER.js +1 -0
  66. package/dist/weight-buffer.d.ts +1 -0
  67. package/package.json +133 -6
package/dist/lod.d.ts ADDED
@@ -0,0 +1,87 @@
1
+ import type { EngineKernel } from '@margoengine/core';
2
+ import type { Engine, EnginePlugin } from '@margoengine/core/extension';
3
+ import type { Animation } from './index.js';
4
+ /** One detail level. A copy takes the last tier whose `distance` it has reached. */
5
+ export interface AnimationLODTier {
6
+ /** World units from the camera at which this tier starts, >= 0. Tiers are given nearest first; the first is 0. */
7
+ distance: number;
8
+ /** Frames between updates: 1 is every frame, 4 every fourth. An integer >= 1. */
9
+ interval: number;
10
+ /** Deepest node level still animated, counted from the scene roots (0). Deeper nodes hold. Default: all. */
11
+ depth?: number;
12
+ }
13
+ /** Options for {@link AnimationLOD}. */
14
+ export interface AnimationLODOptions {
15
+ /** Detail levels, nearest first. Default {@link defaultLODTiers}. */
16
+ tiers?: readonly AnimationLODTier[];
17
+ /** Used while a copy is off screen, at any distance. Default `{distance: 0, interval: 16, depth: 1}`. */
18
+ hidden?: AnimationLODTier;
19
+ }
20
+ /** One copy's options for {@link AnimationLOD.add}. */
21
+ export interface AnimationLODMember {
22
+ /** Radius of the sphere around the model root tested against the view, in world units. Default 2. */
23
+ radius?: number;
24
+ }
25
+ /** What one {@link AnimationLOD.update} did. */
26
+ export interface AnimationLODStats {
27
+ /** Copies posed this frame. */
28
+ updated: number;
29
+ /** Copies left as they were this frame. */
30
+ skipped: number;
31
+ /** Copies off screen. */
32
+ hidden: number;
33
+ }
34
+ /** Every frame up close, every second frame from 15 units, every fourth and only four levels deep from 40. */
35
+ export declare const defaultLODTiers: readonly AnimationLODTier[];
36
+ /**
37
+ * Takes over the playback of many `Animation`s and updates each as often as its distance and visibility call for:
38
+ * near copies every frame, far ones less often and with only their upper bones, off-screen ones rarely. Skipped time is
39
+ * kept, so a copy that is updated again lands exactly where it would have been. A copy's clip, speed and loop still
40
+ * come from its `Animation`.
41
+ *
42
+ * @example
43
+ * ```ts
44
+ * const lod = AnimationLOD.attach(stage.engine);
45
+ * for (const animation of crowd) lod.add(animation, {radius: 1.5});
46
+ * ```
47
+ */
48
+ export declare class AnimationLOD implements EnginePlugin {
49
+ readonly name: string;
50
+ /** What the last update did. */
51
+ readonly stats: AnimationLODStats;
52
+ private readonly tiers;
53
+ private readonly hidden;
54
+ private readonly members;
55
+ private readonly quaternion;
56
+ private engine?;
57
+ private frame;
58
+ private next;
59
+ private disposed;
60
+ private elapsed;
61
+ /** Seconds this LOD has advanced its copies by. A fresh LOD reads 0. */
62
+ get time(): number;
63
+ /** Same as `engine.use(new AnimationLOD(...))`; returns it. */
64
+ static attach(engine: EngineKernel, options?: AnimationLODOptions): AnimationLOD;
65
+ constructor({ tiers, hidden }?: AnimationLODOptions);
66
+ /** Copies under this LOD. */
67
+ get count(): number;
68
+ /** Takes over a copy's playback from its current time; `remove` hands it back. */
69
+ add(animation: Animation, { radius }?: AnimationLODMember): this;
70
+ /** Hands a copy back to its `Animation`, fully posed at the time it has reached. */
71
+ remove(animation: Animation): boolean;
72
+ /** The tier a copy is on after the last update, or undefined if it is not under this LOD. */
73
+ tierOf(animation: Animation): AnimationLODTier | undefined;
74
+ setup(engine: Engine): void;
75
+ onPreUpdate(delta: number): void;
76
+ /** Advances every copy by `delta` seconds, posing those whose turn it is. */
77
+ update(delta: number): void;
78
+ /**
79
+ * Advances every copy's clock by `delta` seconds and picks its tier and turn from the camera, posing nothing: the
80
+ * CPU part of `update`, which a seek from `@margoengine/cutscene/seek` replays (the same turns as a continuous run
81
+ * when the camera is where it was); the next update poses the copies whose turn came, at the time they reached.
82
+ */
83
+ advanceTime(delta: number): void;
84
+ private pose;
85
+ dispose(): void;
86
+ [Symbol.dispose]: () => void;
87
+ }
package/dist/lod.js ADDED
@@ -0,0 +1,4 @@
1
+ // @margo/core-built 0.1.0
2
+ import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
3
+
4
+ import{o as e}from"./sampling-DjDWYqt2.js";import{MargoError as t}from"@margoengine/math/errors";var n=Object.freeze([Object.freeze({distance:0,interval:1}),Object.freeze({distance:15,interval:2}),Object.freeze({distance:40,interval:4,depth:4})]);function r(e,t){if(!Number.isFinite(e?.distance)||e.distance<0||!Number.isInteger(e.interval)||e.interval<1||e.depth!==void 0&&!(Number.isInteger(e.depth)&&e.depth>=0))throw RangeError(`${t} is invalid; use a distance >= 0, an integer interval >= 1 and an integer depth >= 0`)}function i(e){let t=e.model.asset.doc.nodes??[],n=new Int32Array(t.length),r=e=>t[e]?.children??[],i=new Uint8Array(t.length);for(let e=0;e<t.length;e++)for(let t of r(e))i[t]=1;let a=[];for(let e=0;e<t.length;e++)i[e]||a.push(e);for(;a.length;){let e=a.pop();for(let t of r(e))n[t]=n[e]+1,a.push(t)}return n}var a=0,o=class o{coreRequirement=__margoCoreRequirement("0.1.0",import.meta.url);get time(){return this.elapsed}static attach(e,t){__margoAssertCore(e,__margoCoreRequirement("0.1.0",import.meta.url));let n=new o(t);return e.use(n),n}constructor({tiers:e=n,hidden:t={distance:0,interval:16,depth:1}}={}){if(this.name=`animation-lod:`+a++,this.stats={updated:0,skipped:0,hidden:0},this.members=/* @__PURE__ */ new Map,this.quaternion=[0,0,0,1],this.frame=0,this.next=0,this.disposed=!1,this.elapsed=0,!Array.isArray(e)||!e.length)throw TypeError(`AnimationLOD tiers must be a non-empty array`);e.forEach((t,n)=>{if(r(t,`AnimationLOD tier ${n}`),n?t.distance<=e[n-1].distance:t.distance!==0)throw RangeError(`AnimationLOD tiers must start at distance 0 and increase`)}),r(t,`AnimationLOD hidden tier`),this.tiers=e,this.hidden=t}get count(){return this.members.size}add(e,{radius:n=2}={}){if(this.disposed)throw new t(`disposed`,`AnimationLOD is disposed; create a new one`);if(!Number.isFinite(n)||n<0)throw RangeError(`AnimationLOD radius must be a finite number >= 0`);let r=this.members.get(e);return r?(r.radius=n,this):(this.members.set(e,{animation:e,radius:n,phase:this.next++,owed:0,due:!1,time:e.time,playing:e.playing,tier:this.tiers[0],levels:i(e)}),e.playing=!1,this)}remove(e){let t=this.members.get(e);return t?(this.members.delete(e),!e.disposed&&!e.model.disposed&&(e.seek(t.time+t.owed*(e.options.speed??1)),e.playing=t.playing),!0):!1}tierOf(e){return this.members.get(e)?.tier}setup(e){if(this.disposed)throw new t(`disposed`,`AnimationLOD is disposed; create a new controller before attaching`);this.engine=e}onPreUpdate(e){this.update(e)}update(e){this.advanceTime(e);for(let e of this.members.values())e.due&&(e.due=!1,this.pose(e,e.tier))}advanceTime(e){if(this.disposed)return;if(!Number.isFinite(e)||e<0)throw RangeError(`Invalid animation delta; pass a finite delta >= 0 seconds`);this.elapsed+=e;let t=this.engine?.camera,n=this.stats,r=this.frame++;n.updated=n.skipped=n.hidden=0;for(let i of this.members.values()){let{animation:a}=i;if(a.disposed||a.model.disposed){this.members.delete(a);continue}let o=a.model.root.matrix,s=o[12],c=o[13],l=o[14],u=this.tiers[0],d=!0;if(t){let e=t.position,n=Math.hypot(s-e[0],c-e[1],l-e[2]),r=t.planes;for(let e of this.tiers)n>=e.distance&&(u=e);for(let e=0;d&&e<24;e+=4)d=r[e]*s+r[e+1]*c+r[e+2]*l+r[e+3]>=-i.radius}d||(u=this.hidden,n.hidden++),i.tier=u,i.owed+=e,(r+i.phase)%u.interval?n.skipped++:(i.time+=i.owed*(a.options.speed??1),i.owed=0,i.due=!0,n.updated++)}}pose({animation:t,time:n,levels:r},i){if(i.depth===void 0){t.seek(n);return}let a=t.clips[t.clip];if(!a)return;let o=(t.options.loop??!0)&&a.duration>0?n%a.duration:Math.min(n,a.duration),s=t.model.nodes;t.time=n;for(let n of a.tracks){if(n.path!==`weights`&&r[n.node]>i.depth)continue;let a=e(n.times,n.values,n.width,o,n.interpolation,n.path===`rotation`,n.sample),c=s[n.node];if(n.path===`translation`)c.setPosition(a);else if(n.path===`scale`)c.setScale(a);else if(n.path===`rotation`){for(let e=0;e<4;e++)this.quaternion[e]=a[e];c.setQuaternion(this.quaternion)}else for(let e of t.model.primitives)e.nodeIndex===n.node&&e.weights.set(a)}}dispose(){if(!this.disposed){this.disposed=!0;for(let e of[...this.members.keys()])this.remove(e);this.engine?.sceneOf(this)?.removePlugin(this.name)}}[Symbol.dispose??Symbol()](){this.dispose()}};export{o as AnimationLOD,n as defaultLODTiers};
@@ -0,0 +1,29 @@
1
+ import { PBRModel } from '@margoengine/gltf/pbr-model';
2
+ import { type AnimationDefinition } from './gltf.js';
3
+ type Property = 'offset' | 'scale';
4
+ interface MaterialTrack {
5
+ material: number;
6
+ property: Property;
7
+ times: Float32Array;
8
+ values: Float32Array;
9
+ }
10
+ /** @internal Validate only the fixed material pointer subset; leave ordinary node parsing to Animation. */
11
+ export declare function materialTracks(model: PBRModel, def: AnimationDefinition): {
12
+ tracks: MaterialTrack[];
13
+ nodeChannels: unknown[];
14
+ duration: number;
15
+ };
16
+ /**
17
+ * Create a fixed-target STEP texture-transform player for an original glTF clip index (default 0).
18
+ * seek uses finite nonnegative seconds, clamps by default, or wraps at the selected clip duration when loop is true.
19
+ * A zero-duration single-key clip always holds its key. Construction does not seek; dispose releases ownership,
20
+ * leaves the displayed sample intact and is safe to repeat. The model disposes its player automatically.
21
+ */
22
+ export declare function createMaterialAnimation(model: PBRModel, options?: {
23
+ clip?: number;
24
+ loop?: boolean;
25
+ }): {
26
+ seek(seconds: number): void;
27
+ dispose(): void;
28
+ };
29
+ export {};
@@ -0,0 +1,226 @@
1
+ /// <reference lib="esnext.disposable" preserve="true" />
2
+ import { Animation, type KeyframeClip } from '@margoengine/animation';
3
+ import type { Engine, EnginePlugin } from '@margoengine/core/extension';
4
+ import type { EngineKernel } from '@margoengine/core';
5
+ import type { DiscreteClip, BoundDiscreteTrack, DiscreteValue } from './discrete-tracks.js';
6
+ /** Play once, clamping at the directional endpoint. */
7
+ export declare const LoopOnce = 2200;
8
+ /** Repeat from the opposite endpoint. Default loop mode. */
9
+ export declare const LoopRepeat = 2201;
10
+ /** Alternate forward and backward traversals. */
11
+ export declare const LoopPingPong = 2202;
12
+ /** Weighted replacement, with the original property filling weight below one. */
13
+ export declare const NormalAnimationBlendMode = 2500;
14
+ /** Add translation/property deltas, multiply scale deltas and compose quaternion deltas. */
15
+ export declare const AdditiveAnimationBlendMode = 2501;
16
+ /** Supported action loop modes. */
17
+ export type ActionLoop = typeof LoopOnce | typeof LoopRepeat | typeof LoopPingPong;
18
+ /** A parsed glTF clip or a code-authored keyframe clip. */
19
+ export type ActionClip = Animation['clips'][number] | KeyframeClip | DiscreteClip;
20
+ /** A model, existing Animation, Skeleton, or object hosting bound property tracks. */
21
+ export type MixerRoot = object;
22
+ type Binding = {
23
+ base: Float64Array;
24
+ value: Float64Array;
25
+ total: number;
26
+ quaternion: boolean;
27
+ scale: boolean;
28
+ applied: boolean;
29
+ read(): ArrayLike<number>;
30
+ write(value: Float64Array): void;
31
+ };
32
+ type Channel = {
33
+ binding: Binding;
34
+ sample(time: number): ArrayLike<number>;
35
+ };
36
+ type DiscreteBinding = {
37
+ base: DiscreteValue;
38
+ value: DiscreteValue;
39
+ total: number;
40
+ winner: number;
41
+ applied: boolean;
42
+ channel: BoundDiscreteTrack;
43
+ };
44
+ type DiscreteChannel = {
45
+ binding: DiscreteBinding;
46
+ sample(time: number): DiscreteValue;
47
+ };
48
+ /** One cached clip playback, with an independent clock, weight and scheduled fades/warps. */
49
+ export declare class AnimationAction {
50
+ private readonly mixer;
51
+ private readonly clip;
52
+ private readonly root;
53
+ readonly blendMode: number;
54
+ private readonly channels;
55
+ private readonly discrete;
56
+ /** Local cycle time in seconds. Default 0. */
57
+ time: number;
58
+ /** Signed clip seconds per mixer second. Default 1. */
59
+ timeScale: number;
60
+ /** Contribution before a fade multiplier. Default 1. */
61
+ weight: number;
62
+ /** False mutes the action and stops its clock. Default true. */
63
+ enabled: boolean;
64
+ /** Freeze the clip clock while retaining its pose. Default false. */
65
+ paused: boolean;
66
+ /** Hold the last pose after finite playback. Default false (disable at completion). */
67
+ clampWhenFinished: boolean;
68
+ /** LoopRepeat by default. */
69
+ loop: ActionLoop;
70
+ /** Total traversals, Infinity by default; ignored by LoopOnce. */
71
+ repetitions: number;
72
+ private scheduled;
73
+ private loops;
74
+ private fade?;
75
+ private speed?;
76
+ private start?;
77
+ /** What the last clock step left for the blend: the clip time to sample and its weight (0: no contribution). */
78
+ private sampled;
79
+ private contribution;
80
+ /** @internal Actions are cached by AnimationMixer.clipAction. */
81
+ constructor(mixer: AnimationMixer, clip: ActionClip, root: MixerRoot, blendMode?: number, channels?: Channel[], discrete?: DiscreteChannel[]);
82
+ /** Start/resume without resetting the clock. */
83
+ play(): this;
84
+ /** Stop, restore original properties on the next mixer update, and reset. */
85
+ stop(): this;
86
+ /** Rewind, enable, unpause and clear envelopes. */
87
+ reset(): this;
88
+ /** Schedule a mixer-time start without changing the local clock. */
89
+ startAt(time: number): this;
90
+ /** Whether play() scheduled this action. */
91
+ isScheduled(): boolean;
92
+ /** Whether the action clock can currently advance. */
93
+ isRunning(): boolean;
94
+ /** Clip this action samples. */
95
+ getClip(): ActionClip;
96
+ /** Owning mixer. */
97
+ getMixer(): AnimationMixer;
98
+ /** Root this action affects. */
99
+ getRoot(): MixerRoot;
100
+ /** Current weight including enabled and fading. */
101
+ getEffectiveWeight(): number;
102
+ /** Current rate including pause and warping. */
103
+ getEffectiveTimeScale(): number;
104
+ private fadeFactor;
105
+ private rate;
106
+ /** Set contribution and cancel fading. */
107
+ setEffectiveWeight(weight: number): this;
108
+ /** Set rate and cancel warping. Negative rates run backwards. */
109
+ setEffectiveTimeScale(scale: number): this;
110
+ /** Set a positive wall-time duration for one traversal. */
111
+ setDuration(seconds: number): this;
112
+ /** Copy another action's clock/rate and cancel warping. */
113
+ syncWith(action: AnimationAction): this;
114
+ /** Select a mode and total traversal count. Default repetitions Infinity. */
115
+ setLoop(mode: ActionLoop, repetitions?: number): this;
116
+ private envelope;
117
+ /** Multiply weight by a ramp from zero to one. */
118
+ fadeIn(duration: number): this;
119
+ /** Multiply weight by a ramp from one to zero. */
120
+ fadeOut(duration: number): this;
121
+ /** Cancel the scheduled fade, retaining base weight. */
122
+ stopFading(): this;
123
+ /** Schedule absolute signed rates over mixer seconds. */
124
+ warp(from: number, to: number, duration: number): this;
125
+ /** Slow to a stop. */
126
+ halt(duration: number): this;
127
+ /** Cancel scheduled warping. */
128
+ stopWarping(): this;
129
+ /** Fade this action out and the destination in, optionally matching cycle rates during the transition. */
130
+ crossFadeTo(action: AnimationAction, duration: number, warp?: boolean): this;
131
+ /** Fade from another action into this one. */
132
+ crossFadeFrom(action: AnimationAction, duration: number, warp?: boolean): this;
133
+ /**
134
+ * @internal One step of the action clock (start time, warp and fade ends, loops), keeping the clip time and weight
135
+ * it reaches for {@link contribute}. The mixer's `advanceTime` runs it for every action.
136
+ */
137
+ step(delta: number): void;
138
+ /** @internal Adds the channels at the clip time of the last {@link step} to the mixer, at its weight. */
139
+ contribute(): void;
140
+ /** @internal Binding ownership for cache eviction. */
141
+ uses(binding: Binding): boolean;
142
+ /** @internal Categorical binding ownership for activation and cache eviction. */
143
+ usesDiscrete(binding: DiscreteBinding): boolean;
144
+ /** @internal Reset cycle bookkeeping for absolute seeks. */
145
+ rewind(): void;
146
+ private finish;
147
+ }
148
+ /** Independent clip actions on one or more roots. Call update(delta) or register as an engine plugin. */
149
+ export declare class AnimationMixer implements EnginePlugin {
150
+ private readonly root;
151
+ /** Creates and registers a mixer for a root; disposing it removes its engine registration. */
152
+ static attach(engine: EngineKernel, root: MixerRoot): AnimationMixer;
153
+ /** Unique plugin identity. */
154
+ readonly name: string;
155
+ /** Global seconds. Default 0. */
156
+ time: number;
157
+ /** Global signed rate. Default 1. */
158
+ timeScale: number;
159
+ private readonly actions;
160
+ private readonly players;
161
+ private readonly owned;
162
+ private readonly bindings;
163
+ private readonly discreteBindings;
164
+ private engine?;
165
+ private disposed;
166
+ private readonly additive;
167
+ /** Construct over a model, existing Animation or Skeleton. Existing Animation playback is paused. */
168
+ constructor(root: MixerRoot);
169
+ /** @internal Guard all new work after disposal. */
170
+ assertLive(): void;
171
+ /** @internal A disposed model/player cannot start another action. */
172
+ assertRootLive(root: MixerRoot): void;
173
+ private rootAlive;
174
+ /** @internal Capture original values when a property's first action starts. */
175
+ activate(bindings: readonly Binding[]): void;
176
+ /** @internal Restore original values when its last action stops. */
177
+ deactivate(bindings: readonly Binding[]): void;
178
+ /** @internal Capture categorical originals on first activation. */
179
+ activateDiscrete(bindings: readonly DiscreteBinding[]): void;
180
+ /** @internal Restore categorical originals on last deactivation. */
181
+ deactivateDiscrete(bindings: readonly DiscreteBinding[]): void;
182
+ private player;
183
+ private resolve;
184
+ /** Return the cached action for this clip/root/blend mode, creating its bindings once. */
185
+ clipAction(clip: ActionClip | string | number, root?: object, blendMode?: number): AnimationAction;
186
+ /** Existing cached action or null. */
187
+ existingAction(clip: ActionClip | string | number, root?: object): AnimationAction | null;
188
+ /** Default animation root. */
189
+ getRoot(): MixerRoot;
190
+ /** Advance independent action clocks, then blend once per affected property. */
191
+ update(delta: number): this;
192
+ /**
193
+ * Moves the mixer clock by `delta` seconds times `timeScale` and steps every action's clock (start times, fades,
194
+ * warps, loops), writing no property: the CPU part of `update`, which a seek from `@margoengine/cutscene/seek`
195
+ * replays. The next update blends and writes the properties at the times reached.
196
+ */
197
+ advanceTime(delta: number): void;
198
+ /** Blends every action's last step once per affected property and writes it. */
199
+ private blend;
200
+ /** Seek global playback from the beginning, scaling by timeScale. */
201
+ setTime(time: number): this;
202
+ /** Stop and rewind all actions, restoring captured original properties. */
203
+ stopAllAction(): this;
204
+ /** Remove cached actions for a clip/root. Stop them first. */
205
+ uncacheAction(clip: ActionClip | string | number, root?: object): void;
206
+ /** Remove all actions using a clip. */
207
+ uncacheClip(clip: ActionClip): void;
208
+ /** Stop and remove actions using a root. */
209
+ uncacheRoot(root: MixerRoot): void;
210
+ /** Engine plugin setup; no GPU resources of its own. */
211
+ setup(engine: Engine): void;
212
+ /** Engine plugin clock hook. */
213
+ onPreUpdate(delta: number): void;
214
+ /** Restore originals, detach by identity and release only Animations this mixer created. */
215
+ dispose(): void;
216
+ [Symbol.dispose]: () => void;
217
+ /** @internal Shared property accumulation, with deferred additive composition. */
218
+ accumulate(b: Binding, value: ArrayLike<number>, weight: number, mode: number): void;
219
+ private binding;
220
+ private bind;
221
+ private property;
222
+ private bindDiscrete;
223
+ /** @internal Categorical winner selection never averages booleans or string indices. */
224
+ accumulateDiscrete(binding: DiscreteBinding, value: DiscreteValue, weight: number): void;
225
+ }
226
+ export {};
package/dist/mixer.js ADDED
@@ -0,0 +1,4 @@
1
+ // @margo/core-built 0.1.0
2
+ import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
3
+
4
+ import{n as e}from"./errors-t1ewumJS.js";import{MargoError as t}from"@margoengine/math/errors";import{Animation as n,Skeleton as r,sampleKeyframes as i}from"@margoengine/animation";import{sampleTrackInto as a}from"@margoengine/animation/sampling";var o=t=>Object.assign(e(t,`arguments`),{code:`arguments`}),s=2200,c=2201,l=2202,u=2500,d=2501,f=e=>`kind`in e&&e.kind===`discrete`,p=(e,t,n=-1/0)=>{if(!Number.isFinite(e)||e<n)throw o(`Invalid ${t}; pass a finite number >= ${n}`);return e},m=(e,t)=>e.from+(e.to-e.from)*Math.max(0,Math.min(1,(t-e.start)/e.duration));function h(e,t,n,r){let i=0;for(let n=0;n<4;n++)i+=e[n]*t[n];let a=i<0?-1:1;i=Math.min(1,Math.abs(i));let o=1-n,s=n;if(i<.9995){let e=Math.acos(i),t=Math.sin(e);o=Math.sin((1-n)*e)/t,s=Math.sin(n*e)/t}for(let n=0;n<4;n++)r[n]=e[n]*o+t[n]*s*a;let c=Math.hypot(...r);for(let e=0;e<4;e++)r[e]/=c}var g=class{constructor(e,t,n,r=u,i=[],a=[]){this.mixer=e,this.clip=t,this.root=n,this.blendMode=r,this.channels=i,this.discrete=a,this.time=0,this.timeScale=1,this.weight=1,this.enabled=!0,this.paused=!1,this.clampWhenFinished=!1,this.loop=c,this.repetitions=1/0,this.scheduled=!1,this.loops=0,this.sampled=0,this.contribution=0}play(){return this.mixer.assertLive(),this.mixer.assertRootLive(this.root),this.scheduled||this.mixer.activate(this.channels.map(e=>e.binding)),this.scheduled||this.mixer.activateDiscrete(this.discrete.map(e=>e.binding)),this.scheduled=!0,this}stop(){return this.scheduled=!1,this.mixer.deactivate(this.channels.map(e=>e.binding)),this.mixer.deactivateDiscrete(this.discrete.map(e=>e.binding)),this.reset()}reset(){return this.time=this.loops=0,this.enabled=!0,this.paused=!1,this.fade=this.speed=void 0,this.start=void 0,this}startAt(e){return this.start=p(e,`start time`),this}isScheduled(){return this.scheduled}isRunning(){return this.scheduled&&this.enabled&&!this.paused&&this.timeScale!==0&&(this.start===void 0||this.mixer.time>=this.start)}getClip(){return this.clip}getMixer(){return this.mixer}getRoot(){return this.root}getEffectiveWeight(){return this.enabled?this.weight*this.fadeFactor():0}getEffectiveTimeScale(){return this.paused?0:this.rate()}fadeFactor(){let e=this.fade;return e?e.duration?m(e,this.mixer.time):e.to:1}rate(){let e=this.speed;return e?e.duration?m(e,this.mixer.time):e.to:this.timeScale}setEffectiveWeight(e){return this.weight=p(e,`weight`,0),this.fade=void 0,this}setEffectiveTimeScale(e){return this.timeScale=p(e,`timeScale`),this.speed=void 0,this}setDuration(e){if(!(p(e,`duration`,0)>0))throw o(`Duration must be positive; pass seconds > 0`);return this.setEffectiveTimeScale(this.clip.duration/e)}syncWith(e){return this.time=e.time,this.setEffectiveTimeScale(e.timeScale)}setLoop(e,t=1/0){if(![2200,2201,2202].includes(e)||t!==1/0&&(!Number.isSafeInteger(t)||t<1))throw o(`Invalid action loop; pass a loop mode and a positive integer count or Infinity`);return this.loop=e,this.repetitions=t,this}envelope(e,t,n){return p(n,`fade/warp duration`,0),{from:e,to:t,duration:n,start:this.mixer.time}}fadeIn(e){return this.fade=this.envelope(0,1,e),this}fadeOut(e){return this.fade=this.envelope(1,0,e),this}stopFading(){return this.fade=void 0,this}warp(e,t,n){return this.speed=this.envelope(p(e,`warp start`),p(t,`warp end`),n),this}halt(e){return this.warp(this.getEffectiveTimeScale(),0,e)}stopWarping(){return this.speed=void 0,this}crossFadeTo(e,t,n=!1){if(e.mixer!==this.mixer||e===this)throw o(`Crossfade needs a different action from this mixer; use mixer.clipAction`);if(p(t,`crossfade duration`,0),n&&(!(this.clip.duration>0)||!(e.clip.duration>0)))throw o(`Warp needs positive clip durations; omit warp for static clips`);if(this.fadeOut(t),e.fadeIn(t),n){let n=this.clip.duration/e.clip.duration;this.warp(1,n,t),e.warp(1/n,1,t)}return this}crossFadeFrom(e,t,n=!1){return e.crossFadeTo(this,t,n),this}step(e){if(this.contribution=0,!this.scheduled||!this.enabled)return;if(p(this.time,`action time`),p(this.timeScale,`timeScale`),p(this.weight,`weight`,0),this.start!==void 0){if(this.mixer.time<this.start)return;e=Math.min(e,this.mixer.time-this.start),this.start=void 0}let t=this.rate();if(this.speed){let e=this.speed;this.mixer.time>=e.start+e.duration&&(this.timeScale=t,this.speed=void 0,t===0&&(this.paused=!0))}let n=this.fadeFactor();if(this.fade){let e=this.fade;this.mixer.time>=e.start+e.duration&&(this.fade=void 0,e.to===0&&(this.enabled=!1))}let r=this.enabled?this.weight*n:0,i=this.clip.duration,a=this.time;if(!this.paused&&e*t!==0){let n=p(this.time+e*t,`advanced action time`);if(this.loop===2200||i===0)this.time=Math.max(0,Math.min(i,n)),(n>=i||n<0)&&(i>0||this.loop===2200||this.repetitions!==1/0)&&this.finish();else{let e=Math.floor(n/i);this.loops+Math.abs(e)>=this.repetitions?(this.time=n<0?0:i,this.loops=this.repetitions-1,this.finish()):(this.time=(n%i+i)%i,this.loops+=Math.abs(e))}a=this.time}this.loop===2202&&this.loops%2&&(a=i-a),this.enabled||(r=0),this.sampled=a,this.contribution=r}contribute(){let e=this.sampled,t=this.contribution;if(t>0){for(let n of this.channels)this.mixer.accumulate(n.binding,n.sample(e),t,this.blendMode);for(let n of this.discrete)this.mixer.accumulateDiscrete(n.binding,n.sample(e),t)}}uses(e){return this.channels.some(t=>t.binding===e)}usesDiscrete(e){return this.discrete.some(t=>t.binding===e)}rewind(){this.time=this.loops=0}finish(){this.clampWhenFinished?this.paused=!0:this.enabled=!1}},_=class e{coreRequirement=__margoCoreRequirement("0.1.0",import.meta.url);static attach(t,n){__margoAssertCore(t,__margoCoreRequirement("0.1.0",import.meta.url));let r=new e(n);try{return t.use(r),r}catch(e){throw r.dispose(),e}}constructor(e){this.root=e,this.time=0,this.timeScale=1,this.actions=[],this.players=/* @__PURE__ */ new Map,this.owned=/* @__PURE__ */ new Set,this.bindings=/* @__PURE__ */ new Map,this.discreteBindings=/* @__PURE__ */ new Map,this.disposed=!1,this.additive=/* @__PURE__ */ new Map,this.name=`animation-mixer:`+v++,this.player(e)}assertLive(){if(this.disposed)throw new t(`disposed`,`AnimationMixer is disposed; create a new mixer; see https://margoengine.com/errors#disposed`)}assertRootLive(e){let r=this.players.get(e);if(r instanceof n){if(r.model.disposed)throw new t(`disposed`,`Mixer root is disposed; use a live model; see https://margoengine.com/errors#disposed`);r.captureState()}}rootAlive(e){let t=this.players.get(e);return!(t instanceof n)||!t.model.disposed}activate(e){for(let t of e)this.actions.some(e=>e.isScheduled()&&e.uses(t))||t.base.set(Array.from(t.read()))}deactivate(e){for(let t of e)t.applied&&!this.actions.some(e=>e.isScheduled()&&e.uses(t))&&(this.actions.some(e=>e.uses(t)&&this.rootAlive(e.getRoot()))&&t.write(t.base),t.applied=!1)}activateDiscrete(e){for(let t of e)this.actions.some(e=>e.isScheduled()&&e.usesDiscrete(t))||(t.base=t.channel.read())}deactivateDiscrete(e){for(let t of e)t.applied&&!this.actions.some(e=>e.isScheduled()&&e.usesDiscrete(t))&&(this.actions.some(e=>e.usesDiscrete(t)&&this.rootAlive(e.getRoot()))&&t.channel.write(t.base),t.applied=!1)}player(e){if(this.players.has(e))return this.players.get(e);let i=this.players.get(e);if(!i){if(!e||typeof e!=`object`)throw o(`Invalid mixer root; pass an object, model, Skeleton or Animation`);if(e instanceof r||e instanceof n)i=e;else if(Array.isArray(e.nodes)&&e.root?.scene){let r=e;if(r.disposed)throw new t(`disposed`,`Mixer root is disposed; use a live model; see https://margoengine.com/errors#disposed`);i=new n(r),r.root.scene.use(i)}i instanceof n&&(i.playing=!1,i!==e&&this.owned.add(i)),this.players.set(e,i)}return i}resolve(e,t){let r=this.player(t),i=typeof e==`object`?e:r instanceof n?typeof e==`number`?r.clips[e]:r.clips.find(t=>t.name===e):void 0;if(!i||!Number.isFinite(i.duration)||i.duration<0||!Array.isArray(i.tracks))throw o(`Unknown mixer clip; use an Animation clip or createKeyframeClip`);return i}clipAction(e,t=this.root,n=u){if(this.assertLive(),![2500,2501].includes(n))throw o(`Invalid blend mode; choose NormalAnimationBlendMode or AdditiveAnimationBlendMode`);let r=this.resolve(e,t);if(this.assertRootLive(t),f(r)&&n===2501)throw o(`Categorical tracks have no additive arithmetic; use NormalAnimationBlendMode`);let i=this.actions.find(e=>e.getClip()===r&&e.getRoot()===t&&e.blendMode===n);return i||(i=new g(this,r,t,n,this.bind(r,t),this.bindDiscrete(r)),this.actions.push(i)),i}existingAction(e,t=this.root){let r=this.players.get(t),i=typeof e==`object`?e:r instanceof n?typeof e==`number`?r.clips[e]:r.clips.find(t=>t.name===e):void 0;return i?this.actions.find(e=>e.getClip()===i&&e.getRoot()===t)??null:null}getRoot(){return this.root}update(e){return this.advanceTime(e),this.blend(),this}advanceTime(e){this.assertLive(),p(e,`mixer delta`),p(this.timeScale,`mixer timeScale`);let t=e*this.timeScale;p(this.time+t,`mixer time`),this.time+=t;let r=this.actions.filter(e=>{let t=this.players.get(e.getRoot());return t instanceof n&&t.model.disposed});for(let e of r)this.actions.splice(this.actions.indexOf(e),1);for(let[e,t]of this.bindings){for(let[e,n]of t)r.some(e=>e.uses(n))&&!this.actions.some(e=>e.uses(n))&&t.delete(e);t.size||this.bindings.delete(e)}for(let[e,t]of this.discreteBindings){for(let[e,n]of t)r.some(e=>e.usesDiscrete(n))&&!this.actions.some(e=>e.usesDiscrete(n))&&t.delete(e);t.size||this.discreteBindings.delete(e)}for(let e of this.actions)e.step(t)}blend(){this.additive.clear();for(let e of this.discreteBindings.values())for(let t of e.values())t.total=0,t.winner=-1/0,t.value=t.base;for(let e of this.bindings.values())for(let t of e.values())t.total=0,t.value.fill(0);for(let e of this.actions)e.contribute();for(let e of this.bindings.values())for(let t of e.values()){let e=t.total>0||this.additive.has(t);if(e||t.applied){if(t.total===0)t.value.set(t.base);else if(t.quaternion)t.total<1&&h(t.base,t.value,t.total,t.value);else for(let e=0;e<t.value.length;e++)t.value[e]=t.value[e]/Math.max(1,t.total)+t.base[e]*Math.max(0,1-t.total);for(let e of this.additive.get(t)??[])if(t.quaternion){let n=/* @__PURE__ */ new Float64Array(4);h([0,0,0,1],e.value,e.weight,n);let[r,i,a,o]=t.value,[s,c,l,u]=n;t.value.set([o*s+r*u+i*l-a*c,o*c-r*l+i*u+a*s,o*l+r*c-i*s+a*u,o*u-r*s-i*c-a*l])}else for(let n=0;n<t.value.length;n++)t.value[n]=t.scale?t.value[n]*(1+(e.value[n]-1)*e.weight):t.value[n]+e.value[n]*e.weight;t.write(t.value),t.applied=e}}for(let e of this.discreteBindings.values())for(let t of e.values()){let e=t.total>0;(e||t.applied)&&(t.channel.write(!e||Math.max(0,1-t.total)>t.winner?t.base:t.value),t.applied=e)}}setTime(e){p(e,`mixer seek`),this.time=0;for(let e of this.actions)e.rewind();return this.update(e)}stopAllAction(){for(let e of this.actions)e.stop();return this.update(0)}uncacheAction(e,t=this.root){let n=this.resolve(e,t);for(let e=this.actions.length-1;e>=0;e--)this.actions[e].getClip()===n&&this.actions[e].getRoot()===t&&(this.actions[e].stop(),this.actions.splice(e,1));this.update(0);for(let[e,t]of this.bindings){for(let[e,n]of t)this.actions.some(e=>e.uses(n))||t.delete(e);t.size||this.bindings.delete(e)}for(let[e,t]of this.discreteBindings){for(let[e,n]of t)this.actions.some(e=>e.usesDiscrete(n))||t.delete(e);t.size||this.discreteBindings.delete(e)}}uncacheClip(e){for(let t of this.players.keys())this.uncacheAction(e,t)}uncacheRoot(e){for(let t of[...this.actions])t.getRoot()===e&&this.uncacheAction(t.getClip(),e);this.update(0);let t=this.players.get(e);t instanceof n&&this.owned.delete(t)&&t.dispose(),this.players.delete(e)}setup(e){this.assertLive(),this.engine=e}onPreUpdate(e){this.update(e)}dispose(){if(!this.disposed){this.stopAllAction(),this.disposed=!0,this.engine?.sceneOf(this)?.removePlugin(this.name);for(let e of this.owned)e.dispose();this.owned.clear(),this.actions.length=0,this.players.clear(),this.bindings.clear(),this.discreteBindings.clear(),this.engine=void 0}}[Symbol.dispose??Symbol()](){this.dispose()}accumulate(e,t,n,r){if(r===2501){let r=this.additive.get(e);r||this.additive.set(e,r=[]),r.push({value:Float64Array.from(t),weight:n});return}let i=e.total+n;if(e.quaternion)e.total===0?e.value.set(Array.from(t)):h(e.value,t,n/i,e.value);else for(let r=0;r<e.value.length;r++)e.value[r]+=t[r]*n;e.total=i}binding(e,t,n,r,i=!1,a=!1,o=()=>n){let s=this.bindings.get(e);s||this.bindings.set(e,s=/* @__PURE__ */ new Map);let c=s.get(t);return c||(c={base:Float64Array.from(n),value:new Float64Array(n.length),total:0,write:r,quaternion:i,scale:a,applied:!1,read:o},s.set(t,c)),c}bind(e,t){if(f(e))return[];let s=this.player(t),c=[],l=e.tracks[0]&&`target`in e.tracks[0]||`properties`in e;for(let t of e.tracks){let e=t.path,l;if(s instanceof r){if(!(`target`in t)||e===`weights`)continue;let n=s.index(t.target);if(n<0)continue;let r=s.getPose(n),i=e;l=this.binding(s,n+`:`+e,r[i],e=>s.setPose(n,{[i]:e}),e===`rotation`,e===`scale`,()=>s.getPose(n)[i])}else if(s instanceof n){let n=`node`in t?t.node:s.model.nodes.findIndex(e=>e.name===t.target);if(n<0)continue;let r=s.model.nodes[n];if(e===`weights`){let t=s.model.primitives.find(e=>e.nodeIndex===n);if(!t)continue;l=this.binding(r,e,t.weights,e=>{for(let t=0;t<e.length;t++)s.setMorph(n,t,e[t])})}else{let t=r.engine.store.transforms,n=r.id,i=e===`translation`?[t.x[n],t.y[n],t.z[n]]:e===`scale`?[t.sx[n],t.sy[n],t.sz[n]]:[t.qx[n],t.qy[n],t.qz[n],t.qw[n]];l=this.binding(r,e,i,t=>{e===`translation`?r.setPosition(t):e===`scale`?r.setScale(t):r.setQuaternion(Array.from(t))},e===`rotation`,e===`scale`,()=>e===`translation`?[t.x[n],t.y[n],t.z[n]]:e===`scale`?[t.sx[n],t.sy[n],t.sz[n]]:[t.qx[n],t.qy[n],t.qz[n],t.qw[n]])}}else throw o(`Transform tracks need a Skeleton or Animation root; use bound property tracks on plain objects`);if(`node`in t){let n=new Float32Array(t.width);c.push({binding:l,sample:r=>a(t.times,t.values,t.width,r,t.interpolation,e===`rotation`,n)})}else{let e=new Float64Array(t.values.length/t.times.length);c.push({binding:l,sample:n=>i(t,n,e)})}}let u=l?e.properties:`bind`in e&&e.bind?(e.bound??=e.bind()).properties:void 0;for(let e of u??[])this.property(e,c);return c}property(e,t){let n=this.binding(e.target,`property:`+(e.property??e.name),e.read(),t=>e.write(t),e.type===`quaternion`,!1,()=>e.read()),r=new Float64Array(e.size);t.push({binding:n,sample:t=>i(e,t,r)})}bindDiscrete(e){return f(e)?e.tracks.map(e=>{let t=this.discreteBindings.get(e.target);t||this.discreteBindings.set(e.target,t=/* @__PURE__ */ new Map);let n=t.get(e.property);if(!n){let r=e.read();n={base:r,value:r,total:0,winner:-1/0,applied:!1,channel:e},t.set(e.property,n)}else if(typeof n.base!=typeof e.read())throw o(`Categorical binding types disagree; use the same value type for one property`);return{binding:n,sample:t=>e.sample(t)}}):[]}accumulateDiscrete(e,t,n){if(typeof t!=`boolean`&&typeof t!=`string`||typeof t!=typeof e.base)throw o(`Categorical channel changed value type; return the original boolean or string type`);e.total+=n,n>=e.winner&&(e.winner=n,e.value=t)}},v=0;export{d as AdditiveAnimationBlendMode,g as AnimationAction,_ as AnimationMixer,s as LoopOnce,l as LoopPingPong,c as LoopRepeat,u as NormalAnimationBlendMode};
@@ -0,0 +1,76 @@
1
+ import type { EngineKernel } from '@margoengine/core';
2
+ import type { Engine, EnginePlugin, FrameGraph } from '@margoengine/core/extension';
3
+ import type { Animation } from './index.js';
4
+ /** Options for {@link MorphWeightPlayer}. */
5
+ export interface MorphWeightOptions {
6
+ /** Wrap time at the end of the clip. Default true; false holds the first and last keys. */
7
+ loop?: boolean;
8
+ }
9
+ /** One copy's place in the crowd, for {@link MorphWeightPlayer.add}. */
10
+ export interface MorphWeightMember {
11
+ /** Seconds added to the player's time, so copies do not move in step. Default 0. */
12
+ offset?: number;
13
+ /** This copy's rate multiplier, finite and >= 0. Default 1. */
14
+ speed?: number;
15
+ }
16
+ /** Weight tracks sampled per thread; the arithmetic is `sampleTrackInto`'s, term for term. */
17
+ export declare const morphWeightShader = "\nstruct Track {times:u32,keys:u32,values:u32,width:u32,mode:u32,pad0:u32,pad1:u32,pad2:u32}\nstruct Item {weight:u32,track:u32,component:u32,member:u32}\nstruct Params {time:f32,duration:f32,loops:u32,pad:u32}\n@group(0) @binding(0) var<uniform> p:Params;\n@group(0) @binding(1) var<storage,read> tracks:array<Track>;\n@group(0) @binding(2) var<storage,read> times:array<f32>;\n@group(0) @binding(3) var<storage,read> values:array<f32>;\n@group(0) @binding(4) var<storage,read> items:array<Item>;\n@group(0) @binding(5) var<storage,read> members:array<vec2f>;\n@group(0) @binding(6) var<storage,read_write> weights:array<f32>;\n@compute @workgroup_size(64) fn main(@builtin(global_invocation_id) id:vec3u,@builtin(num_workgroups) groups:vec3u) {\n let i=id.y*groups.x*64u+id.x;\n if(i>=arrayLength(&items)){return;}\n let item=items[i];let member=members[item.member];let track=tracks[item.track];\n var at=p.time*member.y+member.x;\n if(p.loops>0u&&p.duration>0.0) {\n\n at=at-floor(at/p.duration)*p.duration;\n if(at<0.0){at+=p.duration;}\n if(at>=p.duration){at-=p.duration;}\n } else {at=clamp(at,0.0,p.duration);}\n var lo=0u;var hi=track.keys-1u;\n while(lo<hi) {\n let mid=(lo+hi+1u)/2u;\n if(times[track.times+mid]<=at){lo=mid;}else{hi=mid-1u;}\n }\n let a=lo;let b=min(a+1u,track.keys-1u);\n let span=times[track.times+b]-times[track.times+a];\n var t=0.0;\n if(span>0.0){t=clamp((at-times[track.times+a])/span,0.0,1.0);}\n let w=track.width;let c=item.component;let cubic=track.mode==2u;\n let ai=track.values+(a*select(1u,3u,cubic)+select(0u,1u,cubic))*w+c;\n let bi=track.values+(b*select(1u,3u,cubic)+select(0u,1u,cubic))*w+c;\n var out=values[ai];\n if(track.mode!=0u&&a!=b) {\n if(cubic) {\n let t2=t*t;let t3=t2*t;\n out=(2.0*t3-3.0*t2+1.0)*values[ai]+(t3-2.0*t2+t)*span*values[track.values+(a*3u+2u)*w+c]\n +(-2.0*t3+3.0*t2)*values[bi]+(t3-t2)*span*values[track.values+b*3u*w+c];\n } else {out=values[ai]*(1.0-t)+values[bi]*t;}\n }\n weights[item.weight]=out;\n}\n";
18
+ /**
19
+ * Plays the morph weight tracks of one glTF clip on many copies of a model with no per-copy CPU work: the tracks upload
20
+ * once, and each frame one compute dispatch per deformation buffer page samples every copy's weights from the player's
21
+ * time and that copy's offset and speed. Only weights are driven: a copy's `Animation` keeps playing its own clip for
22
+ * the body, and weights the player drives are overwritten each frame, so `setMorph` on them has no effect.
23
+ *
24
+ * @example
25
+ * ```ts
26
+ * const talk = MorphWeightPlayer.attach(stage.engine, 'Talk');
27
+ * for (const [i, animation] of faces.entries()) talk.add(animation, {offset: i * 0.13});
28
+ * ```
29
+ */
30
+ export declare class MorphWeightPlayer implements EnginePlugin {
31
+ readonly clip: string | number;
32
+ readonly name: string;
33
+ /** Seconds played; a copy samples `time * speed + offset`. */
34
+ time: number;
35
+ /** Rate multiplier for every copy, finite and >= 0. Default 1. */
36
+ speed: number;
37
+ playing: boolean;
38
+ private readonly members;
39
+ private readonly loop;
40
+ private engine?;
41
+ private gpu?;
42
+ private dirty;
43
+ private disposed;
44
+ private readonly params;
45
+ private readonly paramFloats;
46
+ private readonly paramWords;
47
+ /** Same as `engine.use(new MorphWeightPlayer(...))`; returns the player. */
48
+ static attach(engine: EngineKernel, clip?: string | number, options?: MorphWeightOptions): MorphWeightPlayer;
49
+ /** `clip` is a name or index every added copy's model has. */
50
+ constructor(clip?: string | number, { loop }?: MorphWeightOptions);
51
+ /** Copies playing. */
52
+ get count(): number;
53
+ private tracksOf;
54
+ /** Adds a copy, or changes its offset and speed. Every copy must come from one asset: they share the tracks. */
55
+ add(animation: Animation, { offset, speed }?: MorphWeightMember): this;
56
+ /** Stops driving a copy; its weights stay at the last value the GPU wrote until something else writes them. */
57
+ remove(animation: Animation): boolean;
58
+ setup(engine: Engine): void;
59
+ onPreUpdate(delta: number): void;
60
+ /** Moves `time` by `delta` seconds times `speed` when playing; the weights pass samples it, so a seek replays it. */
61
+ advanceTime(delta: number): void;
62
+ registerPasses(graph: FrameGraph): void;
63
+ /** The live copies, in order; a disposed copy leaves by itself. */
64
+ private live;
65
+ private upload;
66
+ /** Uploads the tracks once per device and asset. */
67
+ private prepare;
68
+ private dropPages;
69
+ /** One item per copy, primitive and target, grouped by the buffer page the weights live in. */
70
+ private build;
71
+ private evaluate;
72
+ private release;
73
+ onDeviceRestored(): void;
74
+ dispose(): void;
75
+ [Symbol.dispose]: () => void;
76
+ }
@@ -0,0 +1,48 @@
1
+ // @margo/core-built 0.1.0
2
+ import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
3
+
4
+ import{t as e}from"./require-webgpu-Jrqt3Xy4.js";import{MargoError as t}from"@margoengine/math/errors";var n=`
5
+ struct Track {times:u32,keys:u32,values:u32,width:u32,mode:u32,pad0:u32,pad1:u32,pad2:u32}
6
+ struct Item {weight:u32,track:u32,component:u32,member:u32}
7
+ struct Params {time:f32,duration:f32,loops:u32,pad:u32}
8
+ @group(0) @binding(0) var<uniform> p:Params;
9
+ @group(0) @binding(1) var<storage,read> tracks:array<Track>;
10
+ @group(0) @binding(2) var<storage,read> times:array<f32>;
11
+ @group(0) @binding(3) var<storage,read> values:array<f32>;
12
+ @group(0) @binding(4) var<storage,read> items:array<Item>;
13
+ @group(0) @binding(5) var<storage,read> members:array<vec2f>;
14
+ @group(0) @binding(6) var<storage,read_write> weights:array<f32>;
15
+ @compute @workgroup_size(64) fn main(@builtin(global_invocation_id) id:vec3u,@builtin(num_workgroups) groups:vec3u) {
16
+ let i=id.y*groups.x*64u+id.x;
17
+ if(i>=arrayLength(&items)){return;}
18
+ let item=items[i];let member=members[item.member];let track=tracks[item.track];
19
+ var at=p.time*member.y+member.x;
20
+ if(p.loops>0u&&p.duration>0.0) {
21
+
22
+ at=at-floor(at/p.duration)*p.duration;
23
+ if(at<0.0){at+=p.duration;}
24
+ if(at>=p.duration){at-=p.duration;}
25
+ } else {at=clamp(at,0.0,p.duration);}
26
+ var lo=0u;var hi=track.keys-1u;
27
+ while(lo<hi) {
28
+ let mid=(lo+hi+1u)/2u;
29
+ if(times[track.times+mid]<=at){lo=mid;}else{hi=mid-1u;}
30
+ }
31
+ let a=lo;let b=min(a+1u,track.keys-1u);
32
+ let span=times[track.times+b]-times[track.times+a];
33
+ var t=0.0;
34
+ if(span>0.0){t=clamp((at-times[track.times+a])/span,0.0,1.0);}
35
+ let w=track.width;let c=item.component;let cubic=track.mode==2u;
36
+ let ai=track.values+(a*select(1u,3u,cubic)+select(0u,1u,cubic))*w+c;
37
+ let bi=track.values+(b*select(1u,3u,cubic)+select(0u,1u,cubic))*w+c;
38
+ var out=values[ai];
39
+ if(track.mode!=0u&&a!=b) {
40
+ if(cubic) {
41
+ let t2=t*t;let t3=t2*t;
42
+ out=(2.0*t3-3.0*t2+1.0)*values[ai]+(t3-2.0*t2+t)*span*values[track.values+(a*3u+2u)*w+c]
43
+ +(-2.0*t3+3.0*t2)*values[bi]+(t3-t2)*span*values[track.values+b*3u*w+c];
44
+ } else {out=values[ai]*(1.0-t)+values[bi]*t;}
45
+ }
46
+ weights[item.weight]=out;
47
+ }
48
+ `,r={STEP:0,LINEAR:1,CUBICSPLINE:2},i=8,a=0,o=class o{coreRequirement=__margoCoreRequirement("0.1.0",import.meta.url);static attach(e,t=0,n){__margoAssertCore(e,__margoCoreRequirement("0.1.0",import.meta.url));let r=new o(t,n);return e.use(r),r}constructor(e=0,{loop:t=!0}={}){if(this.clip=e,this.name=`morph-gpu:`+a++,this.time=0,this.speed=1,this.playing=!0,this.members=/* @__PURE__ */ new Map,this.dirty=!0,this.disposed=!1,this.params=/* @__PURE__ */ new ArrayBuffer(16),this.paramFloats=new Float32Array(this.params),this.paramWords=new Uint32Array(this.params),typeof t!=`boolean`)throw TypeError(`MorphWeightPlayer loop must be a boolean`);if(typeof e!=`string`&&!(Number.isInteger(e)&&e>=0))throw RangeError(`MorphWeightPlayer clip must be a clip name or an index from animation.clips`);this.loop=t}get count(){return this.members.size}tracksOf(e){let t=e.clips,n=t[typeof this.clip==`string`?t.findIndex(e=>e.name===this.clip):this.clip];if(!n)throw RangeError(`Unknown animation clip; pass a clip name or an index from animation.clips`);let r=n.tracks.filter(e=>e.path===`weights`);if(!r.length)throw RangeError(`Clip ${n.name} has no morph weight tracks; pick a clip that has them`);return{duration:n.duration,tracks:r}}add(e,{offset:n=0,speed:r=1}={}){if(this.disposed)throw new t(`disposed`,`MorphWeightPlayer is disposed; create a new one`);if(!Number.isFinite(n)||!Number.isFinite(r)||r<0)throw RangeError(`Invalid morph member; offset must be finite and speed a finite number >= 0`);let i=this.members.keys().next().value;if(i&&i!==e&&i.model.asset!==e.model.asset)throw TypeError(`MorphWeightPlayer copies must share one asset; clone them with cloneModel`);return this.tracksOf(e),e.gpuWeights=!0,this.members.set(e,{offset:n,speed:r}),this.dirty=!0,this}remove(e){let t=this.members.delete(e);return this.dirty||=t,t}setup(n){if(this.disposed)throw new t(`disposed`,`MorphWeightPlayer is disposed; create a new player before attaching`);e(n,`MorphWeightPlayer`),this.engine=n}onPreUpdate(e){this.advanceTime(e)}advanceTime(e){if(!Number.isFinite(e)||e<0)throw RangeError(`Invalid animation delta; pass a finite delta >= 0 seconds`);if(!Number.isFinite(this.speed)||this.speed<0)throw RangeError(`Invalid morph player speed; use a finite number >= 0`);this.playing&&!this.disposed&&(this.time+=e*this.speed)}registerPasses(e){e.add({name:this.name,order:-11,execute:e=>this.evaluate(e)})}live(){for(let e of this.members.keys())(e.disposed||e.model.disposed)&&(this.members.delete(e),this.dirty=!0);return[...this.members.keys()]}upload(e,t){let n=e.createBuffer({size:Math.max(16,Math.ceil(t.byteLength/4)*4),usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST});return e.queue.writeBuffer(n,0,t),n}prepare(e,t){let{tracks:a}=this.tracksOf(t),o=new Uint32Array(a.length*i),s=0,c=0;a.forEach((e,t)=>{o.set([s,e.times.length,c,e.width,r[e.interpolation]],t*i),s+=e.times.length,c+=e.values.length});let l=new Float32Array(s),u=new Float32Array(c);return a.forEach((e,t)=>{l.set(e.times,o[t*i]),u.set(e.values,o[t*i+2])}),{device:e,pipeline:e.createComputePipeline({layout:`auto`,compute:{module:e.createShaderModule({code:n}),entryPoint:`main`}}),params:e.createBuffer({size:16,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),tracks:this.upload(e,o),times:this.upload(e,l),values:this.upload(e,u),pages:[],version:-1}}dropPages(e){for(let t of e.pages)t.items.destroy();e.pages=[],e.members?.destroy(),e.members=void 0}build(e,t,n){this.dropPages(e);let{tracks:r}=this.tracksOf(t[0]),i=/* @__PURE__ */ new Map,a=new Float32Array(t.length*2);t.forEach((e,t)=>{let n=this.members.get(e);a[t*2]=n.offset,a[t*2+1]=n.speed;for(let n of e.resources){let e=n.weights,a=i.get(e)??[];i.set(e,a),r.forEach((e,r)=>{if(e.node===n.primitive.nodeIndex)for(let i=0;i<e.width;i++)a.push(n.slot.weights.offset+i,r,i,t)})}}),e.members=this.upload(e.device,a);let o=e.device.limits.maxComputeWorkgroupsPerDimension??65535;for(let[t,n]of i){if(!n.length)continue;let r=this.upload(e.device,Uint32Array.from(n)),i=Math.ceil(n.length/4/64),a=Math.min(i,o);e.pages.push({items:r,x:a,y:Math.ceil(i/a),group:e.device.createBindGroup({layout:e.pipeline.getBindGroupLayout(0),entries:[e.params,e.tracks,e.times,e.values,r,e.members,t].map((e,t)=>({binding:t,resource:{buffer:e}}))})})}e.version=n,this.dirty=!1}evaluate(e){if(e.backend!==`webgpu`)return;let t=this.live(),n=t[0]?.arena;if(!n)return;this.gpu&&this.gpu.device!==e.device&&this.release();let r=this.gpu??=this.prepare(e.device,t[0]);if((this.dirty||r.version!==n.version)&&this.build(r,t,n.version),!r.pages.length)return;this.paramFloats[0]=this.time,this.paramFloats[1]=this.tracksOf(t[0]).duration,this.paramWords[2]=+this.loop,e.device.queue.writeBuffer(r.params,0,this.params);let i=e.encoder.beginComputePass();try{i.setPipeline(r.pipeline);for(let e of r.pages)i.setBindGroup(0,e.group),i.dispatchWorkgroups(e.x,e.y)}finally{i.end()}}release(){let e=this.gpu;if(e){this.dropPages(e);for(let t of[e.params,e.tracks,e.times,e.values])t.destroy();this.gpu=void 0,this.dirty=!0}}onDeviceRestored(){this.gpu=void 0,this.dirty=!0}dispose(){this.disposed||(this.disposed=!0,this.engine?.sceneOf(this)?.removePlugin(this.name),this.release(),this.members.clear())}[Symbol.dispose??Symbol()](){this.dispose()}};export{o as MorphWeightPlayer,n as morphWeightShader};
@@ -0,0 +1,94 @@
1
+ /// <reference lib="esnext.disposable" preserve="true" />
2
+ import { Animation as BaseAnimation, type AnimationOptions } from '@margoengine/animation';
3
+ import type { PBRModel } from '@margoengine/gltf/pbr';
4
+ import { type ActionLoop } from './mixer.js';
5
+ export { LoopOnce, LoopRepeat, LoopPingPong } from './mixer.js';
6
+ /** Optional plain-player event and iteration controls. */
7
+ export interface PlaybackOptions extends AnimationOptions {
8
+ /** Default LoopRepeat, or LoopOnce when loop=false. */
9
+ loopMode?: ActionLoop;
10
+ /** Total traversals, positive integer or Infinity. Default Infinity; LoopOnce always uses one. */
11
+ repetitions?: number;
12
+ /** Signed multiplier on speed. Default 1. */
13
+ timeScale?: number;
14
+ /** Abort disposes this player and rejects its pending finished promise. */
15
+ signal?: AbortSignal;
16
+ }
17
+ /** Loop or completion notification, delivered after the sampled pose is applied. */
18
+ export declare class PlaybackEvent extends Event {
19
+ readonly animation: PlaybackAnimation;
20
+ readonly loopDelta: number;
21
+ readonly direction: 1 | -1;
22
+ /** @internal Constructed by PlaybackAnimation. */
23
+ constructor(type: 'loop' | 'finished', animation: PlaybackAnimation, loopDelta: number, direction: 1 | -1);
24
+ }
25
+ /** Event payloads for on/addEventListener. */
26
+ export interface PlaybackEventMap {
27
+ loop: PlaybackEvent;
28
+ finished: PlaybackEvent;
29
+ }
30
+ /** Plain Animation playback with repeat counts, ping-pong, events and an abortable completion promise. */
31
+ export declare class PlaybackAnimation extends BaseAnimation {
32
+ /** Directed looping. Default LoopRepeat (LoopOnce when constructed with loop=false). */
33
+ loopMode: ActionLoop;
34
+ /** Total traversals. Default Infinity. */
35
+ repetitions: number;
36
+ /** Signed multiplier on Animation.options.speed. Default 1. */
37
+ timeScale: number;
38
+ private cursor;
39
+ private completed;
40
+ private settled;
41
+ private started;
42
+ private terminal;
43
+ private released;
44
+ private readonly events;
45
+ private promise;
46
+ private resolve;
47
+ private reject;
48
+ private signal?;
49
+ private readonly abort;
50
+ /** Construct like Animation, adding loopMode, repetitions, timeScale and signal. */
51
+ constructor(model: PBRModel, options?: PlaybackOptions);
52
+ /** Create and register in the model's scene; an already-aborted signal never registers. */
53
+ static attach(model: PBRModel, options?: PlaybackOptions): PlaybackAnimation;
54
+ /** Current run's completion, renewed by play; rejects with AbortError on replacement/disposal. */
55
+ get finished(): Promise<PlaybackEvent>;
56
+ private newPromise;
57
+ private validatePlayback;
58
+ /** Start a clip from its beginning (negative rates start at its end); renew completion on a replacement run. */
59
+ play(clip?: string | number): this;
60
+ /** Choose a loop mode and total traversal count, without restarting the run. */
61
+ setLoop(mode: ActionLoop, repetitions?: number): this;
62
+ /** Seek total clip seconds without emitting playback events; restarts traversal counting. */
63
+ seek(time: number): this;
64
+ private mode;
65
+ private pose;
66
+ /** Advance plain playback before world-matrix/deformation updates. */
67
+ onPreUpdate(delta: number): void;
68
+ /**
69
+ * Moves the playback cursor by `delta` seconds times `speed` and `timeScale`, counting loops and the end of the run:
70
+ * the CPU part of the frame update, which a seek from `@margoengine/cutscene/seek` replays. It poses nothing and
71
+ * sends no `loop` or `finished` event (a replayed end still settles `finished`); the next update poses the place
72
+ * reached.
73
+ */
74
+ advanceTime(delta: number): void;
75
+ /** The pose a step owes the next update: cursor, direction, at an endpoint. */
76
+ private owed?;
77
+ /** One step of the cursor: loops crossed, direction and, at the end of the run, its `finished` event. */
78
+ private stepClock;
79
+ /** Subscribe with optional AbortSignal; returns an unsubscribe function. */
80
+ on<K extends keyof PlaybackEventMap>(type: K, listener: (event: PlaybackEventMap[K]) => void, options?: {
81
+ signal?: AbortSignal;
82
+ }): () => void;
83
+ /** Familiar EventTarget listener API. */
84
+ addEventListener(type: 'loop' | 'finished', listener: (event: PlaybackEvent) => void, options?: AddEventListenerOptions | boolean): void;
85
+ /** Remove a previously added listener. */
86
+ removeEventListener(type: 'loop' | 'finished', listener: (event: PlaybackEvent) => void, options?: EventListenerOptions | boolean): void;
87
+ /** Await this run with independent cancellation, without stopping playback. */
88
+ waitForFinished({ signal }?: {
89
+ signal?: AbortSignal;
90
+ }): Promise<PlaybackEvent>;
91
+ /** Reject pending completion, remove abort subscription and release Animation resources. Idempotent. */
92
+ dispose(): void;
93
+ }
94
+ export { PlaybackAnimation as Animation };
@@ -0,0 +1,4 @@
1
+ // @margo/core-built 0.1.0
2
+ import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
3
+
4
+ import{n as e}from"./errors-t1ewumJS.js";import{LoopOnce as t,LoopPingPong as n,LoopRepeat as r}from"./mixer.js";import{Animation as i}from"@margoengine/animation";var a=class extends Event{constructor(e,t,n,r){super(e),this.animation=t,this.loopDelta=n,this.direction=r}},o=t=>Object.assign(e(t,`arguments`),{code:`arguments`}),s=(e,t)=>{if(!Number.isFinite(e))throw o(`Invalid playback ${t}; pass finite seconds or a rate`);return e},c=()=>new DOMException(`Animation playback cancelled; start another play or wait on a live player`,`AbortError`),l=class e extends i{constructor(e,t={}){super(e,t),this.cursor=0,this.completed=0,this.settled=!1,this.started=!1,this.terminal=!1,this.released=!1,this.events=new EventTarget,this.abort=()=>this.dispose(),this.loopMode=t.loopMode??(t.loop===!1?2200:2201),this.repetitions=t.repetitions??1/0,this.timeScale=t.timeScale??1,this.validatePlayback(),this.newPromise(),this.signal=t.signal,t.signal?.addEventListener(`abort`,this.abort,{once:!0}),t.signal?.aborted&&this.dispose()}static attach(t,n={}){__margoAssertCore(t,__margoCoreRequirement("0.1.0",import.meta.url));let r=new e(t,n);if(!n.signal?.aborted)try{t.root.scene.use(r)}catch(e){throw r.dispose(),e}return r}get finished(){return this.promise}newPromise(){this.settled=!1,this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t}),this.promise.catch(()=>{})}validatePlayback(){if(![2200,2201,2202].includes(this.loopMode)||this.repetitions!==1/0&&(!Number.isSafeInteger(this.repetitions)||this.repetitions<1))throw o(`Invalid playback loop; choose a loop mode and a positive integer traversal count or Infinity`);s(this.timeScale,`timeScale`)}play(e=0){return super.play(e),this.started&&(this.settled||this.reject(c()),this.newPromise()),this.started=!0,this.completed=0,this.terminal=!1,this.cursor=this.timeScale<0?this.clips[this.clip].duration:0,this.pose(this.cursor,1,this.timeScale<0),this}setLoop(e,n=1/0){let r=this.loopMode,i=this.repetitions;this.loopMode=e,this.repetitions=n;try{this.validatePlayback()}catch(e){throw this.loopMode=r,this.repetitions=i,e}return this.options.loop=e!==t,this}seek(e){if(s(e,`seek`)<0)throw o(`Playback seek must be nonnegative; pass total clip seconds >= 0`);return this.cursor=e,this.completed=0,this.terminal=!1,this.pose(e,this.timeScale<0?-1:1,!1),this}mode(){return this.loopMode===2201&&this.options.loop===!1?t:this.loopMode}pose(e,t,n){let r=this.clips[this.clip]?.duration??0,i=this.mode(),a=0;if(r>0){if(i===2200)a=Math.max(0,Math.min(r,e));else if(i===2202){let t=2*r,n=(e%t+t)%t;a=n<=r?n:t-n}else a=n?t>0?r:0:(e%r+r)%r}let o=this.options.loop;this.options.loop=!1;try{super.seek(a)}finally{this.options.loop=o}}onPreUpdate(e){if(this.model.disposed){this.dispose();return}this.validatePlayback();let t=this.playing;this.playing=!1;try{super.onPreUpdate(0)}finally{this.playing=t}let n=this.stepClock(e),r=this.owed;if(r&&(this.owed=void 0,this.pose(r[0],r[1],r[2])),!n)return;let[i,o,s]=n;s?this.events.dispatchEvent(s):i&&this.events.dispatchEvent(new a(`loop`,this,i*o,o))}advanceTime(e){this.validatePlayback(),this.stepClock(e)}stepClock(e){if(!this.playing||this.terminal||this.disposed)return;if(s(e,`delta`),e<0)throw o(`Playback delta must be nonnegative; reverse with timeScale`);let t=s(e*(this.options.speed??1)*this.timeScale,`advance`);if(t===0&&(this.clips[this.clip]?.duration??0)>0)return;let n=this.clips[this.clip]?.duration??0,r=t<0?-1:1,i=this.mode(),c=s(this.cursor+t,`clock`),l=0,u=!1;if(n===0)c=0,u=!0;else if(i===2200)u=r>0?c>=n:c<=0,c=Math.max(0,Math.min(n,c));else{if(l=r>0?Math.floor(c/n)-Math.floor(this.cursor/n):Math.ceil(this.cursor/n)-Math.ceil(c/n),!Number.isSafeInteger(l))throw o(`Playback crossed too many loops to count exactly; use a smaller delta or rate`);let e=this.repetitions-this.completed;l>=e&&(c=(r>0?Math.floor(this.cursor/n)+e:Math.ceil(this.cursor/n)-e)*n,l=e,u=!0)}if(this.started=!0,this.cursor=c,this.completed+=l,this.owed=[c,r,u],!u)return[l,r,void 0];this.terminal=!0,this.playing=!1,this.settled=!0;let d=new a(`finished`,this,0,r);return this.resolve(d),[l,r,d]}on(e,t,n={}){return this.events.addEventListener(e,t,n),()=>this.events.removeEventListener(e,t)}addEventListener(e,t,n){this.events.addEventListener(e,t,n)}removeEventListener(e,t,n){this.events.removeEventListener(e,t,n)}waitForFinished({signal:e}={}){return e?e.aborted?Promise.reject(e.reason??c()):new Promise((t,n)=>{let r=()=>{e.removeEventListener(`abort`,r),n(e.reason??c())};e.addEventListener(`abort`,r,{once:!0}),this.finished.then(n=>{e.removeEventListener(`abort`,r),t(n)},t=>{e.removeEventListener(`abort`,r),n(t)})}):this.finished}dispose(){this.released||(this.released=!0,this.playing=!1,this.signal?.removeEventListener(`abort`,this.abort),this.signal=void 0,this.settled||(this.settled=!0,this.reject(c())),super.dispose())}};export{l as Animation,l as PlaybackAnimation,t as LoopOnce,n as LoopPingPong,r as LoopRepeat,a as PlaybackEvent};