@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,764 @@
1
+ import { DisposedError, InvalidArgumentError, CharacterRuntimeError } from '../acs/errors.js';
2
+ import { CharacterStyle } from '../acs/model.js';
3
+ import { checkMouth } from '../acs/mouth.js';
4
+ import { IdleBehavior, MoveActivity, SpeakActivity, VisibilityActivity, WaitActivity } from './activities.js';
5
+ import { AgentAudio, NULL_OUTPUT } from './audio.js';
6
+ import { BalloonController, balloonStyleFor } from './balloon.js';
7
+ import { SystemClock } from './clock.js';
8
+ import { AgentRandom } from './random.js';
9
+ import { AgentRequest } from './request.js';
10
+ import { CharacterResources } from './resources.js';
11
+ import { AnimationScheduler, ALL_REQUEST_KINDS, RequestFailureCode, STOP_ALL_DEFAULT_KINDS, } from './scheduler.js';
12
+ import { selectVoice } from './speech.js';
13
+ import { foldCase } from '../acs/binary.js';
14
+ let nextAgentId = 0;
15
+ function playbackAnimations(character) {
16
+ if (character.animations.some((a) => a.trailingBytes.length > 0))
17
+ throw new CharacterRuntimeError('not-supported', 'Request playback refuses uninterpreted animation tails.');
18
+ return character.animations.map((a) => ({
19
+ name: a.name, returnType: a.returnType, returnName: a.returnName,
20
+ frames: a.frames.map((f) => ({ durationMs: f.durationTicks * 10, exitFrame: f.exitFrame, branches: f.branches, hasImages: f.layers.length > 0 })),
21
+ }));
22
+ }
23
+ /**
24
+ * One running character (Runtime.md): the request queue, random stream, visibility, position, scale, idle, speech, lip-sync, word balloon
25
+ * and typed events. It has no timers or threads: a host calls {@link advance} from its render loop and presents {@link currentFrame}.
26
+ */
27
+ export class CharacterAgent {
28
+ source;
29
+ id;
30
+ name;
31
+ clock;
32
+ resources;
33
+ /** @internal */
34
+ scheduler;
35
+ /** @internal */
36
+ balloonController;
37
+ /** @internal */
38
+ move = null;
39
+ /** @internal */
40
+ speech = null;
41
+ ownsResources;
42
+ audio;
43
+ idle;
44
+ pending = [];
45
+ listeners = new Set();
46
+ pacing;
47
+ maxTextLength;
48
+ movementSpeed;
49
+ maxMoveMs;
50
+ speechRate;
51
+ hasAudioOption;
52
+ createSpeechOutput;
53
+ speechOutput = null;
54
+ visibilityValue;
55
+ positionValue;
56
+ scaleValue;
57
+ now = 0;
58
+ pausedAt = 0;
59
+ disposed = false;
60
+ paused = false;
61
+ frame;
62
+ provider;
63
+ decision = null;
64
+ voice;
65
+ speechEnabledValue;
66
+ balloonEnabledValue;
67
+ speechAudioStatusValue = 'No speech audio yet.';
68
+ animationNames = null;
69
+ constructor(source, options = {}) {
70
+ this.source = source;
71
+ const scale = options.scale ?? 1;
72
+ if (!Number.isFinite(scale) || scale <= 0)
73
+ throw new InvalidArgumentError('Scale must be positive.');
74
+ this.clock = options.clock ?? new SystemClock();
75
+ const character = source.character;
76
+ this.name = options.name ?? character.names[0]?.name ?? source.name;
77
+ const shared = options.resources instanceof CharacterResources ? options.resources : null;
78
+ if (shared && shared.source !== source)
79
+ throw new InvalidArgumentError('The resources belong to another source.');
80
+ this.ownsResources = !shared;
81
+ this.resources = shared ?? new CharacterResources(source, options.resources);
82
+ this.audio = new AgentAudio(source, options.audio ?? (() => NULL_OUTPUT), options.soundEffects ?? true, options.audioLimits);
83
+ let animations;
84
+ try {
85
+ animations = playbackAnimations(character);
86
+ this.scheduler = new AnimationScheduler(animations, options.random ?? new AgentRandom(options.seed ?? 0), (name) => this.unavailableReason(name));
87
+ }
88
+ catch (e) {
89
+ if (e instanceof CharacterRuntimeError)
90
+ throw e;
91
+ throw new InvalidArgumentError(e.message);
92
+ }
93
+ this.id = ++nextAgentId;
94
+ this.scheduler.effectDurationMs = (a, f) => this.audio.effectDuration(a, f);
95
+ this.scheduler.requestChanged = (record) => this.onRequestChanged(record);
96
+ this.scheduler.prepareAnimation = (index) => this.prepareForStart(index);
97
+ this.balloonController = new BalloonController((time, state) => this.raise({ type: 'balloon', timeMs: time, balloon: state }));
98
+ const idle = options.idle;
99
+ this.idle = new IdleBehavior(this, typeof idle === 'object' ? { enabled: true, ...idle } : { enabled: idle ?? true });
100
+ this.scheduler.idle = this.idle;
101
+ this.visibilityValue = options.visibility ?? 'hidden';
102
+ this.positionValue = options.position ?? { x: 0, y: 0 };
103
+ this.scaleValue = scale;
104
+ this.provider = options.speech ?? null;
105
+ this.voice = options.voiceId ?? null;
106
+ this.speechEnabledValue = options.speechEnabled ?? null;
107
+ this.speechRate = options.speechRatePercent ?? 100;
108
+ this.balloonEnabledValue = options.balloonEnabled ?? (character.style & CharacterStyle.balloonOn) !== 0;
109
+ const b = options.balloon ?? {};
110
+ this.pacing = { characterMs: b.characterMs ?? 45, wordMs: b.wordMs ?? 120, minimumMs: b.minimumMs ?? 1200, hideDelayMs: b.hideDelayMs ?? 1500 };
111
+ this.maxTextLength = b.maxTextLength ?? 4096;
112
+ this.movementSpeed = options.movement?.speed ?? 400;
113
+ this.maxMoveMs = options.movement?.maxDurationMs ?? 60_000;
114
+ this.hasAudioOption = !!(options.speechAudio ?? options.audio);
115
+ this.createSpeechOutput = options.speechAudio ?? options.audio ?? null;
116
+ this.now = this.clock.nowMs;
117
+ this.frame = this.computeFrame();
118
+ }
119
+ /** The character this agent plays. */
120
+ get character() {
121
+ return this.source.character;
122
+ }
123
+ /** Animation names in file order. */
124
+ get animations() {
125
+ return (this.animationNames ??= this.character.animations.map((a) => a.name));
126
+ }
127
+ /** State names in file order. */
128
+ get states() {
129
+ return [...this.character.states.keys()];
130
+ }
131
+ get visibility() {
132
+ return this.visibilityValue;
133
+ }
134
+ get position() {
135
+ return this.move?.positionAt(this.shown) ?? this.positionValue;
136
+ }
137
+ get scale() {
138
+ return this.scaleValue;
139
+ }
140
+ set scale(value) {
141
+ if (!Number.isFinite(value) || value <= 0)
142
+ throw new InvalidArgumentError('Scale must be positive.');
143
+ if (this.scaleValue === value)
144
+ return;
145
+ this.scaleValue = value;
146
+ this.raise({ type: 'scale', timeMs: this.now, scale: value });
147
+ this.updateFrame();
148
+ }
149
+ get isPaused() {
150
+ return this.paused;
151
+ }
152
+ get isDisposed() {
153
+ return this.disposed;
154
+ }
155
+ get balloon() {
156
+ return this.balloonController.state;
157
+ }
158
+ /** What to present now. */
159
+ get currentFrame() {
160
+ return this.frame;
161
+ }
162
+ /** The level the next idle animation uses (1–3), or 0 when the character has no idle states. */
163
+ get idleLevel() {
164
+ return this.idle.level;
165
+ }
166
+ /** The running request (also idle requests the runtime created). */
167
+ get activeRequest() {
168
+ return this.scheduler.planOf(this.scheduler.activeRequestId)?.tag ?? null;
169
+ }
170
+ /** Queued requests in start order. */
171
+ get queuedRequests() {
172
+ return this.scheduler.queuedIds.map((id) => this.scheduler.planOf(id)?.tag).filter((t) => t instanceof AgentRequest);
173
+ }
174
+ /** The speech presented now, or null. */
175
+ get speechState() {
176
+ const state = this.speech?.state(this.shown);
177
+ return state ? (this.paused ? { ...state, mouth: null } : state) : null;
178
+ }
179
+ /** Frame sound effects (session setting). */
180
+ get soundEffects() {
181
+ return this.audio.enabled;
182
+ }
183
+ set soundEffects(value) {
184
+ this.audio.enabled = value;
185
+ }
186
+ get idleEnabled() {
187
+ return this.idle.enabled;
188
+ }
189
+ set idleEnabled(value) {
190
+ this.idle.setEnabled(value, this.now);
191
+ }
192
+ get balloonEnabled() {
193
+ return this.balloonEnabledValue;
194
+ }
195
+ set balloonEnabled(value) {
196
+ this.balloonEnabledValue = value;
197
+ }
198
+ get speechProvider() {
199
+ return this.provider;
200
+ }
201
+ set speechProvider(value) {
202
+ this.provider = value;
203
+ this.decision = null;
204
+ }
205
+ get voiceId() {
206
+ return this.voice;
207
+ }
208
+ set voiceId(value) {
209
+ this.voice = value;
210
+ this.decision = null;
211
+ }
212
+ /** Speak synthesizes audio (null follows the character's Style TTS bit). */
213
+ get speechEnabled() {
214
+ return this.speechEnabledValue;
215
+ }
216
+ set speechEnabled(value) {
217
+ this.speechEnabledValue = value;
218
+ }
219
+ /** Speaking rate in percent for speech synthesized from now on (100 = the voice's normal rate). */
220
+ get speechRatePercent() {
221
+ return this.speechRate;
222
+ }
223
+ set speechRatePercent(value) {
224
+ this.speechRate = checkRate(value);
225
+ }
226
+ /** The voice Speak uses now, and why. */
227
+ get voiceDecision() {
228
+ return this.decide();
229
+ }
230
+ /** What happened to the latest speech audio (diagnostic). */
231
+ get speechAudioStatus() {
232
+ return this.speechAudioStatusValue;
233
+ }
234
+ /** The latest sound-effect status (diagnostic). */
235
+ get soundEffectStatus() {
236
+ return this.audio.status;
237
+ }
238
+ /** Subscribes to every event (raised in time order inside {@link advance}). Returns the unsubscribe function. */
239
+ on(listener) {
240
+ this.listeners.add(listener);
241
+ return () => this.listeners.delete(listener);
242
+ }
243
+ // ---- requests
244
+ /** Plays an animation by name (ignoring case). */
245
+ play(animation, options = {}) {
246
+ requireString(animation, 'animation');
247
+ return this.submit('play', animation, () => ({ kind: 'play', name: animation, animation, refusal: this.checkAnimation(animation), refusalCode: RequestFailureCode.resource }), !!options.interrupt);
248
+ }
249
+ /** Plays one animation of a state, chosen when the request starts. State requests are interruptible. */
250
+ playState(state, options = {}) {
251
+ requireString(state, 'state');
252
+ const key = this.stateKey(state);
253
+ return this.submit('state', state, () => ({
254
+ kind: 'state', name: state, stateName: key ?? state, interruptible: true,
255
+ refusal: key === null ? 'Unknown state: ' + state : this.usableAnimations(key).length === 0 ? `State ${key} has no usable animation.` : null,
256
+ refusalCode: key === null ? RequestFailureCode.unknownState : RequestFailureCode.stateUnusable,
257
+ chooseAnimation: () => this.chooseState(key),
258
+ }), !!options.interrupt);
259
+ }
260
+ /** Shows the character: the Showing state animation (unless `fast` or missing), then visible. */
261
+ show(options = {}) {
262
+ return this.submitVisibility(true, !!options.fast);
263
+ }
264
+ /** Hides the character: the Hiding state animation (unless `fast` or missing), then hidden. */
265
+ hide(options = {}) {
266
+ return this.submitVisibility(false, !!options.fast);
267
+ }
268
+ submitVisibility(show, fast) {
269
+ const activity = new VisibilityActivity(this, show);
270
+ const name = show ? 'Show' : 'Hide';
271
+ return this.submit(show ? 'show' : 'hide', name, () => ({ kind: show ? 'show' : 'hide', name, activity, chooseAnimation: () => activity.choose(fast) }), false);
272
+ }
273
+ /** Moves the top-left corner to (x, y) at `speed` units per second (default the session speed; ≤ 0 moves instantly). */
274
+ moveTo(x, y, options = {}) {
275
+ requireFinite(x, y);
276
+ const speed = options.speed ?? this.movementSpeed;
277
+ if (Number.isNaN(speed))
278
+ throw new InvalidArgumentError('The speed is not a number.');
279
+ const activity = new MoveActivity(this, { x, y }, speed, this.maxMoveMs);
280
+ const name = `MoveTo ${x},${y}`;
281
+ return this.submit('move', name, () => ({ kind: 'move', name, activity, holdUntilActivityDone: true, chooseAnimation: (ctx) => activity.choose(ctx.timeMs) }), false);
282
+ }
283
+ /** Gestures toward (x, y), measured from the character's centre, with the character-relative Gesturing state. */
284
+ gestureAt(x, y) {
285
+ requireFinite(x, y);
286
+ const name = `GestureAt ${x},${y}`;
287
+ return this.submit('gesture', name, () => ({
288
+ kind: 'gesture', name,
289
+ chooseAnimation: (ctx) => {
290
+ const state = this.gestureState({ x, y }, ctx.timeMs);
291
+ return state === null || this.visibilityValue === 'hidden' ? null : this.chooseState(state);
292
+ },
293
+ }), false);
294
+ }
295
+ /** Speaks text: synthesized audio when speech is enabled and a provider is set, lip-sync, the speech balloon and the Speaking state. */
296
+ speak(text, options = {}) {
297
+ const content = typeof text === 'string' ? null : text;
298
+ const value = typeof text === 'string' ? text : text?.text;
299
+ requireString(value, 'text');
300
+ this.checkText(value);
301
+ return this.speakCore(value, content, options, 'speech');
302
+ }
303
+ /** Shows text in a thought balloon (no audio, no lip-sync), paced by reading time. */
304
+ think(text, options = {}) {
305
+ requireString(text, 'text');
306
+ this.checkText(text);
307
+ return this.speakCore(text, null, { interrupt: !!options.interrupt }, 'thought');
308
+ }
309
+ speakCore(text, content, options, kind) {
310
+ const requestKind = kind === 'thought' ? 'think' : 'speak';
311
+ const name = (kind === 'thought' ? 'Think: ' : 'Speak: ') + (text.length > 40 ? text.substring(0, 40) + '…' : text);
312
+ return this.submit(requestKind, name, (handle) => {
313
+ const activity = new SpeakActivity(this, handle, text, kind, content, options.balloon ?? this.balloonEnabledValue, this.pacing);
314
+ if (kind === 'speech' && content === null)
315
+ activity.startSynthesis(this.usesSpeech() ? this.provider : null, this.decide().voice, this.speechRate);
316
+ return {
317
+ kind: requestKind, name, activity, holdUntilActivityDone: true,
318
+ chooseAnimation: (ctx) => {
319
+ if (kind === 'thought' || this.visibilityValue === 'hidden' || this.canSpeakOn(ctx.shownAnimation, ctx.shownFrame))
320
+ return null;
321
+ const s = this.stateKey('Speaking');
322
+ return s === null ? null : this.chooseState(s);
323
+ },
324
+ };
325
+ }, !!options.interrupt);
326
+ }
327
+ /** Holds this agent's queue until `request` (of any agent) is terminal. */
328
+ wait(request) {
329
+ if (!(request instanceof AgentRequest))
330
+ throw new InvalidArgumentError('Wait needs a request handle.');
331
+ const activity = new WaitActivity(request);
332
+ const name = `Wait #${request.id} (${request.agent.name})`;
333
+ return this.submit('wait', name, () => ({ kind: 'wait', name, activity }), false, request);
334
+ }
335
+ /** Cancels one request of this agent. False when it is already terminal. */
336
+ cancel(request) {
337
+ if (request.agent !== this)
338
+ throw new InvalidArgumentError('The request belongs to another agent.');
339
+ if (this.disposed || request.id === 0)
340
+ return false;
341
+ const done = this.scheduler.cancel(request.id, this.nowTime());
342
+ this.updateFrame();
343
+ return done;
344
+ }
345
+ /** Gracefully cancels queued and running requests of the given kinds (default: all but show and hide). Returns the count. */
346
+ stopAll(kinds = STOP_ALL_DEFAULT_KINDS) {
347
+ if (this.disposed)
348
+ return 0;
349
+ const set = new Set(kinds === 'all' ? ALL_REQUEST_KINDS : kinds);
350
+ const count = this.scheduler.stopAll(this.nowTime(), set);
351
+ this.updateFrame();
352
+ return count;
353
+ }
354
+ pause() {
355
+ if (this.disposed || this.paused)
356
+ return;
357
+ const t = this.nowTime();
358
+ this.scheduler.pause(t);
359
+ this.paused = true;
360
+ this.pausedAt = t;
361
+ this.speech?.pause();
362
+ this.updateFrame();
363
+ }
364
+ resume() {
365
+ if (this.disposed || !this.paused)
366
+ return;
367
+ const t = this.nowTime();
368
+ this.scheduler.resume(t);
369
+ this.paused = false;
370
+ this.balloonController.shift(t - this.pausedAt);
371
+ this.speech?.resume(t);
372
+ this.updateFrame();
373
+ }
374
+ /** Cancels every request immediately (no exit path, no return), stops speech and sounds and hides the balloon. */
375
+ reset() {
376
+ if (!this.disposed)
377
+ this.resetCore(this.nowTime(), 'cancelled-by-caller');
378
+ }
379
+ resetCore(t, reason) {
380
+ this.now = t;
381
+ this.scheduler.cancelAll(t, reason);
382
+ this.paused = false;
383
+ try {
384
+ this.audio.stop();
385
+ }
386
+ catch {
387
+ // A platform output that cannot stop does not stop a reset.
388
+ }
389
+ this.stopSpeechAudio();
390
+ this.balloonController.hide(t);
391
+ this.updateFrame();
392
+ }
393
+ /** Sets the position immediately (not queued). A running move continues from here to its target. */
394
+ setPosition(x, y) {
395
+ requireFinite(x, y);
396
+ if (this.disposed)
397
+ throw new DisposedError();
398
+ const t = this.nowTime();
399
+ this.positionValue = { x, y };
400
+ this.move?.restart(t, this.positionValue);
401
+ this.raise({ type: 'position', timeMs: t, position: this.positionValue });
402
+ this.updateFrame();
403
+ }
404
+ /** Hides the balloon now. */
405
+ dismissBalloon() {
406
+ if (!this.disposed)
407
+ this.balloonController.hide(this.nowTime());
408
+ }
409
+ // ---- time
410
+ /** Advances the agent to `time` (default: its clock) and returns the events since the previous call, in time order. */
411
+ advance(time = this.clock.nowMs) {
412
+ if (this.disposed)
413
+ return [];
414
+ this.now = Math.max(time, this.scheduler.clockMs);
415
+ this.scheduler.update(this.now);
416
+ const trace = this.scheduler.drainEvents();
417
+ if (trace.length > 0)
418
+ this.audio.process(trace, this.now);
419
+ if (!this.paused) {
420
+ this.speech?.tick(this.now);
421
+ this.balloonController.tick(this.now);
422
+ }
423
+ this.balloonController.move(this.anchor);
424
+ // Causal order: a service event follows the scheduler records emitted before it; then a stable sort by logical time.
425
+ const batch = [];
426
+ let next = 0;
427
+ for (let i = 0; i <= trace.length; i++) {
428
+ while (next < this.pending.length && this.pending[next].position <= i)
429
+ batch.push(this.pending[next++].event);
430
+ if (i < trace.length)
431
+ this.fromTrace(trace[i], batch);
432
+ }
433
+ while (next < this.pending.length)
434
+ batch.push(this.pending[next++].event);
435
+ this.pending.length = 0;
436
+ const ordered = batch.map((e, i) => ({ e, i })).sort((a, b) => a.e.timeMs - b.e.timeMs || a.i - b.i).map((x) => x.e);
437
+ this.updateFrame();
438
+ for (const e of ordered)
439
+ for (const listener of [...this.listeners])
440
+ listener(e);
441
+ return ordered;
442
+ }
443
+ nowTime() {
444
+ const t = this.clock.nowMs;
445
+ return (this.now = Math.max(Math.max(t, this.now), this.scheduler.clockMs));
446
+ }
447
+ /** @internal */
448
+ get hostNow() {
449
+ return this.now;
450
+ }
451
+ get shown() {
452
+ return this.paused ? this.pausedAt : this.now;
453
+ }
454
+ /** @internal The time an activity that ends now is evaluated at (the pause time while paused). */
455
+ frozen(time) {
456
+ return this.paused ? Math.min(time, this.pausedAt) : time;
457
+ }
458
+ // ---- presentation
459
+ updateFrame() {
460
+ this.frame = this.computeFrame();
461
+ }
462
+ computeFrame() {
463
+ const a = this.scheduler.presentedAnimationIndex, f = this.scheduler.presentedFrameIndex;
464
+ const animations = this.character.animations;
465
+ const valid = a >= 0 && a < animations.length && f >= 0 && f < animations[a].frames.length;
466
+ const blank = valid && animations[a].frames[f].layers.length === 0;
467
+ const shape = valid && !blank && !this.paused ? this.speech?.mouthAt(this.now) ?? null : null;
468
+ const mouth = shape !== null && this.canDrawMouth(a, f, shape) ? shape : null;
469
+ const visible = this.visibilityValue !== 'hidden';
470
+ return {
471
+ animation: valid ? a : -1, frame: valid ? f : -1, mouth, blank, visible, position: this.move?.positionAt(this.shown) ?? this.positionValue,
472
+ scale: this.scaleValue, width: this.character.width, height: this.character.height, hasImage: visible && !blank && valid,
473
+ };
474
+ }
475
+ /** Composes {@link currentFrame} to RGBA (null when nothing is shown). */
476
+ composeFrame() {
477
+ const f = this.frame;
478
+ if (!f.hasImage)
479
+ return null;
480
+ return f.mouth !== null ? this.resources.composeMouthFrame(f.animation, f.frame, f.mouth) : this.resources.composeFrame(f.animation, f.frame);
481
+ }
482
+ /** @internal Top centre of the character in logical units. */
483
+ get anchor() {
484
+ const p = this.move?.positionAt(this.shown) ?? this.positionValue;
485
+ return { x: p.x + (this.character.width * this.scaleValue) / 2, y: p.y };
486
+ }
487
+ // ---- services used by activities
488
+ /** @internal */
489
+ raise(event) {
490
+ this.pending.push({ event: { ...event, agentId: this.id }, position: this.scheduler.pendingEventCount });
491
+ }
492
+ /** @internal */
493
+ setVisibility(time, value) {
494
+ if (this.visibilityValue === value)
495
+ return;
496
+ this.visibilityValue = value;
497
+ this.raise({ type: 'visibility', timeMs: time, visibility: value });
498
+ if (value === 'hidden')
499
+ this.balloonController.hide(time);
500
+ }
501
+ /** @internal */
502
+ positionAt(time) {
503
+ return this.move?.positionAt(time) ?? this.positionValue;
504
+ }
505
+ /** @internal */
506
+ endMove(move, at) {
507
+ if (this.move === move)
508
+ this.move = null;
509
+ this.positionValue = at;
510
+ }
511
+ /** @internal */
512
+ get balloonStyle() {
513
+ return balloonStyleFor(this.character.style, this.source.document.metadata.balloon);
514
+ }
515
+ /** @internal The state name as stored that matches `state` ignoring case (first in file order), or null. */
516
+ stateKey(state) {
517
+ const key = foldCase(state);
518
+ for (const name of this.character.states.keys())
519
+ if (name.length === state.length && foldCase(name) === key)
520
+ return name;
521
+ return null;
522
+ }
523
+ /** @internal The playable animations a state lists, duplicates removed, in listed order. */
524
+ usableAnimations(stateKey) {
525
+ const list = this.character.states.get(stateKey);
526
+ if (!list)
527
+ return [];
528
+ const seen = new Set(), result = [];
529
+ for (const n of list) {
530
+ const i = this.scheduler.indexOf(n);
531
+ if (i >= 0 && !seen.has(i)) {
532
+ seen.add(i);
533
+ result.push(this.character.animations[i].name);
534
+ }
535
+ }
536
+ return result;
537
+ }
538
+ /** @internal One animation of a state: the only usable one, or one draw among several. */
539
+ chooseState(stateKey) {
540
+ const usable = this.usableAnimations(stateKey);
541
+ return usable.length === 0 ? null : usable.length === 1 ? usable[0] : usable[this.scheduler.random.nextInt(usable.length)];
542
+ }
543
+ gestureState(target, time) {
544
+ const p = this.positionAt(time);
545
+ const dx = target.x - (p.x + (this.character.width * this.scaleValue) / 2), dy = target.y - (p.y + (this.character.height * this.scaleValue) / 2);
546
+ if (dx === 0 && dy === 0)
547
+ return null;
548
+ const direction = Math.abs(dx) >= Math.abs(dy) ? (dx > 0 ? 'Left' : 'Right') : dy < 0 ? 'Up' : 'Down';
549
+ return this.stateKey('Gesturing' + direction) ?? this.stateKey('Gesture' + direction);
550
+ }
551
+ /** @internal The resource refusal of an animation by name (null when it can play or is unknown). */
552
+ checkAnimation(animation) {
553
+ const index = this.scheduler.indexOf(animation);
554
+ return index < 0 ? null : this.prepareForStart(index);
555
+ }
556
+ prepareForStart(animation) {
557
+ try {
558
+ this.resources.checkAnimation(animation);
559
+ this.audio.prepare(animation);
560
+ return null;
561
+ }
562
+ catch (e) {
563
+ if (e instanceof CharacterRuntimeError)
564
+ return `Cannot prepare ${this.character.animations[animation].name}: ${e.message}`;
565
+ throw e;
566
+ }
567
+ }
568
+ unavailableReason(name) {
569
+ const u = this.source.document.unavailableAnimations.find((x) => foldCase(x.name) === foldCase(name));
570
+ return u ? `Animation '${u.name}' is unavailable: stream ${u.streamName} is damaged (${u.category}: ${u.message})` : null;
571
+ }
572
+ canSpeakOn(animation, frame) {
573
+ if (animation < 0 || frame < 0)
574
+ return false;
575
+ for (let s = 0; s <= 6; s++)
576
+ if (this.canDrawMouth(animation, frame, s))
577
+ return true;
578
+ return false;
579
+ }
580
+ canDrawMouth(animation, frameIndex, shape) {
581
+ const f = this.character.animations[animation]?.frames[frameIndex];
582
+ if (!f || f.mouths.length === 0)
583
+ return false;
584
+ return checkMouth(f.mouths, shape, f.layers.length, this.character.imageCount).canDraw;
585
+ }
586
+ usesSpeech() {
587
+ return this.provider !== null && (this.speechEnabledValue ?? (this.character.style & CharacterStyle.voiceTts) !== 0);
588
+ }
589
+ decide() {
590
+ if (this.decision)
591
+ return this.decision;
592
+ if (!this.provider)
593
+ return (this.decision = { voice: null, reason: 'No speech provider is configured; Speak shows the balloon and approximate mouth movement without audio.' });
594
+ let voices;
595
+ try {
596
+ voices = this.provider.getVoices();
597
+ }
598
+ catch (e) {
599
+ return (this.decision = { voice: null, reason: `Speech provider ${this.provider.name} failed to list voices: ${e.message}` });
600
+ }
601
+ return (this.decision = selectVoice(voices, this.source.document.metadata.tts, this.voice));
602
+ }
603
+ /** @internal Why Speak would present speech without audio now (null when it synthesizes audio and has an output). */
604
+ get speechAudioProblem() {
605
+ if (!this.provider)
606
+ return 'No speech provider is configured (speech audio off); paced without audio.';
607
+ if (this.speechEnabledValue === false)
608
+ return 'Speech audio off for this session; paced without audio.';
609
+ if (this.speechEnabledValue === null && (this.character.style & CharacterStyle.voiceTts) === 0)
610
+ return "Speech audio off: the character's Style has TTS off and speech is not enabled; paced without audio.";
611
+ if (!this.hasAudioOption)
612
+ return 'Speech audio off: no speech audio output is configured.';
613
+ return null;
614
+ }
615
+ /** @internal A Speak started without audio: causes the host did not choose are runtime errors, so silence is never reported as success. */
616
+ reportNoSpeechAudio(time, requestId, note) {
617
+ this.speechAudioStatusValue = `No speech audio for #${requestId}: ${note}`;
618
+ const styleTts = (this.character.style & CharacterStyle.voiceTts) !== 0;
619
+ if (this.speechEnabledValue !== false && (this.provider === null || (this.speechEnabledValue === null && !styleTts)))
620
+ this.raise({ type: 'runtime-error', timeMs: time, source: 'speech-audio', message: this.speechAudioStatusValue });
621
+ }
622
+ checkText(text) {
623
+ if (text.length > this.maxTextLength)
624
+ throw new InvalidArgumentError(`Text exceeds ${this.maxTextLength} characters.`);
625
+ }
626
+ /** @internal */
627
+ playSpeech(clip, start) {
628
+ try {
629
+ this.speechOutput ??= this.createSpeechOutput?.() ?? null;
630
+ if (!this.speechOutput) {
631
+ this.speechAudioStatusValue = 'Speech audio not played: no speech audio output is configured.';
632
+ this.raise({ type: 'runtime-error', timeMs: start, source: 'speech-audio', message: this.speechAudioStatusValue });
633
+ return;
634
+ }
635
+ const offset = Math.max(0, this.now - start);
636
+ if (offset < clip.durationMs) {
637
+ this.speechOutput.stop();
638
+ this.speechOutput.play(clip, offset);
639
+ this.speechAudioStatusValue = `Speech audio sent to the output from ${Math.round(offset)} ms.`;
640
+ }
641
+ else {
642
+ this.speechAudioStatusValue = `Speech audio skipped: it started ${Math.round(offset)} ms late, after its end.`;
643
+ this.raise({ type: 'runtime-error', timeMs: start, source: 'speech-audio', message: this.speechAudioStatusValue });
644
+ }
645
+ }
646
+ catch (e) {
647
+ this.speechAudioStatusValue = 'Speech audio failed: ' + e.message;
648
+ this.raise({ type: 'runtime-error', timeMs: start, source: 'speech-audio', message: this.speechAudioStatusValue });
649
+ }
650
+ }
651
+ /** @internal */
652
+ stopSpeechAudio() {
653
+ try {
654
+ this.speechOutput?.stop();
655
+ }
656
+ catch (e) {
657
+ this.raise({ type: 'runtime-error', timeMs: this.now, source: 'speech-audio', message: e.message });
658
+ }
659
+ }
660
+ /** @internal */
661
+ createHandle(kind, name, waitTarget) {
662
+ return new AgentRequest(this, kind, name, waitTarget);
663
+ }
664
+ submit(kind, name, build, interrupt, waitTarget = null) {
665
+ if (this.disposed)
666
+ throw new DisposedError('The agent has been disposed.');
667
+ const t = this.nowTime();
668
+ const handle = new AgentRequest(this, kind, name, waitTarget);
669
+ this.scheduler.submit({ ...build(handle), tag: handle }, t, interrupt);
670
+ this.scheduler.update(t);
671
+ this.updateFrame();
672
+ return handle;
673
+ }
674
+ onRequestChanged(record) {
675
+ const handle = this.scheduler.planOf(record.id)?.tag;
676
+ if (handle instanceof AgentRequest)
677
+ handle.update(record);
678
+ }
679
+ fromTrace(e, batch) {
680
+ const request = this.scheduler.find(e.requestId);
681
+ const kind = request?.kind ?? 'play', name = request?.name ?? '';
682
+ const base = { timeMs: e.timeMs, agentId: this.id };
683
+ const animations = this.character.animations;
684
+ switch (e.kind) {
685
+ case 'queued':
686
+ batch.push({ ...base, type: 'request-queued', requestId: e.requestId, kind, name });
687
+ break;
688
+ case 'started':
689
+ batch.push({ ...base, type: 'request-started', requestId: e.requestId, kind, name, animation: e.animation });
690
+ break;
691
+ case 'completed':
692
+ batch.push({ ...base, type: 'request-completed', requestId: e.requestId, kind, name });
693
+ break;
694
+ case 'cancelled':
695
+ batch.push({ ...base, type: 'request-cancelled', requestId: e.requestId, kind, name, reason: request?.reason ?? 'cancelled-by-caller' });
696
+ break;
697
+ case 'failed':
698
+ batch.push({ ...base, type: 'request-failed', requestId: e.requestId, kind, name, code: request?.failureCode ?? '', detail: e.detail });
699
+ break;
700
+ case 'transition':
701
+ batch.push({ ...base, type: 'animation-started', requestId: e.requestId, animation: e.animation, animationName: animations[e.animation]?.name ?? '', frame: e.frame, cause: e.detail });
702
+ break;
703
+ case 'frame':
704
+ batch.push({ ...base, type: 'frame', requestId: e.requestId, animation: e.animation, frame: e.frame, isReturn: e.detail === 'return', resting: false });
705
+ break;
706
+ case 'rest':
707
+ batch.push({ ...base, type: 'frame', requestId: e.requestId, animation: e.animation, frame: e.frame, isReturn: false, resting: true });
708
+ break;
709
+ case 'exit-cycle':
710
+ case 'return-skipped':
711
+ batch.push({ ...base, type: 'runtime-error', source: e.kind, message: e.detail });
712
+ break;
713
+ case 'state':
714
+ batch.push({ ...base, type: 'state-requested', requestId: e.requestId, state: e.detail });
715
+ break;
716
+ case 'paused':
717
+ batch.push({ ...base, type: 'paused' });
718
+ break;
719
+ case 'resumed':
720
+ batch.push({ ...base, type: 'resumed' });
721
+ break;
722
+ }
723
+ if (e.kind === 'frame') {
724
+ const sound = animations[e.animation]?.frames[e.frame]?.sound ?? -1;
725
+ if (sound >= 0)
726
+ batch.push({ ...base, type: 'sound-cue', requestId: e.requestId, animation: e.animation, frame: e.frame, sound });
727
+ }
728
+ }
729
+ /**
730
+ * Cancels every request (reason `disposed`), completes every handle, stops speech and sounds, removes listeners and releases what the
731
+ * agent owns. Idempotent.
732
+ */
733
+ dispose() {
734
+ if (this.disposed)
735
+ return;
736
+ this.resetCore(this.nowTime(), 'disposed');
737
+ this.disposed = true;
738
+ try {
739
+ this.speechOutput?.dispose();
740
+ }
741
+ catch {
742
+ // Disposal problems of a platform output are not runtime errors.
743
+ }
744
+ this.speechOutput = null;
745
+ this.audio.dispose();
746
+ if (this.ownsResources)
747
+ this.resources.dispose();
748
+ this.listeners.clear();
749
+ this.pending.length = 0;
750
+ }
751
+ }
752
+ function requireString(value, what) {
753
+ if (typeof value !== 'string')
754
+ throw new InvalidArgumentError(`The ${what} must be a string.`);
755
+ }
756
+ function checkRate(value) {
757
+ if (!Number.isFinite(value) || value <= 0)
758
+ throw new InvalidArgumentError('The speech rate must be a positive number.');
759
+ return value;
760
+ }
761
+ function requireFinite(x, y) {
762
+ if (!Number.isFinite(x) || !Number.isFinite(y))
763
+ throw new InvalidArgumentError('Coordinates must be finite numbers.');
764
+ }