@holtjs/stage 0.4.1 → 0.5.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.
package/dist/rig2d.js ADDED
@@ -0,0 +1,871 @@
1
+ import { _ as rgbToCss, r as BlendModes } from "./types-DRFB0Klc.js";
2
+ // src/rig2d.ts
3
+ const TWO_PI = Math.PI * 2;
4
+ /** Shortest signed angular delta in `[-PI, PI]`. */
5
+ function wrapAngleDelta(fromRad, toRad) {
6
+ let d = (toRad - fromRad) % TWO_PI;
7
+ if (d > Math.PI) d -= TWO_PI;
8
+ else if (d < -Math.PI) d += TWO_PI;
9
+ return d;
10
+ }
11
+ function evalRigCurve(t, kind = "linear") {
12
+ const u = t <= 0 ? 0 : t >= 1 ? 1 : t;
13
+ switch (kind) {
14
+ case "step": return u < 1 ? 0 : 1;
15
+ case "smoothstep": return u * u * (3 - 2 * u);
16
+ case "outBack": {
17
+ const c1 = 1.70158;
18
+ const c3 = 2.70158;
19
+ const m = u - 1;
20
+ return 1 + c3 * m * m * m + c1 * m * m;
21
+ }
22
+ default: return u;
23
+ }
24
+ }
25
+ /** Validate and topologically sort a 2D skeletal cutout rig definition (`parentIndex < boneIndex`). */
26
+ function defineRig2DSkeleton(def) {
27
+ if (!def.bones.length) throw new Error(`Rig2D(${def.id}): skeleton requires at least 1 bone`);
28
+ const rawByName = /* @__PURE__ */ new Map();
29
+ for (const b of def.bones) {
30
+ if (rawByName.has(b.name)) throw new Error(`Rig2D(${def.id}): duplicate bone "${b.name}"`);
31
+ rawByName.set(b.name, b);
32
+ }
33
+ const ordered = [];
34
+ const boneIndexByName = /* @__PURE__ */ new Map();
35
+ const visiting = /* @__PURE__ */ new Set();
36
+ const visit = (b) => {
37
+ const existing = boneIndexByName.get(b.name);
38
+ if (existing !== void 0) return existing;
39
+ if (visiting.has(b.name)) throw new Error(`Rig2D(${def.id}): cycle detected in bone hierarchy at "${b.name}"`);
40
+ visiting.add(b.name);
41
+ let parentIndex = -1;
42
+ if (b.parent) {
43
+ const p = rawByName.get(b.parent);
44
+ if (!p) throw new Error(`Rig2D(${def.id}): bone "${b.name}" references missing parent "${b.parent}"`);
45
+ parentIndex = visit(p);
46
+ }
47
+ visiting.delete(b.name);
48
+ const idx = ordered.length;
49
+ ordered.push({
50
+ index: idx,
51
+ name: b.name,
52
+ parentIndex,
53
+ restX: b.x ?? 0,
54
+ restY: b.y ?? 0,
55
+ restRotation: b.rotation ?? 0,
56
+ restScaleX: b.scaleX ?? 1,
57
+ restScaleY: b.scaleY ?? 1,
58
+ length: b.length ?? 0
59
+ });
60
+ boneIndexByName.set(b.name, idx);
61
+ return idx;
62
+ };
63
+ for (const b of def.bones) visit(b);
64
+ const slots = [];
65
+ const slotIndexByName = /* @__PURE__ */ new Map();
66
+ for (let i = 0; i < def.slots.length; i++) {
67
+ const s = def.slots[i];
68
+ if (slotIndexByName.has(s.name)) throw new Error(`Rig2D(${def.id}): duplicate slot "${s.name}"`);
69
+ const bIdx = boneIndexByName.get(s.bone);
70
+ if (bIdx === void 0) throw new Error(`Rig2D(${def.id}): slot "${s.name}" references unknown bone "${s.bone}"`);
71
+ slots.push({
72
+ index: i,
73
+ name: s.name,
74
+ boneIndex: bIdx,
75
+ defaultAttachment: s.defaultAttachment ?? null,
76
+ zOrder: s.zOrder ?? i,
77
+ restTint: s.tint ?? 0xffffff,
78
+ restAlpha: s.alpha ?? 1,
79
+ blendMode: s.blendMode ?? BlendModes.NORMAL
80
+ });
81
+ slotIndexByName.set(s.name, i);
82
+ }
83
+ const attachments = /* @__PURE__ */ new Map();
84
+ for (const [k, att] of Object.entries(def.attachments)) attachments.set(k, {
85
+ ...att,
86
+ id: att.id || k
87
+ });
88
+ const skins = /* @__PURE__ */ new Map();
89
+ if (def.skins) for (const [k, skin] of Object.entries(def.skins)) skins.set(k, { ...skin });
90
+ const clips = /* @__PURE__ */ new Map();
91
+ if (def.clips) for (const [k, clip] of Object.entries(def.clips)) {
92
+ const sortedTracks = {};
93
+ for (const [boneName, frames] of Object.entries(clip.tracks)) sortedTracks[boneName] = [...frames].sort((a, b) => a.timeMs - b.timeMs);
94
+ const sortedEvents = clip.events ? [...clip.events].sort((a, b) => a.timeMs - b.timeMs) : void 0;
95
+ clips.set(k, {
96
+ ...clip,
97
+ name: clip.name || k,
98
+ tracks: sortedTracks,
99
+ events: sortedEvents
100
+ });
101
+ }
102
+ return {
103
+ id: def.id,
104
+ bones: ordered,
105
+ boneIndexByName,
106
+ slots,
107
+ slotIndexByName,
108
+ attachments,
109
+ skins,
110
+ clips
111
+ };
112
+ }
113
+ function sampleBoneTrack(frames, timeMs, out) {
114
+ if (!frames || frames.length === 0) {
115
+ out.dx = 0;
116
+ out.dy = 0;
117
+ out.drot = 0;
118
+ out.sx = 1;
119
+ out.sy = 1;
120
+ return false;
121
+ }
122
+ if (frames.length === 1 || timeMs <= frames[0].timeMs) {
123
+ const f = frames[0];
124
+ out.dx = f.x ?? 0;
125
+ out.dy = f.y ?? 0;
126
+ out.drot = f.rotation ?? 0;
127
+ out.sx = f.scaleX ?? 1;
128
+ out.sy = f.scaleY ?? 1;
129
+ return true;
130
+ }
131
+ const last = frames[frames.length - 1];
132
+ if (timeMs >= last.timeMs) {
133
+ out.dx = last.x ?? 0;
134
+ out.dy = last.y ?? 0;
135
+ out.drot = last.rotation ?? 0;
136
+ out.sx = last.scaleX ?? 1;
137
+ out.sy = last.scaleY ?? 1;
138
+ return true;
139
+ }
140
+ let hi = 1;
141
+ while (hi < frames.length - 1 && frames[hi].timeMs < timeMs) hi++;
142
+ const a = frames[hi - 1];
143
+ const b = frames[hi];
144
+ const span = Math.max(1e-6, b.timeMs - a.timeMs);
145
+ const u = evalRigCurve((timeMs - a.timeMs) / span, a.curve ?? "linear");
146
+ const ax = a.x ?? 0, bx = b.x ?? ax;
147
+ const ay = a.y ?? 0, by = b.y ?? ay;
148
+ const ar = a.rotation ?? 0, br = b.rotation ?? ar;
149
+ const asx = a.scaleX ?? 1, bsx = b.scaleX ?? asx;
150
+ const asy = a.scaleY ?? 1, bsy = b.scaleY ?? asy;
151
+ out.dx = ax + (bx - ax) * u;
152
+ out.dy = ay + (by - ay) * u;
153
+ out.drot = ar + wrapAngleDelta(ar, br) * u;
154
+ out.sx = asx + (bsx - asx) * u;
155
+ out.sy = asy + (bsy - asy) * u;
156
+ return true;
157
+ }
158
+ /** Zero-GC runtime instance of a `Rig2DSkeleton` with FK solver, slot equipment table, and 2-layer clip mixer. */
159
+ var Rig2DInstance = class {
160
+ skeleton;
161
+ x = 0;
162
+ y = 0;
163
+ rotation = 0;
164
+ scaleX = 1;
165
+ scaleY = 1;
166
+ flipX = false;
167
+ flipY = false;
168
+ boneLocalX;
169
+ boneLocalY;
170
+ boneLocalRot;
171
+ boneLocalScaleX;
172
+ boneLocalScaleY;
173
+ boneManualX;
174
+ boneManualY;
175
+ boneManualRot;
176
+ boneWorldMat;
177
+ boneWorldRot;
178
+ boneWorldScaleX;
179
+ boneWorldScaleY;
180
+ slotAttachments;
181
+ slotTint;
182
+ slotAlpha;
183
+ slotZOrder;
184
+ baseClip = null;
185
+ baseTimeMs = 0;
186
+ baseSpeed = 1;
187
+ baseLoop = true;
188
+ prevClip = null;
189
+ prevTimeMs = 0;
190
+ crossfadeElapsedMs = 0;
191
+ crossfadeDurationMs = 0;
192
+ overlayClip = null;
193
+ overlayTimeMs = 0;
194
+ overlaySpeed = 1;
195
+ overlayLoop = false;
196
+ overlayWeight = 1;
197
+ overlayBlendInMs = 60;
198
+ overlayBlendOutMs = 90;
199
+ overlayMask;
200
+ sampleA = {
201
+ dx: 0,
202
+ dy: 0,
203
+ drot: 0,
204
+ sx: 1,
205
+ sy: 1
206
+ };
207
+ sampleB = {
208
+ dx: 0,
209
+ dy: 0,
210
+ drot: 0,
211
+ sx: 1,
212
+ sy: 1
213
+ };
214
+ listeners = /* @__PURE__ */ new Set();
215
+ worldDirty = true;
216
+ constructor(skeleton) {
217
+ this.skeleton = skeleton;
218
+ const nB = skeleton.bones.length;
219
+ this.boneLocalX = new Float32Array(nB);
220
+ this.boneLocalY = new Float32Array(nB);
221
+ this.boneLocalRot = new Float32Array(nB);
222
+ this.boneLocalScaleX = new Float32Array(nB);
223
+ this.boneLocalScaleY = new Float32Array(nB);
224
+ this.boneManualX = new Float32Array(nB);
225
+ this.boneManualY = new Float32Array(nB);
226
+ this.boneManualRot = new Float32Array(nB);
227
+ this.boneWorldMat = new Float32Array(nB * 6);
228
+ this.boneWorldRot = new Float32Array(nB);
229
+ this.boneWorldScaleX = new Float32Array(nB);
230
+ this.boneWorldScaleY = new Float32Array(nB);
231
+ this.overlayMask = new Uint8Array(nB);
232
+ const nS = skeleton.slots.length;
233
+ this.slotAttachments = new Array(nS);
234
+ this.slotTint = new Uint32Array(nS);
235
+ this.slotAlpha = new Float32Array(nS);
236
+ this.slotZOrder = new Int32Array(nS);
237
+ this.resetToSetupPose();
238
+ }
239
+ /** Reset all bones, slots, and attachments to the skeleton's rest setup pose. */
240
+ resetToSetupPose() {
241
+ const bones = this.skeleton.bones;
242
+ for (let i = 0; i < bones.length; i++) {
243
+ const b = bones[i];
244
+ this.boneLocalX[i] = b.restX;
245
+ this.boneLocalY[i] = b.restY;
246
+ this.boneLocalRot[i] = b.restRotation;
247
+ this.boneLocalScaleX[i] = b.restScaleX;
248
+ this.boneLocalScaleY[i] = b.restScaleY;
249
+ this.boneManualX[i] = 0;
250
+ this.boneManualY[i] = 0;
251
+ this.boneManualRot[i] = 0;
252
+ }
253
+ const slots = this.skeleton.slots;
254
+ for (let i = 0; i < slots.length; i++) {
255
+ const s = slots[i];
256
+ this.slotAttachments[i] = s.defaultAttachment;
257
+ this.slotTint[i] = s.restTint;
258
+ this.slotAlpha[i] = s.restAlpha;
259
+ this.slotZOrder[i] = s.zOrder;
260
+ }
261
+ this.worldDirty = true;
262
+ return this;
263
+ }
264
+ setPosition(x, y) {
265
+ this.x = x;
266
+ this.y = y;
267
+ this.worldDirty = true;
268
+ return this;
269
+ }
270
+ setScale(sx, sy = sx) {
271
+ this.scaleX = sx;
272
+ this.scaleY = sy;
273
+ this.worldDirty = true;
274
+ return this;
275
+ }
276
+ setFlip(flipX, flipY = this.flipY) {
277
+ this.flipX = flipX;
278
+ this.flipY = flipY;
279
+ this.worldDirty = true;
280
+ return this;
281
+ }
282
+ /** Swap a single slot's equipped cutout part in O(1) (`null` hides/unequips the slot). */
283
+ setAttachment(slotName, attachmentId) {
284
+ const sIdx = this.skeleton.slotIndexByName.get(slotName);
285
+ if (sIdx === void 0) throw new Error(`Rig2D(${this.skeleton.id}): unknown slot "${slotName}"`);
286
+ if (attachmentId !== null && !this.skeleton.attachments.has(attachmentId)) throw new Error(`Rig2D(${this.skeleton.id}): unknown attachment "${attachmentId}"`);
287
+ this.slotAttachments[sIdx] = attachmentId;
288
+ return this;
289
+ }
290
+ getAttachment(slotName) {
291
+ const sIdx = this.skeleton.slotIndexByName.get(slotName);
292
+ return sIdx === void 0 ? null : this.slotAttachments[sIdx];
293
+ }
294
+ getSlotAttachmentByIndex(slotIndex) {
295
+ const id = this.slotAttachments[slotIndex];
296
+ return id ? this.skeleton.attachments.get(id) ?? null : null;
297
+ }
298
+ /** Apply a named skin from the skeleton or an explicit `{ slotName: attachmentId | null }` wardrobe map. */
299
+ applySkin(skinNameOrMap) {
300
+ const map = typeof skinNameOrMap === "string" ? this.skeleton.skins.get(skinNameOrMap) : skinNameOrMap;
301
+ if (!map) throw new Error(`Rig2D(${this.skeleton.id}): unknown skin "${String(skinNameOrMap)}"`);
302
+ for (const [slotName, attId] of Object.entries(map)) if (this.skeleton.slotIndexByName.has(slotName)) this.setAttachment(slotName, attId);
303
+ return this;
304
+ }
305
+ setSlotTint(slotName, tintRgb, alpha) {
306
+ const sIdx = this.skeleton.slotIndexByName.get(slotName);
307
+ if (sIdx === void 0) return this;
308
+ this.slotTint[sIdx] = tintRgb & 0xffffff;
309
+ if (alpha !== void 0) this.slotAlpha[sIdx] = alpha;
310
+ return this;
311
+ }
312
+ /** Apply an additive procedural bone offset (e.g. aiming arm or head tracking cursor). */
313
+ setBoneManualOffset(boneName, dx = 0, dy = 0, drot = 0) {
314
+ const bIdx = this.skeleton.boneIndexByName.get(boneName);
315
+ if (bIdx === void 0) return this;
316
+ this.boneManualX[bIdx] = dx;
317
+ this.boneManualY[bIdx] = dy;
318
+ this.boneManualRot[bIdx] = drot;
319
+ this.worldDirty = true;
320
+ return this;
321
+ }
322
+ onEvent(fn) {
323
+ this.listeners.add(fn);
324
+ return () => {
325
+ this.listeners.delete(fn);
326
+ };
327
+ }
328
+ get currentClipName() {
329
+ return this.baseClip?.name ?? null;
330
+ }
331
+ get activeOverlayClipName() {
332
+ return this.overlayClip?.name ?? null;
333
+ }
334
+ /** Start or crossfade to a base locomotion/idle animation clip. */
335
+ play(clipOrName, opts = {}) {
336
+ const clip = typeof clipOrName === "string" ? this.skeleton.clips.get(clipOrName) : clipOrName;
337
+ if (!clip) throw new Error(`Rig2D(${this.skeleton.id}): unknown clip "${String(clipOrName)}"`);
338
+ if (this.baseClip === clip && !opts.restart) {
339
+ if (opts.speed !== void 0) this.baseSpeed = opts.speed;
340
+ if (opts.loop !== void 0) this.baseLoop = opts.loop;
341
+ return this;
342
+ }
343
+ const fade = Math.max(0, opts.crossfadeMs ?? 0);
344
+ if (fade > 0 && this.baseClip) {
345
+ this.prevClip = this.baseClip;
346
+ this.prevTimeMs = this.baseTimeMs;
347
+ this.crossfadeElapsedMs = 0;
348
+ this.crossfadeDurationMs = fade;
349
+ } else {
350
+ this.prevClip = null;
351
+ this.crossfadeDurationMs = 0;
352
+ }
353
+ this.baseClip = clip;
354
+ this.baseTimeMs = 0;
355
+ this.baseSpeed = opts.speed ?? 1;
356
+ this.baseLoop = opts.loop ?? clip.loop !== false;
357
+ this.evaluatePose();
358
+ return this;
359
+ }
360
+ /** Play an action overlay clip (e.g. axe chop, pickaxe mine, lantern raise) masked onto specific bones. */
361
+ playOverlay(clipOrName, opts = {}) {
362
+ const clip = typeof clipOrName === "string" ? this.skeleton.clips.get(clipOrName) : clipOrName;
363
+ if (!clip) throw new Error(`Rig2D(${this.skeleton.id}): unknown overlay clip "${String(clipOrName)}"`);
364
+ this.overlayClip = clip;
365
+ this.overlayTimeMs = 0;
366
+ this.overlaySpeed = opts.speed ?? 1;
367
+ this.overlayLoop = opts.loop ?? Boolean(clip.loop);
368
+ this.overlayWeight = Math.max(0, Math.min(1, opts.weight ?? 1));
369
+ this.overlayBlendInMs = Math.max(0, opts.blendInMs ?? 50);
370
+ this.overlayBlendOutMs = Math.max(0, opts.blendOutMs ?? 80);
371
+ this.overlayMask.fill(0);
372
+ if (!opts.bones || opts.bones.length === 0) this.overlayMask.fill(1);
373
+ else {
374
+ const includeChildren = opts.includeChildren !== false;
375
+ for (const name of opts.bones) {
376
+ const idx = this.skeleton.boneIndexByName.get(name);
377
+ if (idx !== void 0) this.overlayMask[idx] = 1;
378
+ }
379
+ if (includeChildren) {
380
+ const bones = this.skeleton.bones;
381
+ for (let i = 0; i < bones.length; i++) {
382
+ const p = bones[i].parentIndex;
383
+ if (p >= 0 && this.overlayMask[p]) this.overlayMask[i] = 1;
384
+ }
385
+ }
386
+ }
387
+ this.evaluatePose();
388
+ return this;
389
+ }
390
+ clearOverlay() {
391
+ this.overlayClip = null;
392
+ this.evaluatePose();
393
+ return this;
394
+ }
395
+ /** Deterministically advance animation tracks by `deltaMs` and fire any crossed keyframe events. */
396
+ step(deltaMs) {
397
+ const dt = Math.max(0, deltaMs);
398
+ if (this.prevClip && this.crossfadeDurationMs > 0) {
399
+ this.crossfadeElapsedMs += dt;
400
+ this.prevTimeMs = this.advanceClipTime(this.prevClip, this.prevTimeMs, dt * this.baseSpeed, true, false);
401
+ if (this.crossfadeElapsedMs >= this.crossfadeDurationMs) {
402
+ this.prevClip = null;
403
+ this.crossfadeDurationMs = 0;
404
+ }
405
+ }
406
+ if (this.baseClip) this.baseTimeMs = this.advanceClipTime(this.baseClip, this.baseTimeMs, dt * this.baseSpeed, this.baseLoop, true);
407
+ if (this.overlayClip) {
408
+ const nextT = this.advanceClipTime(this.overlayClip, this.overlayTimeMs, dt * this.overlaySpeed, this.overlayLoop, true);
409
+ this.overlayTimeMs = nextT;
410
+ if (!this.overlayLoop && nextT >= this.overlayClip.durationMs) this.overlayClip = null;
411
+ }
412
+ this.evaluatePose();
413
+ return this;
414
+ }
415
+ advanceClipTime(clip, prevTime, scaledDt, loop, fireEvents) {
416
+ const dur = Math.max(.001, clip.durationMs);
417
+ if (scaledDt <= 0) return prevTime;
418
+ const rawNext = prevTime + scaledDt;
419
+ if (!loop) {
420
+ const clamped = Math.min(dur, rawNext);
421
+ if (fireEvents && clip.events?.length) this.emitEventsInRange(clip, prevTime, clamped, true);
422
+ return clamped;
423
+ }
424
+ const wrapped = rawNext % dur;
425
+ if (fireEvents && clip.events?.length) {
426
+ if (rawNext < dur) this.emitEventsInRange(clip, prevTime, rawNext, false);
427
+ else {
428
+ this.emitEventsInRange(clip, prevTime, dur, true);
429
+ const fullLoops = Math.floor(rawNext / dur) - 1;
430
+ for (let k = 0; k < Math.min(4, fullLoops); k++) this.emitEventsInRange(clip, -1, dur, true);
431
+ this.emitEventsInRange(clip, -1, wrapped, false);
432
+ }
433
+ }
434
+ return wrapped;
435
+ }
436
+ emitEventsInRange(clip, t0, t1, inclusiveEnd) {
437
+ const evs = clip.events;
438
+ if (!evs || this.listeners.size === 0) return;
439
+ for (let i = 0; i < evs.length; i++) {
440
+ const ev = evs[i];
441
+ const afterStart = ev.timeMs > t0;
442
+ const beforeEnd = inclusiveEnd ? ev.timeMs <= t1 : ev.timeMs < t1;
443
+ if (afterStart && beforeEnd) for (const fn of this.listeners) fn(ev.name, clip.name, ev.timeMs);
444
+ }
445
+ }
446
+ evaluatePose() {
447
+ const bones = this.skeleton.bones;
448
+ const fadeAlpha = this.prevClip && this.crossfadeDurationMs > 0 ? Math.min(1, this.crossfadeElapsedMs / this.crossfadeDurationMs) : 1;
449
+ let overlayAlpha = 0;
450
+ if (this.overlayClip) {
451
+ let env = 1;
452
+ if (this.overlayBlendInMs > 0 && this.overlayTimeMs < this.overlayBlendInMs) env = this.overlayTimeMs / this.overlayBlendInMs;
453
+ else if (!this.overlayLoop && this.overlayBlendOutMs > 0 && this.overlayClip.durationMs - this.overlayTimeMs < this.overlayBlendOutMs) env = Math.max(0, (this.overlayClip.durationMs - this.overlayTimeMs) / this.overlayBlendOutMs);
454
+ overlayAlpha = this.overlayWeight * env;
455
+ }
456
+ for (let i = 0; i < bones.length; i++) {
457
+ const b = bones[i];
458
+ let dx = 0, dy = 0, drot = 0, sx = 1, sy = 1;
459
+ if (this.baseClip) {
460
+ sampleBoneTrack(this.baseClip.tracks[b.name], this.baseTimeMs, this.sampleA);
461
+ dx = this.sampleA.dx;
462
+ dy = this.sampleA.dy;
463
+ drot = this.sampleA.drot;
464
+ sx = this.sampleA.sx;
465
+ sy = this.sampleA.sy;
466
+ if (this.prevClip && fadeAlpha < 1) {
467
+ sampleBoneTrack(this.prevClip.tracks[b.name], this.prevTimeMs, this.sampleB);
468
+ dx = this.sampleB.dx + (dx - this.sampleB.dx) * fadeAlpha;
469
+ dy = this.sampleB.dy + (dy - this.sampleB.dy) * fadeAlpha;
470
+ drot = this.sampleB.drot + wrapAngleDelta(this.sampleB.drot, drot) * fadeAlpha;
471
+ sx = this.sampleB.sx + (sx - this.sampleB.sx) * fadeAlpha;
472
+ sy = this.sampleB.sy + (sy - this.sampleB.sy) * fadeAlpha;
473
+ }
474
+ }
475
+ if (this.overlayClip && overlayAlpha > 0 && this.overlayMask[i]) {
476
+ if (sampleBoneTrack(this.overlayClip.tracks[b.name], this.overlayTimeMs, this.sampleB)) {
477
+ dx = dx + (this.sampleB.dx - dx) * overlayAlpha;
478
+ dy = dy + (this.sampleB.dy - dy) * overlayAlpha;
479
+ drot = drot + wrapAngleDelta(drot, this.sampleB.drot) * overlayAlpha;
480
+ sx = sx + (this.sampleB.sx - sx) * overlayAlpha;
481
+ sy = sy + (this.sampleB.sy - sy) * overlayAlpha;
482
+ }
483
+ }
484
+ this.boneLocalX[i] = b.restX + dx + this.boneManualX[i];
485
+ this.boneLocalY[i] = b.restY + dy + this.boneManualY[i];
486
+ this.boneLocalRot[i] = b.restRotation + drot + this.boneManualRot[i];
487
+ this.boneLocalScaleX[i] = b.restScaleX * sx;
488
+ this.boneLocalScaleY[i] = b.restScaleY * sy;
489
+ }
490
+ const applySlotTracks = (clip, t) => {
491
+ if (!clip?.slotTracks) return;
492
+ for (const [slotName, keys] of Object.entries(clip.slotTracks)) {
493
+ const sIdx = this.skeleton.slotIndexByName.get(slotName);
494
+ if (sIdx === void 0 || !keys.length) continue;
495
+ let chosen;
496
+ for (let k = 0; k < keys.length; k++) if (keys[k].timeMs <= t) chosen = keys[k].attachment;
497
+ else break;
498
+ if (chosen !== void 0) this.slotAttachments[sIdx] = chosen;
499
+ }
500
+ };
501
+ applySlotTracks(this.baseClip, this.baseTimeMs);
502
+ applySlotTracks(this.overlayClip, this.overlayTimeMs);
503
+ this.worldDirty = true;
504
+ }
505
+ /** Solve hierarchical 2D Forward Kinematics across all bones in topological order (zero heap allocation). */
506
+ solveWorldTransforms() {
507
+ if (!this.worldDirty) return this;
508
+ this.worldDirty = false;
509
+ const rootSx = (this.flipX ? -1 : 1) * this.scaleX;
510
+ const rootSy = (this.flipY ? -1 : 1) * this.scaleY;
511
+ const rCos = Math.cos(this.rotation);
512
+ const rSin = Math.sin(this.rotation);
513
+ const ra = rCos * rootSx;
514
+ const rb = rSin * rootSx;
515
+ const rc = -rSin * rootSy;
516
+ const rd = rCos * rootSy;
517
+ const rtx = this.x;
518
+ const rty = this.y;
519
+ const bones = this.skeleton.bones;
520
+ const mat = this.boneWorldMat;
521
+ for (let i = 0; i < bones.length; i++) {
522
+ const p = bones[i].parentIndex;
523
+ const lx = this.boneLocalX[i];
524
+ const ly = this.boneLocalY[i];
525
+ const lr = this.boneLocalRot[i];
526
+ const lsx = this.boneLocalScaleX[i];
527
+ const lsy = this.boneLocalScaleY[i];
528
+ const cs = Math.cos(lr);
529
+ const sn = Math.sin(lr);
530
+ const la = cs * lsx;
531
+ const lb = sn * lsx;
532
+ const lc = -sn * lsy;
533
+ const ld = cs * lsy;
534
+ let pa, pb, pc, pd, ptx, pty;
535
+ if (p < 0) {
536
+ pa = ra;
537
+ pb = rb;
538
+ pc = rc;
539
+ pd = rd;
540
+ ptx = rtx;
541
+ pty = rty;
542
+ this.boneWorldRot[i] = this.rotation + (this.flipX !== this.flipY ? -lr : lr);
543
+ this.boneWorldScaleX[i] = rootSx * lsx;
544
+ this.boneWorldScaleY[i] = rootSy * lsy;
545
+ } else {
546
+ const po = p * 6;
547
+ pa = mat[po];
548
+ pb = mat[po + 1];
549
+ pc = mat[po + 2];
550
+ pd = mat[po + 3];
551
+ ptx = mat[po + 4];
552
+ pty = mat[po + 5];
553
+ this.boneWorldRot[i] = this.boneWorldRot[p] + (this.flipX !== this.flipY ? -lr : lr);
554
+ this.boneWorldScaleX[i] = this.boneWorldScaleX[p] * lsx;
555
+ this.boneWorldScaleY[i] = this.boneWorldScaleY[p] * lsy;
556
+ }
557
+ const o = i * 6;
558
+ mat[o] = pa * la + pc * lb;
559
+ mat[o + 1] = pb * la + pd * lb;
560
+ mat[o + 2] = pa * lc + pc * ld;
561
+ mat[o + 3] = pb * lc + pd * ld;
562
+ mat[o + 4] = pa * lx + pc * ly + ptx;
563
+ mat[o + 5] = pb * lx + pd * ly + pty;
564
+ }
565
+ return this;
566
+ }
567
+ /** Query a bone's solved world-space position & orientation (ideal for attaching torches, lights, particles, or hitboxes). */
568
+ getBoneWorldTransform(boneName, localOffsetX = 0, localOffsetY = 0, out) {
569
+ this.solveWorldTransforms();
570
+ const idx = this.skeleton.boneIndexByName.get(boneName);
571
+ if (idx === void 0) throw new Error(`Rig2D(${this.skeleton.id}): unknown bone "${boneName}"`);
572
+ const o = idx * 6;
573
+ const a = this.boneWorldMat[o];
574
+ const b = this.boneWorldMat[o + 1];
575
+ const c = this.boneWorldMat[o + 2];
576
+ const d = this.boneWorldMat[o + 3];
577
+ const tx = this.boneWorldMat[o + 4];
578
+ const ty = this.boneWorldMat[o + 5];
579
+ const wx = a * localOffsetX + c * localOffsetY + tx;
580
+ const wy = b * localOffsetX + d * localOffsetY + ty;
581
+ const target = out ?? {
582
+ x: 0,
583
+ y: 0,
584
+ rotation: 0,
585
+ scaleX: 1,
586
+ scaleY: 1,
587
+ a: 1,
588
+ b: 0,
589
+ c: 0,
590
+ d: 1,
591
+ tx: 0,
592
+ ty: 0
593
+ };
594
+ target.x = wx;
595
+ target.y = wy;
596
+ target.rotation = this.boneWorldRot[idx];
597
+ target.scaleX = this.boneWorldScaleX[idx];
598
+ target.scaleY = this.boneWorldScaleY[idx];
599
+ target.a = a;
600
+ target.b = b;
601
+ target.c = c;
602
+ target.d = d;
603
+ target.tx = tx;
604
+ target.ty = ty;
605
+ return target;
606
+ }
607
+ };
608
+ /**
609
+ * Mount a `Rig2DInstance` onto a Stage `Scene` using nested `Container` + `ImageObject` nodes.
610
+ * Works identically across WebGL2 (single-batch when sharing a cutout atlas!), WebGPU, Canvas2D, and Node 60fps Headless.
611
+ */
612
+ function mountRig2D(scene, instance, opts = {}) {
613
+ const root = scene.add.container(instance.x, instance.y);
614
+ if (opts.trackId) root.trackId = opts.trackId;
615
+ if (opts.depth !== void 0) root.setDepth(opts.depth);
616
+ let shadow = null;
617
+ let shadowSkewX = 0;
618
+ if (opts.contactShadow !== false) {
619
+ const scfg = opts.contactShadow ?? {
620
+ rx: 16,
621
+ ry: 7,
622
+ alpha: .28,
623
+ color: 592656,
624
+ offsetY: 2
625
+ };
626
+ shadow = scene.make.graphics({ add: false });
627
+ shadow.zIndex = -9999;
628
+ shadow.fillStyle(scfg.color ?? 592656, scfg.alpha ?? .28);
629
+ shadow.fillEllipse(0, scfg.offsetY ?? 2, scfg.rx * 2, scfg.ry * 2);
630
+ root.add(shadow);
631
+ }
632
+ const bodyContainer = scene.make.container(0, 0);
633
+ bodyContainer.zIndex = 0;
634
+ root.add(bodyContainer);
635
+ const bones = instance.skeleton.bones;
636
+ const boneContainers = new Array(bones.length);
637
+ for (let i = 0; i < bones.length; i++) {
638
+ const bc = scene.make.container(bones[i].restX, bones[i].restY);
639
+ const p = bones[i].parentIndex;
640
+ if (p < 0) bodyContainer.add(bc);
641
+ else boneContainers[p].add(bc);
642
+ boneContainers[i] = bc;
643
+ }
644
+ for (let i = 0; i < boneContainers.length; i++) boneContainers[i].destroy();
645
+ const slots = instance.skeleton.slots;
646
+ const slotImages = new Array(slots.length);
647
+ const fallbackKey = instance.skeleton.attachments.values().next().value?.textureKey ?? "__WHITE";
648
+ for (let i = 0; i < slots.length; i++) {
649
+ const s = slots[i];
650
+ const att = instance.getSlotAttachmentByIndex(i);
651
+ const img = scene.make.image(0, 0, att?.textureKey ?? fallbackKey, att?.frame);
652
+ img.zIndex = s.zOrder;
653
+ img.blendMode = s.blendMode;
654
+ bodyContainer.add(img);
655
+ slotImages[i] = img;
656
+ }
657
+ const locMat = new Float32Array(bones.length * 6);
658
+ const locRot = new Float32Array(bones.length);
659
+ const locSx = new Float32Array(bones.length);
660
+ const locSy = new Float32Array(bones.length);
661
+ const sync = () => {
662
+ root.x = instance.x;
663
+ root.y = instance.y;
664
+ root.rotation = instance.rotation;
665
+ bodyContainer.scaleX = (instance.flipX ? -1 : 1) * instance.scaleX;
666
+ bodyContainer.scaleY = (instance.flipY ? -1 : 1) * instance.scaleY;
667
+ if (shadow) {
668
+ shadow.scaleX = instance.scaleX + Math.abs(shadowSkewX) * .15;
669
+ shadow.scaleY = instance.scaleY;
670
+ }
671
+ for (let i = 0; i < bones.length; i++) {
672
+ const p = bones[i].parentIndex;
673
+ const lx = instance.boneLocalX[i];
674
+ const ly = instance.boneLocalY[i];
675
+ const lr = instance.boneLocalRot[i];
676
+ const lsx = instance.boneLocalScaleX[i];
677
+ const lsy = instance.boneLocalScaleY[i];
678
+ const cs = Math.cos(lr);
679
+ const sn = Math.sin(lr);
680
+ const la = cs * lsx, lb = sn * lsx, lc = -sn * lsy, ld = cs * lsy;
681
+ const o = i * 6;
682
+ if (p < 0) {
683
+ locMat[o] = la;
684
+ locMat[o + 1] = lb;
685
+ locMat[o + 2] = lc;
686
+ locMat[o + 3] = ld;
687
+ locMat[o + 4] = lx;
688
+ locMat[o + 5] = ly;
689
+ locRot[i] = lr;
690
+ locSx[i] = lsx;
691
+ locSy[i] = lsy;
692
+ } else {
693
+ const po = p * 6;
694
+ const pa = locMat[po], pb = locMat[po + 1], pc = locMat[po + 2], pd = locMat[po + 3];
695
+ locMat[o] = pa * la + pc * lb;
696
+ locMat[o + 1] = pb * la + pd * lb;
697
+ locMat[o + 2] = pa * lc + pc * ld;
698
+ locMat[o + 3] = pb * lc + pd * ld;
699
+ locMat[o + 4] = pa * lx + pc * ly + locMat[po + 4];
700
+ locMat[o + 5] = pb * lx + pd * ly + locMat[po + 5];
701
+ locRot[i] = locRot[p] + lr;
702
+ locSx[i] = locSx[p] * lsx;
703
+ locSy[i] = locSy[p] * lsy;
704
+ }
705
+ }
706
+ for (let i = 0; i < slots.length; i++) {
707
+ const img = slotImages[i];
708
+ const att = instance.getSlotAttachmentByIndex(i);
709
+ if (!att || instance.slotAlpha[i] <= 0) {
710
+ img.visible = false;
711
+ continue;
712
+ }
713
+ img.visible = true;
714
+ if (img.texture.key !== att.textureKey || att.frame !== void 0 && img.frame.name !== String(att.frame)) img.setTexture(att.textureKey, att.frame);
715
+ img.setOrigin(att.originX ?? .5, att.originY ?? .5);
716
+ img.zIndex = instance.slotZOrder[i];
717
+ const bIdx = slots[i].boneIndex;
718
+ const bo = bIdx * 6;
719
+ const ax = att.x ?? 0;
720
+ const ay = att.y ?? 0;
721
+ img.x = locMat[bo] * ax + locMat[bo + 2] * ay + locMat[bo + 4];
722
+ img.y = locMat[bo + 1] * ax + locMat[bo + 3] * ay + locMat[bo + 5];
723
+ img.rotation = locRot[bIdx] + (att.rotation ?? 0);
724
+ img.scaleX = locSx[bIdx] * (att.scaleX ?? 1);
725
+ img.scaleY = locSy[bIdx] * (att.scaleY ?? 1);
726
+ const slotTint = instance.slotTint[i];
727
+ const attTint = att.tint ?? 0xffffff;
728
+ const mergedTint = slotTint === 0xffffff ? attTint : attTint === 0xffffff ? slotTint : (slotTint >> 16 & 255) * (attTint >> 16 & 255) / 255 << 16 | (slotTint >> 8 & 255) * (attTint >> 8 & 255) / 255 << 8 | ((slotTint & 255) * (attTint & 255) / 255 | 0);
729
+ img.setTint(mergedTint);
730
+ img.alpha = instance.slotAlpha[i] * (att.alpha ?? 1);
731
+ }
732
+ };
733
+ sync();
734
+ return {
735
+ container: root,
736
+ instance,
737
+ shadow,
738
+ slotImages,
739
+ update(deltaMs = 0) {
740
+ if (deltaMs > 0) instance.step(deltaMs);
741
+ sync();
742
+ },
743
+ sync,
744
+ destroy() {
745
+ root.destroy();
746
+ }
747
+ };
748
+ }
749
+ /**
750
+ * Pack procedural 2D cutout parts (heads, hats, robes, axes, pickaxes, torches, shields) onto a single padded atlas canvas
751
+ * with crisp hand-drawn outlines — zero external PNG files needed!
752
+ */
753
+ function bakeCutoutAtlas(textureKey, parts, createCanvasFn, padding = 4) {
754
+ const makeCanvas = createCanvasFn ?? ((w, h) => {
755
+ if (typeof document === "undefined") throw new Error("bakeCutoutAtlas: pass createCanvasFn in headless Node environments");
756
+ const c = document.createElement("canvas");
757
+ c.width = w;
758
+ c.height = h;
759
+ return c;
760
+ });
761
+ const maxShelfW = 512;
762
+ let curX = padding;
763
+ let curY = padding;
764
+ let rowH = 0;
765
+ let usedW = 64;
766
+ const placements = [];
767
+ for (const spec of parts) {
768
+ const pw = Math.ceil(spec.width);
769
+ const ph = Math.ceil(spec.height);
770
+ if (curX + pw + padding > maxShelfW && curX > padding) {
771
+ curX = padding;
772
+ curY += rowH + padding;
773
+ rowH = 0;
774
+ }
775
+ placements.push({
776
+ spec,
777
+ x: curX,
778
+ y: curY
779
+ });
780
+ curX += pw + padding;
781
+ if (curX > usedW) usedW = curX;
782
+ if (ph > rowH) rowH = ph;
783
+ }
784
+ const atlasW = Math.max(32, usedW);
785
+ const atlasH = Math.max(32, curY + rowH + padding);
786
+ const canvas = makeCanvas(atlasW, atlasH);
787
+ const ctx = canvas.getContext("2d");
788
+ if (!ctx) throw new Error("bakeCutoutAtlas: 2D context unavailable");
789
+ ctx.clearRect(0, 0, atlasW, atlasH);
790
+ ctx.lineJoin = "round";
791
+ ctx.lineCap = "round";
792
+ const frames = {};
793
+ const attachments = {};
794
+ for (const { spec, x, y } of placements) {
795
+ ctx.save();
796
+ ctx.translate(x, y);
797
+ for (const op of spec.shapes) {
798
+ ctx.beginPath();
799
+ switch (op.kind) {
800
+ case "roundRect": {
801
+ const r = Math.min(op.r, op.w * .5, op.h * .5);
802
+ ctx.moveTo(op.x + r, op.y);
803
+ ctx.arcTo(op.x + op.w, op.y, op.x + op.w, op.y + op.h, r);
804
+ ctx.arcTo(op.x + op.w, op.y + op.h, op.x, op.y + op.h, r);
805
+ ctx.arcTo(op.x, op.y + op.h, op.x, op.y, r);
806
+ ctx.arcTo(op.x, op.y, op.x + op.w, op.y, r);
807
+ ctx.closePath();
808
+ break;
809
+ }
810
+ case "ellipse":
811
+ ctx.ellipse(op.cx, op.cy, op.rx, op.ry, 0, 0, TWO_PI);
812
+ break;
813
+ case "circle":
814
+ ctx.arc(op.cx, op.cy, op.r, 0, TWO_PI);
815
+ break;
816
+ case "poly":
817
+ if (op.points.length > 0) {
818
+ ctx.moveTo(op.points[0][0], op.points[0][1]);
819
+ for (let i = 1; i < op.points.length; i++) ctx.lineTo(op.points[i][0], op.points[i][1]);
820
+ if (op.close !== false) ctx.closePath();
821
+ }
822
+ break;
823
+ case "line":
824
+ ctx.moveTo(op.x1, op.y1);
825
+ ctx.lineTo(op.x2, op.y2);
826
+ }
827
+ if ("fill" in op && op.fill !== void 0) {
828
+ ctx.fillStyle = rgbToCss(op.fill);
829
+ ctx.fill();
830
+ }
831
+ if (op.stroke !== void 0) {
832
+ ctx.strokeStyle = rgbToCss(op.stroke);
833
+ ctx.lineWidth = op.lineWidth ?? 2;
834
+ ctx.stroke();
835
+ }
836
+ }
837
+ ctx.restore();
838
+ frames[spec.id] = {
839
+ x,
840
+ y,
841
+ w: spec.width,
842
+ h: spec.height
843
+ };
844
+ attachments[spec.id] = {
845
+ id: spec.id,
846
+ textureKey,
847
+ frame: spec.id,
848
+ width: spec.width,
849
+ height: spec.height,
850
+ originX: spec.originX ?? .5,
851
+ originY: spec.originY ?? .5,
852
+ x: spec.offsetX ?? 0,
853
+ y: spec.offsetY ?? 0,
854
+ rotation: spec.rotation ?? 0
855
+ };
856
+ }
857
+ return {
858
+ textureKey,
859
+ canvas,
860
+ width: atlasW,
861
+ height: atlasH,
862
+ frames,
863
+ attachments,
864
+ registerOnScene(scene) {
865
+ const tex = scene.textures.addImage(textureKey, canvas);
866
+ if (!tex) return;
867
+ for (const [frameId, rect] of Object.entries(frames)) tex.add(frameId, 0, rect.x, rect.y, rect.w, rect.h);
868
+ }
869
+ };
870
+ }
871
+ export { Rig2DInstance, bakeCutoutAtlas, defineRig2DSkeleton, evalRigCurve, mountRig2D, wrapAngleDelta };