@holtjs/stage 0.5.2 → 0.7.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/anims.js ADDED
@@ -0,0 +1,436 @@
1
+ // src/anims.ts
2
+ const LOOP_CLIP_RE = /^(?:idle|walk|run|move|jog|sprint|fly|swim|hover|burn|burning|loop|breathe|patrol)$/i;
3
+ const CARDINAL_DIR_INDEX = {
4
+ e: {
5
+ idx4: 0,
6
+ idx8: 0
7
+ },
8
+ east: {
9
+ idx4: 0,
10
+ idx8: 0
11
+ },
12
+ right: {
13
+ idx4: 0,
14
+ idx8: 0
15
+ },
16
+ se: { idx8: 1 },
17
+ southeast: { idx8: 1 },
18
+ s: {
19
+ idx4: 1,
20
+ idx8: 2
21
+ },
22
+ south: {
23
+ idx4: 1,
24
+ idx8: 2
25
+ },
26
+ down: {
27
+ idx4: 1,
28
+ idx8: 2
29
+ },
30
+ front: {
31
+ idx4: 1,
32
+ idx8: 2
33
+ },
34
+ sw: { idx8: 3 },
35
+ southwest: { idx8: 3 },
36
+ w: {
37
+ idx4: 2,
38
+ idx8: 4
39
+ },
40
+ west: {
41
+ idx4: 2,
42
+ idx8: 4
43
+ },
44
+ left: {
45
+ idx4: 2,
46
+ idx8: 4
47
+ },
48
+ nw: { idx8: 5 },
49
+ northwest: { idx8: 5 },
50
+ n: {
51
+ idx4: 3,
52
+ idx8: 6
53
+ },
54
+ north: {
55
+ idx4: 3,
56
+ idx8: 6
57
+ },
58
+ up: {
59
+ idx4: 3,
60
+ idx8: 6
61
+ },
62
+ back: {
63
+ idx4: 3,
64
+ idx8: 6
65
+ },
66
+ ne: { idx8: 7 },
67
+ northeast: { idx8: 7 }
68
+ };
69
+ function normalizeEvents(raw) {
70
+ if (!raw) return [];
71
+ return typeof raw === "string" ? [raw] : [...raw];
72
+ }
73
+ function actorBasename(actor) {
74
+ const slash = actor.lastIndexOf("/");
75
+ return slash >= 0 ? actor.slice(slash + 1) : actor;
76
+ }
77
+ function parseFrameConvention(frame) {
78
+ const name = String(frame.name);
79
+ if (name === "__BASE") return null;
80
+ if (frame.clip && frame.animFrameIndex !== null) return {
81
+ frameName: name,
82
+ actor: frame.actor ?? "",
83
+ clip: frame.clip,
84
+ dir: frame.dir,
85
+ frameIdx: frame.animFrameIndex,
86
+ loop: frame.animLoop
87
+ };
88
+ const slashDir = /^(.+)\/([^/]+)\/d?(\d+|east|south|west|north|down|up|left|right|front|back|se|sw|ne|nw)\/f?(\d+)$/i.exec(name);
89
+ if (slashDir) {
90
+ const rawDir = slashDir[3];
91
+ const dir = /^\d+$/.test(rawDir) ? Number(rawDir) : rawDir.toLowerCase();
92
+ return {
93
+ frameName: name,
94
+ actor: slashDir[1],
95
+ clip: slashDir[2],
96
+ dir,
97
+ frameIdx: Number(slashDir[4])
98
+ };
99
+ }
100
+ const slashFlat = /^(.+)\/([^/]+)\/f?(\d+)$/i.exec(name);
101
+ if (slashFlat) return {
102
+ frameName: name,
103
+ actor: slashFlat[1],
104
+ clip: slashFlat[2],
105
+ dir: null,
106
+ frameIdx: Number(slashFlat[3])
107
+ };
108
+ const underDir = /^(.+?)_([a-zA-Z0-9]+)_d?(\d+|east|south|west|north|down|up|left|right|front|back|se|sw|ne|nw)_f?(\d+)$/i.exec(name);
109
+ if (underDir) {
110
+ const rawDir = underDir[3];
111
+ const dir = /^\d+$/.test(rawDir) ? Number(rawDir) : rawDir.toLowerCase();
112
+ return {
113
+ frameName: name,
114
+ actor: underDir[1],
115
+ clip: underDir[2],
116
+ dir,
117
+ frameIdx: Number(underDir[4])
118
+ };
119
+ }
120
+ const underTwo = /^(.+?)_([a-zA-Z]+)_f?(\d+)$/.exec(name);
121
+ if (underTwo) return {
122
+ frameName: name,
123
+ actor: underTwo[1],
124
+ clip: underTwo[2],
125
+ dir: null,
126
+ frameIdx: Number(underTwo[3])
127
+ };
128
+ const underOne = /^([a-zA-Z0-9/-]+)[_/-]f?(\d+)$/.exec(name);
129
+ if (underOne) return {
130
+ frameName: name,
131
+ actor: "",
132
+ clip: underOne[1],
133
+ dir: null,
134
+ frameIdx: Number(underOne[2])
135
+ };
136
+ return null;
137
+ }
138
+ var AnimationManager = class {
139
+ textures;
140
+ anims = /* @__PURE__ */ new Map();
141
+ aliases = /* @__PURE__ */ new Map();
142
+ dirGroups = /* @__PURE__ */ new Map();
143
+ constructor(textures) {
144
+ this.textures = textures;
145
+ }
146
+ exists(key) {
147
+ return this.anims.has(key) || this.aliases.has(key);
148
+ }
149
+ get(key) {
150
+ return this.anims.get(key) ?? this.aliases.get(key) ?? null;
151
+ }
152
+ /** Resolve an animation by key or throw a fail-fast diagnostic listing valid animations. */
153
+ resolveOrThrow(key) {
154
+ if (typeof key !== "string") return key;
155
+ const found = this.get(key);
156
+ if (found) return found;
157
+ const sample = this.listKeys().slice(0, 12).join(", ");
158
+ throw new Error(`Stage anims: unknown animation "${key}"${sample ? ` (registered: ${sample}${this.anims.size > 12 ? ", ..." : ""})` : " (no animations registered)"}`);
159
+ }
160
+ getDirectionalGroup(baseKey) {
161
+ return this.dirGroups.get(baseKey) ?? null;
162
+ }
163
+ /** Resolve a directional clip group (`'survivor/walk'` or `'survivor_walk'`) or throw a fail-fast diagnostic. */
164
+ resolveDirectionalOrThrow(baseKey) {
165
+ const found = this.dirGroups.get(baseKey);
166
+ if (found) return found;
167
+ const sample = this.listDirectionalGroups().slice(0, 12).join(", ");
168
+ throw new Error(`Stage anims: unknown directional clip group "${baseKey}"${sample ? ` (registered groups: ${sample}${this.dirGroups.size > 12 ? ", ..." : ""})` : " (call scene.anims.createFromAtlas(textureKey) first)"}`);
169
+ }
170
+ listKeys() {
171
+ return Array.from(this.anims.keys());
172
+ }
173
+ listDirectionalGroups() {
174
+ const seen = /* @__PURE__ */ new Set();
175
+ const out = [];
176
+ for (const [k, grp] of this.dirGroups.entries()) if (k === grp.baseKey && !seen.has(grp)) {
177
+ seen.add(grp);
178
+ out.push(k);
179
+ }
180
+ return out;
181
+ }
182
+ create(config) {
183
+ if (!config.frames || config.frames.length === 0) throw new Error(`Stage anims.create("${config.key}"): frames array must not be empty`);
184
+ const count = config.frames.length;
185
+ const frameRate = config.frameRate !== void 0 && config.frameRate > 0 ? config.frameRate : config.duration !== void 0 && config.duration > 0 ? count * 1e3 / config.duration : 10;
186
+ const baseMsPerFrame = 1e3 / frameRate;
187
+ const compiled = new Array(count);
188
+ let offsetMs = 0;
189
+ for (let i = 0; i < count; i++) {
190
+ const f = config.frames[i];
191
+ const texKey = f.key ?? config.defaultTextureKey;
192
+ if (!texKey) throw new Error(`Stage anims.create("${config.key}"): frame ${i} missing texture key`);
193
+ const dur = f.duration !== void 0 && f.duration > 0 ? f.duration : baseMsPerFrame;
194
+ const evs = [...normalizeEvents(config.events?.[i]), ...normalizeEvents(f.events)];
195
+ compiled[i] = {
196
+ index: i,
197
+ textureKey: texKey,
198
+ frameName: f.frame,
199
+ durationMs: dur,
200
+ offsetMs,
201
+ events: evs
202
+ };
203
+ offsetMs += dur;
204
+ }
205
+ const anim = {
206
+ key: config.key,
207
+ frames: compiled,
208
+ frameRate,
209
+ msPerFrame: baseMsPerFrame,
210
+ totalDurationMs: Math.max(.001, offsetMs),
211
+ repeat: config.repeat ?? 0,
212
+ yoyo: Boolean(config.yoyo)
213
+ };
214
+ this.anims.set(config.key, anim);
215
+ return anim;
216
+ }
217
+ /** Register an alias key pointing to an existing `StageAnimation` (does not overwrite explicit primary keys). */
218
+ registerAlias(aliasKey, target) {
219
+ if (!this.anims.has(aliasKey)) this.aliases.set(aliasKey, target);
220
+ }
221
+ /** Register a directional animation group (and optional alias keys such as bare `'survivor/walk'` & `'survivor_walk'`). */
222
+ registerDirectionalGroup(group, aliases = []) {
223
+ this.dirGroups.set(group.baseKey, group);
224
+ for (const a of aliases) if (!this.dirGroups.has(a)) this.dirGroups.set(a, group);
225
+ }
226
+ remove(key) {
227
+ this.aliases.delete(key);
228
+ return this.anims.delete(key);
229
+ }
230
+ clear() {
231
+ this.anims.clear();
232
+ this.aliases.clear();
233
+ this.dirGroups.clear();
234
+ }
235
+ generateFrameNames(textureKey, config = {}) {
236
+ const out = [];
237
+ const prefix = config.prefix ?? "";
238
+ const suffix = config.suffix ?? "";
239
+ const pad = config.zeroPad ?? 0;
240
+ if (config.frames) {
241
+ for (const f of config.frames) {
242
+ const token = typeof f === "number" && pad > 0 ? String(f).padStart(pad, "0") : String(f);
243
+ out.push({
244
+ key: textureKey,
245
+ frame: `${prefix}${token}${suffix}`
246
+ });
247
+ }
248
+ return out;
249
+ }
250
+ const start = config.start ?? 0;
251
+ const end = config.end ?? start;
252
+ const step = start <= end ? 1 : -1;
253
+ for (let i = start; step > 0 ? i <= end : i >= end; i += step) {
254
+ const token = pad > 0 ? String(i).padStart(pad, "0") : String(i);
255
+ out.push({
256
+ key: textureKey,
257
+ frame: `${prefix}${token}${suffix}`
258
+ });
259
+ }
260
+ return out;
261
+ }
262
+ generateFrameNumbers(textureKey, config = {}) {
263
+ if (config.frames) return config.frames.map((f) => ({
264
+ key: textureKey,
265
+ frame: f
266
+ }));
267
+ const tex = this.textures.get(textureKey);
268
+ const numericMax = Object.keys(tex.frames).filter((k) => /^\d+$/.test(k)).reduce((m, k) => Math.max(m, Number(k)), -1);
269
+ const start = config.start ?? 0;
270
+ const end = config.end ?? Math.max(start, numericMax);
271
+ const out = [];
272
+ for (let i = start; i <= end; i++) out.push({
273
+ key: textureKey,
274
+ frame: i
275
+ });
276
+ return out;
277
+ }
278
+ /**
279
+ * Auto-discover and compile all animations (both 4/8-directional character clips and non-directional prop strips)
280
+ * directly from an atlas texture registered via `textures.addAtlas` or `registerThreeAtlasOnStage`!
281
+ *
282
+ * Automatically registers bare actor aliases (e.g. `chars/survivor` -> `survivor/walk` AND `survivor_walk`)
283
+ * whenever the basename is unambiguous across the atlas, eliminating manual frame-table indexing bugs.
284
+ */
285
+ createFromAtlas(textureKey, options = {}) {
286
+ const tex = this.textures.get(textureKey);
287
+ const defaultFps = options.defaultFrameRate ?? 10;
288
+ const rules = options.clips ?? {};
289
+ const parsed = [];
290
+ for (const frame of Object.values(tex.frames)) {
291
+ const p = parseFrameConvention(frame);
292
+ if (p) parsed.push(p);
293
+ }
294
+ const actorsByBase = /* @__PURE__ */ new Map();
295
+ for (const p of parsed) {
296
+ if (!p.actor) continue;
297
+ const base = actorBasename(p.actor);
298
+ let set = actorsByBase.get(base);
299
+ if (!set) {
300
+ set = /* @__PURE__ */ new Set();
301
+ actorsByBase.set(base, set);
302
+ }
303
+ set.add(p.actor);
304
+ }
305
+ const resolveRule = (actor, clip) => {
306
+ const bare = actor ? actorBasename(actor) : "";
307
+ return (actor ? rules[`${actor}/${clip}`] ?? rules[`${actor}_${clip}`] : void 0) ?? (bare && bare !== actor ? rules[`${bare}/${clip}`] ?? rules[`${bare}_${clip}`] : void 0) ?? rules[clip];
308
+ };
309
+ const buckets = /* @__PURE__ */ new Map();
310
+ for (const p of parsed) {
311
+ const bKey = `${p.actor}\u0000${p.clip}`;
312
+ let b = buckets.get(bKey);
313
+ if (!b) {
314
+ b = {
315
+ actor: p.actor,
316
+ clip: p.clip,
317
+ byDir: /* @__PURE__ */ new Map(),
318
+ loopHint: p.loop
319
+ };
320
+ buckets.set(bKey, b);
321
+ } else if (b.loopHint === void 0 && p.loop !== void 0) b.loopHint = p.loop;
322
+ let arr = b.byDir.get(p.dir);
323
+ if (!arr) {
324
+ arr = [];
325
+ b.byDir.set(p.dir, arr);
326
+ }
327
+ arr.push(p);
328
+ }
329
+ const created = [];
330
+ const atlasYaw = tex.atlasYaw ?? 0;
331
+ for (const b of buckets.values()) {
332
+ const rule = resolveRule(b.actor, b.clip);
333
+ const repeat = rule?.repeat !== void 0 ? rule.repeat : options.defaultRepeat !== void 0 ? options.defaultRepeat : b.loopHint !== void 0 ? b.loopHint ? -1 : 0 : LOOP_CLIP_RE.test(b.clip) ? -1 : 0;
334
+ const fps = rule?.frameRate ?? defaultFps;
335
+ const bare = b.actor ? actorBasename(b.actor) : "";
336
+ const canBareAlias = Boolean(bare && bare !== b.actor && (actorsByBase.get(bare)?.size ?? 0) === 1);
337
+ if (b.byDir.size === 1 && b.byDir.has(null)) {
338
+ const seq = b.byDir.get(null).sort((a, c) => a.frameIdx - c.frameIdx);
339
+ const primaryKey = b.actor ? `${b.actor}/${b.clip}` : b.clip;
340
+ const anim = this.create({
341
+ key: primaryKey,
342
+ defaultTextureKey: textureKey,
343
+ frames: seq.map((s) => ({
344
+ key: textureKey,
345
+ frame: s.frameName
346
+ })),
347
+ frameRate: fps,
348
+ duration: rule?.duration,
349
+ repeat,
350
+ yoyo: rule?.yoyo,
351
+ events: rule?.events
352
+ });
353
+ created.push(anim);
354
+ if (b.actor) this.registerAlias(`${b.actor}_${b.clip}`, anim);
355
+ if (canBareAlias) {
356
+ this.registerAlias(`${bare}/${b.clip}`, anim);
357
+ this.registerAlias(`${bare}_${b.clip}`, anim);
358
+ }
359
+ continue;
360
+ }
361
+ const dirEntries = Array.from(b.byDir.entries()).filter(([d]) => d !== null);
362
+ const isCardinal8 = dirEntries.length > 4 && dirEntries.every(([d]) => typeof d === "string" && CARDINAL_DIR_INDEX[d]?.idx8 !== void 0);
363
+ const isCardinal4 = !isCardinal8 && dirEntries.every(([d]) => typeof d === "string" && CARDINAL_DIR_INDEX[d]?.idx4 !== void 0);
364
+ const indexedDirs = dirEntries.map(([d, list]) => {
365
+ const sorted = list.sort((a, c) => a.frameIdx - c.frameIdx);
366
+ if (typeof d === "number") return {
367
+ dirIdx: d,
368
+ label: `d${d}`,
369
+ frames: sorted
370
+ };
371
+ const entry = CARDINAL_DIR_INDEX[d];
372
+ return {
373
+ dirIdx: isCardinal8 ? entry?.idx8 ?? 0 : isCardinal4 ? entry?.idx4 ?? 0 : 0,
374
+ label: String(d),
375
+ frames: sorted
376
+ };
377
+ });
378
+ indexedDirs.sort((a, c) => a.dirIdx - c.dirIdx);
379
+ const dirClips = [];
380
+ for (const item of indexedDirs) {
381
+ const prefixSlash = b.actor ? `${b.actor}/${b.clip}` : b.clip;
382
+ const prefixUnder = b.actor ? `${b.actor}_${b.clip}` : b.clip;
383
+ const primaryKey = `${prefixSlash}/d${item.dirIdx}`;
384
+ const anim = this.create({
385
+ key: primaryKey,
386
+ defaultTextureKey: textureKey,
387
+ frames: item.frames.map((s) => ({
388
+ key: textureKey,
389
+ frame: s.frameName
390
+ })),
391
+ frameRate: fps,
392
+ duration: rule?.duration,
393
+ repeat,
394
+ yoyo: rule?.yoyo,
395
+ events: rule?.events
396
+ });
397
+ created.push(anim);
398
+ dirClips.push(anim);
399
+ this.registerAlias(`${prefixSlash}/${item.dirIdx}`, anim);
400
+ this.registerAlias(`${prefixUnder}_${item.dirIdx}`, anim);
401
+ if (item.label !== `d${item.dirIdx}`) {
402
+ this.registerAlias(`${prefixSlash}/${item.label}`, anim);
403
+ this.registerAlias(`${prefixUnder}_${item.label}`, anim);
404
+ }
405
+ if (canBareAlias) {
406
+ this.registerAlias(`${bare}/${b.clip}/d${item.dirIdx}`, anim);
407
+ this.registerAlias(`${bare}/${b.clip}/${item.dirIdx}`, anim);
408
+ this.registerAlias(`${bare}_${b.clip}_${item.dirIdx}`, anim);
409
+ }
410
+ }
411
+ if (dirClips.length > 0) {
412
+ const baseSlash = b.actor ? `${b.actor}/${b.clip}` : b.clip;
413
+ const baseUnder = b.actor ? `${b.actor}_${b.clip}` : b.clip;
414
+ const aliases = [baseUnder];
415
+ if (canBareAlias) aliases.push(`${bare}/${b.clip}`, `${bare}_${b.clip}`);
416
+ this.registerAlias(baseSlash, dirClips[0]);
417
+ this.registerAlias(baseUnder, dirClips[0]);
418
+ if (canBareAlias) {
419
+ this.registerAlias(`${bare}/${b.clip}`, dirClips[0]);
420
+ this.registerAlias(`${bare}_${b.clip}`, dirClips[0]);
421
+ }
422
+ this.registerDirectionalGroup({
423
+ baseKey: baseSlash,
424
+ actor: b.actor,
425
+ clip: b.clip,
426
+ textureKey,
427
+ dirClips,
428
+ directions: dirClips.length,
429
+ atlasYaw
430
+ }, aliases);
431
+ }
432
+ }
433
+ return created;
434
+ }
435
+ };
436
+ export { AnimationManager };