@lubomirklimes/character-runtime 0.0.0-stage → 0.1.0-preview.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +89 -2
  3. package/dist/acs/acs15.d.ts +9 -0
  4. package/dist/acs/acs15.js +382 -0
  5. package/dist/acs/acs2-reader.d.ts +2 -0
  6. package/dist/acs/acs2-reader.js +277 -0
  7. package/dist/acs/binary.d.ts +1 -0
  8. package/dist/acs/binary.js +107 -0
  9. package/dist/acs/compound-file.d.ts +1 -0
  10. package/dist/acs/compound-file.js +326 -0
  11. package/dist/acs/document.d.ts +33 -0
  12. package/dist/acs/document.js +99 -0
  13. package/dist/acs/errors.d.ts +28 -0
  14. package/dist/acs/errors.js +41 -0
  15. package/dist/acs/image.d.ts +30 -0
  16. package/dist/acs/image.js +113 -0
  17. package/dist/acs/index.d.ts +11 -0
  18. package/dist/acs/index.js +10 -0
  19. package/dist/acs/lz.d.ts +7 -0
  20. package/dist/acs/lz.js +102 -0
  21. package/dist/acs/metadata.d.ts +14 -0
  22. package/dist/acs/metadata.js +126 -0
  23. package/dist/acs/model.d.ts +130 -0
  24. package/dist/acs/model.js +12 -0
  25. package/dist/acs/mouth.d.ts +37 -0
  26. package/dist/acs/mouth.js +43 -0
  27. package/dist/acs/wave.d.ts +53 -0
  28. package/dist/acs/wave.js +422 -0
  29. package/dist/browser/animation-frame-clock.d.ts +18 -0
  30. package/dist/browser/animation-frame-clock.js +42 -0
  31. package/dist/browser/canvas-renderer.d.ts +50 -0
  32. package/dist/browser/canvas-renderer.js +145 -0
  33. package/dist/browser/host.d.ts +84 -0
  34. package/dist/browser/host.js +206 -0
  35. package/dist/browser/index.d.ts +6 -0
  36. package/dist/browser/index.js +8 -0
  37. package/dist/browser/web-audio.d.ts +48 -0
  38. package/dist/browser/web-audio.js +205 -0
  39. package/dist/browser/web-speech.d.ts +131 -0
  40. package/dist/browser/web-speech.js +302 -0
  41. package/dist/core/activities.d.ts +10 -0
  42. package/dist/core/activities.js +479 -0
  43. package/dist/core/agent.d.ts +263 -0
  44. package/dist/core/agent.js +764 -0
  45. package/dist/core/audio.d.ts +17 -0
  46. package/dist/core/audio.js +174 -0
  47. package/dist/core/balloon.d.ts +43 -0
  48. package/dist/core/balloon.js +94 -0
  49. package/dist/core/clock.d.ts +32 -0
  50. package/dist/core/clock.js +51 -0
  51. package/dist/core/compositor.d.ts +22 -0
  52. package/dist/core/compositor.js +67 -0
  53. package/dist/core/events.d.ts +131 -0
  54. package/dist/core/events.js +1 -0
  55. package/dist/core/host.d.ts +29 -0
  56. package/dist/core/host.js +77 -0
  57. package/dist/core/index.d.ts +16 -0
  58. package/dist/core/index.js +13 -0
  59. package/dist/core/lipsync.d.ts +41 -0
  60. package/dist/core/lipsync.js +209 -0
  61. package/dist/core/random.d.ts +52 -0
  62. package/dist/core/random.js +105 -0
  63. package/dist/core/request.d.ts +68 -0
  64. package/dist/core/request.js +131 -0
  65. package/dist/core/resources.d.ts +70 -0
  66. package/dist/core/resources.js +243 -0
  67. package/dist/core/scheduler.d.ts +25 -0
  68. package/dist/core/scheduler.js +766 -0
  69. package/dist/core/source.d.ts +21 -0
  70. package/dist/core/source.js +54 -0
  71. package/dist/core/speech.d.ts +91 -0
  72. package/dist/core/speech.js +86 -0
  73. package/dist/core/text.d.ts +38 -0
  74. package/dist/core/text.js +97 -0
  75. package/dist/index.d.ts +2 -0
  76. package/dist/index.js +4 -0
  77. package/package.json +68 -4
@@ -0,0 +1,766 @@
1
+ import { foldCase } from '../acs/binary.js';
2
+ /** Every request kind. */
3
+ export const ALL_REQUEST_KINDS = ['play', 'state', 'show', 'hide', 'move', 'gesture', 'speak', 'think', 'wait', 'idle'];
4
+ /** The kinds `stopAll()` stops by default: everything except visibility transitions. */
5
+ export const STOP_ALL_DEFAULT_KINDS = ALL_REQUEST_KINDS.filter((k) => k !== 'show' && k !== 'hide');
6
+ /** Portable failure codes of requests (Runtime.md §4.2). */
7
+ export const RequestFailureCode = {
8
+ unknownAnimation: 'unknown-animation',
9
+ unavailableAnimation: 'unavailable-animation',
10
+ invalidAnimation: 'invalid-animation',
11
+ unknownState: 'unknown-state',
12
+ stateUnusable: 'state-unusable',
13
+ resource: 'resource',
14
+ queueLimit: 'queue-limit',
15
+ updateLimit: 'update-limit',
16
+ transitionLimit: 'transition-limit',
17
+ effectDuration: 'effect-duration',
18
+ randomSample: 'random-sample',
19
+ refused: 'refused',
20
+ };
21
+ /** Bound of one random exit path in transitions. */
22
+ const EXIT_PATH_LIMIT = 256;
23
+ const UPDATE_STEP_LIMIT = 2048;
24
+ const EVENT_LIMIT = 8192;
25
+ const HISTORY_LIMIT = 127;
26
+ /** @internal */
27
+ export class AnimationScheduler {
28
+ random;
29
+ unavailable;
30
+ queueLimit;
31
+ transitionLimit;
32
+ animations;
33
+ names = new Map();
34
+ queue = [];
35
+ requests = new Map();
36
+ plans = new Map();
37
+ events = [];
38
+ serial = 0;
39
+ active = 0;
40
+ destination = -1;
41
+ animation = -1;
42
+ frame = -1;
43
+ previousAnimation = -1;
44
+ previousFrame = -1;
45
+ lastTimed = -1;
46
+ transitions = 0;
47
+ anchor = 0;
48
+ offset = 0;
49
+ clock = 0;
50
+ pausedAt = 0;
51
+ idleSince = 0;
52
+ lastEmitted = 0;
53
+ audioUntil = 0;
54
+ silentExit = false;
55
+ pendingExit = false;
56
+ startedFrom = { animation: -1, frame: -1, exit: false };
57
+ presentedOwn = false;
58
+ exitSteps = 0;
59
+ exitVisited = new Set();
60
+ presentedAnimation = -1;
61
+ presentedFrame = -1;
62
+ eventAnimation = -1;
63
+ eventFrame = -1;
64
+ activePlan = null;
65
+ activityBegun = false;
66
+ activityDone = false;
67
+ released = false;
68
+ holding = false;
69
+ returning = false;
70
+ exitPath = false;
71
+ entered = false;
72
+ haveClock = false;
73
+ paused = false;
74
+ effectDurationMs = null;
75
+ requestChanged = null;
76
+ prepareAnimation = null;
77
+ idle = null;
78
+ constructor(source, random, unavailable, queueLimit = 32, transitionLimit = 100_000) {
79
+ this.random = random;
80
+ this.unavailable = unavailable;
81
+ this.queueLimit = queueLimit;
82
+ this.transitionLimit = transitionLimit;
83
+ this.animations = source;
84
+ source.forEach((a, i) => {
85
+ const key = foldCase(a.name);
86
+ if (this.names.has(key))
87
+ throw new Error('Ambiguous animation name: ' + a.name);
88
+ this.names.set(key, i);
89
+ });
90
+ }
91
+ get deadline() {
92
+ return this.anchor + this.offset;
93
+ }
94
+ set deadline(value) {
95
+ this.anchor = value;
96
+ this.offset = 0;
97
+ }
98
+ get isRunning() {
99
+ return this.active !== 0;
100
+ }
101
+ get activeRequestId() {
102
+ return this.active;
103
+ }
104
+ get presentedAnimationIndex() {
105
+ return this.presentedAnimation;
106
+ }
107
+ get presentedFrameIndex() {
108
+ return this.presentedFrame;
109
+ }
110
+ get queuedIds() {
111
+ return [...this.queue];
112
+ }
113
+ get clockMs() {
114
+ return this.clock;
115
+ }
116
+ get pendingEventCount() {
117
+ return this.events.length;
118
+ }
119
+ indexOf(name) {
120
+ return this.names.get(foldCase(name)) ?? -1;
121
+ }
122
+ find(id) {
123
+ return this.requests.get(id) ?? null;
124
+ }
125
+ planOf(id) {
126
+ return this.plans.get(id) ?? null;
127
+ }
128
+ observe(now) {
129
+ if (!Number.isFinite(now) || now < 0 || (this.haveClock && now < this.clock))
130
+ throw new RangeError('Supply a finite monotonic timestamp.');
131
+ this.clock = now;
132
+ this.haveClock = true;
133
+ }
134
+ emit(time, kind, detail = '', a = -1, f = -1, id) {
135
+ if (this.events.length >= EVENT_LIMIT)
136
+ throw new Error('Event buffer full: drain events between operations.');
137
+ this.events.push({ timeMs: time, requestId: id ?? this.active, kind, animation: a, frame: f, detail });
138
+ this.lastEmitted = Math.max(this.lastEmitted, time);
139
+ }
140
+ changed(record) {
141
+ this.requestChanged?.(record);
142
+ }
143
+ end(id, status, reason, time, detail) {
144
+ const record = this.requests.get(id);
145
+ record.status = status;
146
+ record.detail = detail;
147
+ record.reason = reason;
148
+ record.endedAtMs = time;
149
+ this.changed(record);
150
+ const plan = this.plans.get(id);
151
+ if (plan) {
152
+ this.plans.delete(id);
153
+ plan.activity?.end(time, status, reason);
154
+ }
155
+ }
156
+ submit(plan, now, interrupt = false) {
157
+ this.update(now);
158
+ if (this.active !== 0 && this.activePlan?.interruptible)
159
+ interrupt = true;
160
+ const id = ++this.serial;
161
+ this.prune();
162
+ const record = {
163
+ id, name: plan.name, kind: plan.kind, stateName: plan.stateName ?? null, queuedAtMs: now, status: 'queued', reason: 'none', detail: '',
164
+ failureCode: '', startedAtMs: null, endedAtMs: null,
165
+ };
166
+ this.requests.set(id, record);
167
+ this.plans.set(id, plan);
168
+ this.changed(record);
169
+ if (plan.kind !== 'idle')
170
+ this.idle?.activity(now);
171
+ if (plan.refusal != null) {
172
+ this.fail(id, now, plan.refusal, plan.refusalCode ?? RequestFailureCode.refused);
173
+ return id;
174
+ }
175
+ if (plan.animation != null) {
176
+ const target = this.indexOf(plan.animation);
177
+ if (target < 0) {
178
+ const why = this.unavailable(plan.animation);
179
+ if (why !== null)
180
+ this.fail(id, now, why, RequestFailureCode.unavailableAnimation);
181
+ else
182
+ this.fail(id, now, 'Unknown animation: ' + plan.animation, RequestFailureCode.unknownAnimation);
183
+ return id;
184
+ }
185
+ const problem = this.validate(target);
186
+ if (problem !== null) {
187
+ this.fail(id, now, problem, RequestFailureCode.invalidAnimation);
188
+ return id;
189
+ }
190
+ }
191
+ if (!interrupt && this.queue.length >= this.queueLimit) {
192
+ this.fail(id, now, 'Queue limit reached.', RequestFailureCode.queueLimit);
193
+ return id;
194
+ }
195
+ let fromAnimation = this.previousAnimation, fromFrame = this.previousFrame, fromExit = this.pendingExit;
196
+ const wasActive = this.isRunning;
197
+ if (interrupt) {
198
+ if (wasActive && !this.holding) {
199
+ this.emitRest(now);
200
+ ({ animation: fromAnimation, frame: fromFrame, exit: fromExit } = this.stopCursor());
201
+ }
202
+ else if (!wasActive)
203
+ fromExit = this.pendingExit;
204
+ this.cancelRequests(now, 'interrupted');
205
+ this.paused = false;
206
+ }
207
+ this.emit(now, 'queued', '', -1, -1, id);
208
+ if (plan.stateName != null)
209
+ this.emit(now, 'state', plan.stateName, -1, -1, id);
210
+ this.queue.push(id);
211
+ if (!this.isRunning && !this.paused)
212
+ this.startNext(now, fromAnimation, fromFrame, interrupt ? fromExit : this.pendingExit);
213
+ return id;
214
+ }
215
+ /** Keeps a bounded terminal history; queued and running requests are never evicted. */
216
+ prune() {
217
+ const excess = this.requests.size - HISTORY_LIMIT;
218
+ if (excess <= 0)
219
+ return;
220
+ const terminal = [...this.requests.values()].filter((r) => r.status !== 'queued' && r.status !== 'running').sort((a, b) => a.id - b.id);
221
+ for (const r of terminal.slice(0, excess))
222
+ this.requests.delete(r.id);
223
+ }
224
+ /** Null when the animation can be played; otherwise why it is refused (`invalid-animation`). */
225
+ validate(index) {
226
+ const a = this.animations[index];
227
+ if (a.returnType > 2)
228
+ return 'Unsupported return type in ' + a.name;
229
+ if (a.frames.some((f) => f.branches.length > 3))
230
+ return 'Unsupported branch count in ' + a.name;
231
+ return null;
232
+ }
233
+ /** The first frame of the exit path that leaves `frame` of `a`, or −1. */
234
+ exitStart(a, frame) {
235
+ const f = a.frames[frame];
236
+ if (f.exitFrame >= 0)
237
+ return f.exitFrame < a.frames.length ? f.exitFrame : -1;
238
+ if (f.exitFrame !== -2)
239
+ return -1;
240
+ let next = frame + 1;
241
+ if (f.branches.length > 0) {
242
+ const sample = this.random.nextPercent();
243
+ if (sample >= 0 && sample < 100)
244
+ next = branchNext(f.branches, sample, frame, a.frames.length);
245
+ }
246
+ return next < a.frames.length ? next : -1;
247
+ }
248
+ fail(id, now, reason, code) {
249
+ this.requests.get(id).failureCode = code;
250
+ this.end(id, 'failed', 'failed', now, reason);
251
+ this.emit(now, 'failed', reason, -1, -1, id);
252
+ }
253
+ cancelRequests(now, reason) {
254
+ const ids = [this.active, ...this.queue].filter((id) => id !== 0);
255
+ for (const id of ids) {
256
+ this.end(id, 'cancelled', reason, now, 'Cancelled by caller.');
257
+ this.emit(now, 'cancelled', '', -1, -1, id);
258
+ }
259
+ this.queue.length = 0;
260
+ if (this.active !== 0)
261
+ this.idleSince = now;
262
+ this.active = 0;
263
+ this.entered = false;
264
+ this.activePlan = null;
265
+ this.holding = false;
266
+ }
267
+ /** Cancels every request immediately: no exit path, no return; the pending return and the presentation are forgotten. */
268
+ cancelAll(now, reason) {
269
+ this.update(now);
270
+ this.cancelRequests(now, reason);
271
+ this.previousAnimation = this.previousFrame = this.animation = this.frame = this.lastTimed = -1;
272
+ this.paused = false;
273
+ this.pendingExit = false;
274
+ this.idleSince = now;
275
+ this.presentedAnimation = this.presentedFrame = this.eventAnimation = this.eventFrame = -1;
276
+ }
277
+ /** Cancels one request: a queued one is removed, the running one stops gracefully. False when unknown or terminal. */
278
+ cancel(id, now, reason = 'cancelled-by-caller') {
279
+ this.update(now);
280
+ const request = this.requests.get(id);
281
+ if (!request || request.endedAtMs !== null || isTerminal(request.status))
282
+ return false;
283
+ if (request.status === 'queued') {
284
+ const index = this.queue.indexOf(id);
285
+ if (index >= 0)
286
+ this.queue.splice(index, 1);
287
+ this.end(id, 'cancelled', reason, now, 'Cancelled by caller.');
288
+ this.emit(now, 'cancelled', '', -1, -1, id);
289
+ return true;
290
+ }
291
+ this.stopActive(now, reason);
292
+ if (!this.paused && this.queue.length > 0)
293
+ this.startNext(now, this.previousAnimation, this.previousFrame, this.pendingExit);
294
+ return true;
295
+ }
296
+ /** Gracefully cancels queued and running requests of the given kinds. Returns the number cancelled. */
297
+ stopAll(now, kinds) {
298
+ this.update(now);
299
+ let count = 0;
300
+ const keep = [];
301
+ for (const id of this.queue) {
302
+ if (kinds.has(this.requests.get(id).kind)) {
303
+ this.end(id, 'cancelled', 'stopped', now, 'Cancelled by caller.');
304
+ this.emit(now, 'cancelled', '', -1, -1, id);
305
+ count++;
306
+ }
307
+ else
308
+ keep.push(id);
309
+ }
310
+ this.queue.length = 0;
311
+ this.queue.push(...keep);
312
+ if (this.active !== 0 && kinds.has(this.requests.get(this.active).kind)) {
313
+ this.stopActive(now, 'stopped');
314
+ count++;
315
+ }
316
+ if (!this.isRunning && !this.paused && this.queue.length > 0)
317
+ this.startNext(now, this.previousAnimation, this.previousFrame, this.pendingExit);
318
+ return count;
319
+ }
320
+ stopActive(now, reason) {
321
+ const hold = this.holding, id = this.active;
322
+ this.emitRest(now);
323
+ const cursor = hold ? null : this.stopCursor();
324
+ this.end(id, 'cancelled', reason, now, 'Cancelled by caller.');
325
+ this.emit(now, 'cancelled', '', -1, -1, id);
326
+ this.active = 0;
327
+ this.entered = false;
328
+ this.activePlan = null;
329
+ this.holding = false;
330
+ this.idleSince = now;
331
+ // A request without an animation of its own leaves the pending exit cursor / return untouched.
332
+ if (cursor) {
333
+ this.previousAnimation = cursor.animation;
334
+ this.previousFrame = cursor.frame;
335
+ this.pendingExit = cursor.exit;
336
+ }
337
+ }
338
+ /** What a stop or interrupt of the running request leaves pending (Runtime.md §6). */
339
+ stopCursor() {
340
+ if (!this.presentedOwn)
341
+ return this.startedFrom.exit ? { ...this.startedFrom } : { animation: -1, frame: -1, exit: false };
342
+ if (!this.returning && this.animation >= 0 && this.frame >= this.animations[this.animation].frames.length)
343
+ return { animation: this.animation, frame: this.lastTimed, exit: false };
344
+ if (this.lastTimed >= 0)
345
+ return { animation: this.animation, frame: this.lastTimed, exit: true };
346
+ return this.eventFrame >= 0 ? { animation: this.eventAnimation, frame: this.eventFrame, exit: true } : { animation: -1, frame: -1, exit: false };
347
+ }
348
+ /** A zero-duration frame with images that ends the reached path is the resting image (`rest` record). */
349
+ emitRest(time) {
350
+ if (this.presentedFrame >= 0 && (this.presentedAnimation !== this.eventAnimation || this.presentedFrame !== this.eventFrame)) {
351
+ this.emit(time, 'rest', '', this.presentedAnimation, this.presentedFrame);
352
+ this.eventAnimation = this.presentedAnimation;
353
+ this.eventFrame = this.presentedFrame;
354
+ }
355
+ }
356
+ /** Show without a usable Showing animation: nothing is presented until an animation draws. */
357
+ clearPresentation(time) {
358
+ const had = this.presentedFrame >= 0 || this.eventFrame >= 0;
359
+ this.presentedAnimation = this.presentedFrame = this.eventAnimation = this.eventFrame = -1;
360
+ if (had)
361
+ this.emit(time, 'clear');
362
+ }
363
+ /** Fast Show: the resting presentation of an animation without playing it. */
364
+ presentResting(index, time) {
365
+ this.presentedAnimation = this.presentedFrame = -1;
366
+ if (index >= 0 && index < this.animations.length) {
367
+ const frames = this.animations[index].frames;
368
+ for (let i = 0; i < frames.length; i++)
369
+ if (frames[i].durationMs > 0 || frames[i].hasImages) {
370
+ this.presentedAnimation = index;
371
+ this.presentedFrame = i;
372
+ }
373
+ }
374
+ if (this.presentedFrame >= 0)
375
+ this.emitRest(time);
376
+ else
377
+ this.clearPresentation(time);
378
+ }
379
+ pause(now) {
380
+ this.update(now);
381
+ if (!this.paused) {
382
+ this.paused = true;
383
+ this.pausedAt = now;
384
+ this.emit(now, 'paused');
385
+ }
386
+ }
387
+ resume(now) {
388
+ this.observe(now);
389
+ if (this.paused) {
390
+ const delta = now - this.pausedAt;
391
+ if (this.isRunning) {
392
+ this.anchor += delta;
393
+ this.audioUntil += delta;
394
+ this.activePlan?.activity?.shift?.(delta);
395
+ }
396
+ this.idleSince += delta;
397
+ this.paused = false;
398
+ this.emit(now, 'resumed');
399
+ }
400
+ if (!this.isRunning && this.queue.length > 0)
401
+ this.startNext(now, this.previousAnimation, this.previousFrame, this.pendingExit);
402
+ }
403
+ startNext(now, fromAnimation, fromFrame, interrupted) {
404
+ for (;;) {
405
+ if (this.queue.length === 0)
406
+ return;
407
+ this.active = this.queue.shift();
408
+ const plan = this.plans.get(this.active);
409
+ if (plan.interruptible && this.queue.length > 0) {
410
+ // Skipped: an interruptible request never delays requests submitted after it.
411
+ const skipped = this.active;
412
+ this.active = 0;
413
+ this.end(skipped, 'cancelled', 'interrupted', now, 'Superseded by a later request.');
414
+ this.emit(now, 'cancelled', '', -1, -1, skipped);
415
+ continue;
416
+ }
417
+ this.startPlan(plan, now, fromAnimation, fromFrame, interrupted);
418
+ return;
419
+ }
420
+ }
421
+ startPlan(plan, now, fromAnimation, fromFrame, interrupted) {
422
+ this.activePlan = plan;
423
+ this.activityBegun = this.activityDone = this.released = this.holding = this.presentedOwn = false;
424
+ this.startedFrom = { animation: fromAnimation, frame: fromFrame, exit: interrupted };
425
+ let target = plan.animation != null ? this.indexOf(plan.animation) : -1;
426
+ this.transitions = 0;
427
+ this.audioUntil = now;
428
+ this.silentExit = interrupted;
429
+ const record = this.requests.get(this.active);
430
+ record.status = 'running';
431
+ record.startedAtMs = now;
432
+ this.changed(record);
433
+ let refusal = null, refusalCode = null;
434
+ if (plan.animation == null && plan.chooseAnimation) {
435
+ const chosen = plan.chooseAnimation({ timeMs: now, shownAnimation: this.presentedAnimation, shownFrame: this.presentedFrame });
436
+ if (chosen !== null) {
437
+ target = this.indexOf(chosen);
438
+ if (target < 0) {
439
+ const why = this.unavailable(chosen);
440
+ refusal = why ?? 'Unknown animation: ' + chosen;
441
+ refusalCode = why !== null ? RequestFailureCode.unavailableAnimation : RequestFailureCode.unknownAnimation;
442
+ }
443
+ else {
444
+ refusal = this.validate(target);
445
+ if (refusal !== null)
446
+ refusalCode = RequestFailureCode.invalidAnimation;
447
+ }
448
+ }
449
+ }
450
+ if (refusal === null && target >= 0) {
451
+ refusal = this.prepareAnimation?.(target) ?? null;
452
+ refusalCode = RequestFailureCode.resource;
453
+ }
454
+ this.destination = target;
455
+ this.emit(now, 'started', '', this.destination);
456
+ if (refusal !== null) {
457
+ this.failActive(now, refusal, refusalCode ?? RequestFailureCode.refused);
458
+ return;
459
+ }
460
+ if (target < 0) {
461
+ // No animation of its own: keep showing the current frame and keep the pending return for the next animation request.
462
+ this.previousAnimation = fromAnimation;
463
+ this.previousFrame = fromFrame;
464
+ this.pendingExit = interrupted;
465
+ this.holding = true;
466
+ this.deadline = now;
467
+ this.beginActivity(now);
468
+ return;
469
+ }
470
+ this.previousAnimation = this.previousFrame = -1;
471
+ this.pendingExit = false;
472
+ let returnAnimation = -1, returnFrame = -1, useExit = false;
473
+ if (fromAnimation >= 0) {
474
+ const prior = this.animations[fromAnimation];
475
+ // Exit paths follow a stop or interrupt only; return type 0 plays its named return after natural completion.
476
+ if (interrupted && fromFrame >= 0) {
477
+ returnFrame = this.exitStart(prior, fromFrame);
478
+ useExit = returnFrame >= 0;
479
+ returnAnimation = useExit ? fromAnimation : -1;
480
+ }
481
+ else if (prior.returnType === 0) {
482
+ returnAnimation = this.indexOf(prior.returnName);
483
+ if (returnAnimation >= 0)
484
+ returnFrame = 0;
485
+ else {
486
+ const why = this.unavailable(prior.returnName);
487
+ this.emit(now, 'return-skipped', why !== null ? `Named return ${prior.returnName} of ${prior.name} is unavailable: ${why}`
488
+ : `Named return ${prior.returnName} of ${prior.name} does not exist.`, fromAnimation);
489
+ }
490
+ }
491
+ }
492
+ let returnProblem = returnAnimation >= 0 ? this.validate(returnAnimation) : null;
493
+ if (returnProblem === null && returnAnimation >= 0)
494
+ returnProblem = this.prepareAnimation?.(returnAnimation) ?? null;
495
+ if (returnProblem !== null) {
496
+ // A return that cannot play is skipped, never a reason to fail the request that follows it.
497
+ this.emit(now, 'return-skipped', returnProblem, returnAnimation);
498
+ returnAnimation = -1;
499
+ }
500
+ this.returning = returnAnimation >= 0;
501
+ this.exitPath = this.returning && useExit;
502
+ this.exitSteps = 0;
503
+ this.exitVisited.clear();
504
+ if (this.exitPath)
505
+ this.exitVisited.add(returnFrame);
506
+ this.begin(this.returning ? returnAnimation : this.destination, this.returning ? returnFrame : 0, now, this.returning ? (useExit ? (interrupted ? 'interrupt-exit' : 'exit-return') : 'named-return') : 'animation');
507
+ }
508
+ begin(a, f, time, cause) {
509
+ this.animation = a;
510
+ this.frame = f;
511
+ this.lastTimed = -1;
512
+ this.deadline = time;
513
+ this.entered = false;
514
+ this.emit(time, 'transition', cause, a, f);
515
+ if (cause === 'animation')
516
+ this.beginActivity(time);
517
+ }
518
+ beginActivity(time) {
519
+ if (this.activityBegun || this.activePlan === null)
520
+ return;
521
+ this.activityBegun = true;
522
+ this.activePlan.activity?.begin(time);
523
+ if (!this.activePlan?.activity)
524
+ this.activityDone = true;
525
+ }
526
+ failActive(time, reason, code) {
527
+ this.fail(this.active, time, reason, code);
528
+ this.active = 0;
529
+ this.activePlan = null;
530
+ this.holding = false;
531
+ this.idleSince = time;
532
+ // A request that failed before it reached a frame of its own leaves the inherited cursor pending.
533
+ if (this.presentedOwn) {
534
+ this.previousAnimation = this.previousFrame = -1;
535
+ this.pendingExit = false;
536
+ }
537
+ else {
538
+ this.previousAnimation = this.startedFrom.animation;
539
+ this.previousFrame = this.startedFrom.frame;
540
+ this.pendingExit = this.startedFrom.exit;
541
+ }
542
+ }
543
+ complete(time, a) {
544
+ this.emitRest(time);
545
+ this.end(this.active, 'completed', 'completed', time, this.activePlan?.activity?.note ?? '');
546
+ this.emit(time, 'completed', '', a);
547
+ this.active = 0;
548
+ this.activePlan = null;
549
+ this.holding = false;
550
+ this.idleSince = time;
551
+ }
552
+ /** Leaves a held animation when its activity finished: through the current frame's explicit exit target, or at once. */
553
+ release(time) {
554
+ this.released = true;
555
+ this.activityDone = true;
556
+ const a = this.animations[this.animation];
557
+ const from = this.lastTimed >= 0 ? this.lastTimed : Math.min(this.frame, a.frames.length - 1);
558
+ const e = from >= 0 && from < a.frames.length ? a.frames[from].exitFrame : -1;
559
+ const exit = e >= 0 && e < a.frames.length ? e : -1;
560
+ this.deadline = time;
561
+ this.entered = false;
562
+ if (exit >= 0) {
563
+ this.frame = exit;
564
+ this.exitPath = true;
565
+ this.exitSteps = 0;
566
+ this.exitVisited.clear();
567
+ this.exitVisited.add(exit);
568
+ this.emit(time, 'transition', 'release-exit', this.animation, this.frame);
569
+ }
570
+ else
571
+ this.frame = a.frames.length;
572
+ }
573
+ update(now) {
574
+ const floor = this.haveClock ? Math.max(this.clock, this.lastEmitted) : now;
575
+ this.observe(now);
576
+ if (this.paused)
577
+ return;
578
+ const steps = { count: 0 };
579
+ for (;;) {
580
+ if (this.run(now, floor, steps) || this.paused || this.isRunning || this.queue.length > 0)
581
+ break;
582
+ const idle = this.idle?.next(this.idleSince, now);
583
+ if (!idle)
584
+ break;
585
+ const due = Math.max(idle.due, Math.max(this.idleSince, this.lastEmitted));
586
+ if (due > now)
587
+ break;
588
+ const id = ++this.serial;
589
+ this.prune();
590
+ const record = {
591
+ id, name: idle.plan.name, kind: 'idle', stateName: idle.plan.stateName ?? null, queuedAtMs: due, status: 'queued', reason: 'none',
592
+ detail: '', failureCode: '', startedAtMs: null, endedAtMs: null,
593
+ };
594
+ this.requests.set(id, record);
595
+ this.plans.set(id, idle.plan);
596
+ this.changed(record);
597
+ this.emit(due, 'queued', '', -1, -1, id);
598
+ if (idle.plan.stateName != null)
599
+ this.emit(due, 'state', idle.plan.stateName, -1, -1, id);
600
+ this.queue.push(id);
601
+ this.startNext(due, this.previousAnimation, this.previousFrame, this.pendingExit);
602
+ if (++steps.count > UPDATE_STEP_LIMIT)
603
+ break;
604
+ }
605
+ }
606
+ /** Releases a held animation whose activity finished no later than the current deadline. */
607
+ releaseDue(a, now, floor) {
608
+ const plan = this.activePlan;
609
+ if (this.returning || this.released || !this.activityBegun || !plan?.holdUntilActivityDone || !plan.activity || this.frame >= a.frames.length)
610
+ return false;
611
+ const r = plan.activity.poll(now, floor);
612
+ if (r === null || r > this.deadline)
613
+ return false;
614
+ this.release(Math.max(r, this.lastEmitted));
615
+ return true;
616
+ }
617
+ /** The bounded update pump. Returns true when it stopped while a request waits for a later time. */
618
+ run(now, floor, steps) {
619
+ while (this.isRunning || this.queue.length > 0) {
620
+ if (++steps.count > UPDATE_STEP_LIMIT) {
621
+ if (this.isRunning)
622
+ this.failActive(now, 'Per-update transition limit.', RequestFailureCode.updateLimit);
623
+ this.cancelRequests(now, 'failed');
624
+ break;
625
+ }
626
+ if (!this.isRunning) {
627
+ this.startNext(this.deadline, this.previousAnimation, this.previousFrame, this.pendingExit);
628
+ if (!this.isRunning)
629
+ continue;
630
+ }
631
+ if (this.holding) {
632
+ const activity = this.activePlan?.activity;
633
+ const done = activity ? activity.poll(now, floor) : this.deadline;
634
+ if (done === null)
635
+ return true;
636
+ const end = Math.max(done, this.deadline);
637
+ if (end > now) {
638
+ this.deadline = end;
639
+ return true;
640
+ }
641
+ this.activityDone = true;
642
+ this.complete(end, -1);
643
+ this.deadline = end;
644
+ continue;
645
+ }
646
+ const a = this.animations[this.animation];
647
+ if (this.releaseDue(a, now, floor))
648
+ continue;
649
+ if (this.deadline > now)
650
+ return true;
651
+ const time = this.deadline;
652
+ if (!this.entered) {
653
+ if (++this.transitions > this.transitionLimit) {
654
+ this.failActive(time, 'Total transition limit.', RequestFailureCode.transitionLimit);
655
+ continue;
656
+ }
657
+ if (this.frame >= a.frames.length) {
658
+ if (this.returning) {
659
+ this.returning = this.exitPath = false;
660
+ this.begin(this.destination, 0, time, 'animation');
661
+ continue;
662
+ }
663
+ const activity = this.activePlan?.activity;
664
+ if (!this.activityDone && this.activityBegun && activity) {
665
+ const finished = activity.poll(now, floor);
666
+ if (finished === null)
667
+ return true;
668
+ if (finished > time) {
669
+ this.deadline = finished;
670
+ continue;
671
+ }
672
+ this.activityDone = true;
673
+ }
674
+ if (this.audioUntil > time) {
675
+ this.deadline = this.audioUntil;
676
+ continue;
677
+ }
678
+ this.previousAnimation = this.animation;
679
+ this.previousFrame = this.lastTimed;
680
+ this.complete(time, this.animation);
681
+ continue;
682
+ }
683
+ const f = a.frames[this.frame];
684
+ this.entered = true;
685
+ this.presentedOwn = true;
686
+ if (f.durationMs > 0 || f.hasImages) {
687
+ this.presentedAnimation = this.animation;
688
+ this.presentedFrame = this.frame;
689
+ }
690
+ if (f.durationMs > 0) {
691
+ this.lastTimed = this.frame;
692
+ this.eventAnimation = this.animation;
693
+ this.eventFrame = this.frame;
694
+ this.emit(time, 'frame', this.returning ? 'return' : 'animation', this.animation, this.frame);
695
+ if (!(this.returning && this.silentExit) && this.effectDurationMs) {
696
+ const duration = this.effectDurationMs(this.animation, this.frame);
697
+ if (!Number.isFinite(duration) || duration < 0 || duration > 60_000) {
698
+ this.failActive(time, 'Invalid effect duration.', RequestFailureCode.effectDuration);
699
+ continue;
700
+ }
701
+ this.audioUntil = Math.max(this.audioUntil, time + duration);
702
+ }
703
+ }
704
+ else
705
+ this.emit(time, 'control', this.returning ? 'return' : 'animation', this.animation, this.frame);
706
+ this.offset += f.durationMs;
707
+ if (this.deadline > now)
708
+ return true;
709
+ if (this.releaseDue(a, now, floor))
710
+ continue;
711
+ }
712
+ const current = a.frames[this.frame];
713
+ let next = this.frame + 1, drew = false;
714
+ if (this.exitPath && current.exitFrame >= 0 && current.exitFrame < a.frames.length)
715
+ next = current.exitFrame;
716
+ else if (this.exitPath && current.exitFrame !== -2)
717
+ next = a.frames.length;
718
+ else if (current.branches.length > 0) {
719
+ const sample = this.random.nextPercent();
720
+ drew = true;
721
+ if (!(sample >= 0 && sample < 100)) {
722
+ this.failActive(time, 'Invalid random sample.', RequestFailureCode.randomSample);
723
+ continue;
724
+ }
725
+ next = branchNext(current.branches, sample, this.frame, a.frames.length);
726
+ }
727
+ if (this.exitPath && next < a.frames.length) {
728
+ if (drew)
729
+ this.exitVisited.clear();
730
+ const repeated = this.exitVisited.has(next);
731
+ this.exitVisited.add(next);
732
+ if (repeated || ++this.exitSteps > EXIT_PATH_LIMIT) {
733
+ // The native exit-cycle hang is never reproduced: the path ends here and is reported.
734
+ this.emit(time, 'exit-cycle', `Exit path of ${a.name} ended at frame ${this.frame + 1}.`, this.animation, this.frame);
735
+ next = a.frames.length;
736
+ }
737
+ }
738
+ this.frame = next;
739
+ this.entered = false;
740
+ }
741
+ return false;
742
+ }
743
+ /** Records emitted since the last drain. */
744
+ drainEvents() {
745
+ const result = this.events;
746
+ this.events = [];
747
+ return result;
748
+ }
749
+ }
750
+ function isTerminal(status) {
751
+ return status === 'completed' || status === 'cancelled' || status === 'failed';
752
+ }
753
+ /**
754
+ * The branch rule (Runtime.md §5): the first record whose interval contains the sample wins; a winner outside the animation, or no
755
+ * winner, continues with the next frame.
756
+ * @internal
757
+ */
758
+ export function branchNext(branches, sample, frame, frameCount) {
759
+ let s = sample;
760
+ for (const b of branches) {
761
+ if (s < b.percent)
762
+ return b.target >= 0 && b.target < frameCount ? b.target : frame + 1;
763
+ s -= b.percent;
764
+ }
765
+ return frame + 1;
766
+ }