@anime-studio/core 0.2.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/dist/audio.d.ts +44 -0
  2. package/dist/audio.d.ts.map +1 -0
  3. package/dist/audio.js +57 -0
  4. package/dist/audio.js.map +1 -0
  5. package/dist/bounds.d.ts +25 -0
  6. package/dist/bounds.d.ts.map +1 -0
  7. package/dist/bounds.js +211 -0
  8. package/dist/bounds.js.map +1 -0
  9. package/dist/fastmath.d.ts +12 -0
  10. package/dist/fastmath.d.ts.map +1 -0
  11. package/dist/fastmath.js +35 -0
  12. package/dist/fastmath.js.map +1 -0
  13. package/dist/field.d.ts.map +1 -1
  14. package/dist/field.js +74 -38
  15. package/dist/field.js.map +1 -1
  16. package/dist/format/schema.d.ts +22 -0
  17. package/dist/format/schema.d.ts.map +1 -1
  18. package/dist/format/schema.js +18 -3
  19. package/dist/format/schema.js.map +1 -1
  20. package/dist/format/validate.d.ts.map +1 -1
  21. package/dist/format/validate.js +7 -2
  22. package/dist/format/validate.js.map +1 -1
  23. package/dist/fx.d.ts +26 -0
  24. package/dist/fx.d.ts.map +1 -1
  25. package/dist/fx.js +122 -22
  26. package/dist/fx.js.map +1 -1
  27. package/dist/index.d.ts +3 -0
  28. package/dist/index.d.ts.map +1 -1
  29. package/dist/index.js +3 -0
  30. package/dist/index.js.map +1 -1
  31. package/dist/preview.d.ts +16 -1
  32. package/dist/preview.d.ts.map +1 -1
  33. package/dist/preview.js +43 -4
  34. package/dist/preview.js.map +1 -1
  35. package/dist/rig.d.ts.map +1 -1
  36. package/dist/rig.js +3 -1
  37. package/dist/rig.js.map +1 -1
  38. package/dist/sanitize.d.ts +24 -0
  39. package/dist/sanitize.d.ts.map +1 -0
  40. package/dist/sanitize.js +79 -0
  41. package/dist/sanitize.js.map +1 -0
  42. package/dist/scene.d.ts +31 -3
  43. package/dist/scene.d.ts.map +1 -1
  44. package/dist/scene.js +136 -23
  45. package/dist/scene.js.map +1 -1
  46. package/dist/sequence.d.ts +5 -3
  47. package/dist/sequence.d.ts.map +1 -1
  48. package/dist/sequence.js +15 -6
  49. package/dist/sequence.js.map +1 -1
  50. package/dist/solid.d.ts.map +1 -1
  51. package/dist/solid.js +437 -47
  52. package/dist/solid.js.map +1 -1
  53. package/package.json +1 -1
package/dist/scene.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { getEasing } from "./easing.js";
2
2
  import { makeTrack, normalizeTrack, sampleTrack } from "./keyframes.js";
3
3
  import { cuesFromText } from "./lipsync.js";
4
- import { BEHIND_FX, FX_DURATIONS, SCREEN_FX, fxMarkup } from "./fx.js";
4
+ import { BEHIND_FX, BODY_ANCHOR_AT, FX_DEFAULT_ANCHOR, FX_DEFAULT_LAYER, FX_DURATIONS, LAYERED_FX, SCREEN_FX, fxMarkup } from "./fx.js";
5
5
  import { cssBlur, bakeFollow, bakeFrame, clampToBounds, depthBlur, fitBox, matScale, handheldOffset, pathPoint, punchFactor, rigBounds, rigWeight, sampleFollow, sampleFrame, } from "./camera.js";
6
6
  import { compileSurface, surfaceY } from "./surface.js";
7
7
  import { fallHeight, groundParts, hipBone, lyingPose, planFall, planGetUp } from "./fall.js";
@@ -11,15 +11,25 @@ import { apply, applyLinear, clamp, formatNumber, fromTRS, hashString, invert, l
11
11
  import { bakeHang, bakePhysics, sampleHang, samplePhysics } from "./physics.js";
12
12
  import { markupBounds } from "./paths.js";
13
13
  import { LIGHTING_DEFS, keyLight, lightingAt, lightingChannelDefault, overlayMarkup, projectLights, shadingMarkup, unknownKeyLight, } from "./lighting.js";
14
+ import { sanitizeSvg } from "./sanitize.js";
14
15
  import { applyPhysicsSample, evaluatePose } from "./pose.js";
15
16
  import { nodeToString, renderCharacter } from "./render.js";
16
17
  import { RigError, compileRig, namespaceIds, resolveChannel } from "./rig.js";
17
18
  export class SceneError extends Error {
18
19
  path;
19
- constructor(message, path) {
20
+ /** The message without the path in front. */
21
+ detail;
22
+ /**
23
+ * Every problem found. A script is compiled to the end, so a scene with several bad actions
24
+ * throws one SceneError listing them all (one per action); otherwise this is the error itself.
25
+ */
26
+ problems;
27
+ constructor(message, path, problems) {
20
28
  super(path ? `${path}: ${message}` : message);
21
29
  this.path = path;
22
30
  this.name = "SceneError";
31
+ this.detail = message;
32
+ this.problems = problems ?? [{ path: path ?? "(root)", message }];
23
33
  }
24
34
  }
25
35
  /** Placement channels; `flip` and `z` are stepped (a side, a depth order: nothing in between). */
@@ -184,6 +194,40 @@ function initialPlacement(def) {
184
194
  }
185
195
  /** Frames per drawing from a `twos` field: `true` = 2, `false` = 1, a number as is (unset: `fallback`). */
186
196
  const framesPerDrawing = (v, fallback) => v === undefined ? fallback : v === true ? 2 : v === false ? 1 : Math.max(1, Math.round(v));
197
+ /**
198
+ * The names a pose control accepts: its poses (a 2.5D rig's `view`: its drawn views too). An
199
+ * unknown name would draw the default in silence, so it is an error naming the valid ones.
200
+ */
201
+ export function poseNames(rig, control) {
202
+ const c = rig.controls[control];
203
+ if (!c || c.type !== "pose")
204
+ return undefined;
205
+ const names = Object.keys(c.poses);
206
+ if (control === "view" && rig.rig3d)
207
+ for (const v of Object.keys(rig.rig3d.views))
208
+ if (!names.includes(v))
209
+ names.push(v);
210
+ return names;
211
+ }
212
+ /** Throws a SceneError when a pose control's value (a name or `{ name: weight }`) is not one of its poses. */
213
+ function checkPoseValue(rig, control, value, path) {
214
+ const valid = poseNames(rig, control);
215
+ if (!valid || value === null || value === undefined)
216
+ return;
217
+ const names = typeof value === "string" ? [value] : typeof value === "object" && !Array.isArray(value) ? Object.keys(value) : undefined;
218
+ const list = valid.join(", ") || "none";
219
+ if (!names)
220
+ throw new SceneError(`the "${control}" control takes a pose name or { name: weight } weights, not ${JSON.stringify(value)}. Valid: ${list}.`, path);
221
+ for (const name of names) {
222
+ if (valid.includes(name))
223
+ continue;
224
+ // A mirrored view ("~half") exists for a head turned on its own, not for the body.
225
+ const hint = name.startsWith("~") && valid.includes(name.slice(1))
226
+ ? ` The "${control}" control has no mirrored drawings: use "${name.slice(1)}" and turn the actor round with its "flip" (or a "face" action).`
227
+ : "";
228
+ throw new SceneError(`"${name}" is not a pose of the "${control}" control of "${rig.name}". Valid: ${list}.${hint}`, path);
229
+ }
230
+ }
187
231
  /** Compiles a validated scene and its assets into an evaluable scene. */
188
232
  export function compileScene(doc, assets) {
189
233
  const rigCache = new Map();
@@ -254,13 +298,15 @@ export function compileScene(doc, assets) {
254
298
  throw new SceneError(`unknown surface "${def.ground.surface}"`, `props[${i}].ground`);
255
299
  ground = { surface: sf, offset: def.ground.offset ?? 0 };
256
300
  }
257
- return { id: def.id, def, markup: def.art, placement: {}, grabs: [], impulses: [], ground };
301
+ // Art from the document is sanitized here, once (it ends up in the DOM: see `sanitizeSvg`).
302
+ const safe = { ...def, art: sanitizeSvg(def.art), ...(def.back !== undefined ? { back: sanitizeSvg(def.back) } : {}) };
303
+ return { id: def.id, def: safe, markup: safe.art, placement: {}, grabs: [], impulses: [], ground };
258
304
  });
259
305
  const propBuffers = new Map(props.map((p) => {
260
306
  const init = initialPlacement(p.def);
261
307
  return [p.id, Object.fromEntries(PLACEMENT.map((k) => [k, new KeyBuffer(init[k])]))];
262
308
  }));
263
- const layers = (doc.layers ?? []).map((def) => ({ id: def.id, def, placement: {} }));
309
+ const layers = (doc.layers ?? []).map((def) => ({ id: def.id, def: { ...def, art: sanitizeSvg(def.art) }, placement: {} }));
264
310
  const layerBuffers = new Map(layers.map((l) => {
265
311
  const init = initialPlacement(l.def);
266
312
  return [l.id, Object.fromEntries(PLACEMENT.map((k) => [k, new KeyBuffer(init[k])]))];
@@ -350,9 +396,16 @@ export function compileScene(doc, assets) {
350
396
  actorBuffers.get(seg[1]).placement[rest].push(...norm);
351
397
  else {
352
398
  try {
399
+ const rig = rigCache.get(seg[1]);
400
+ const ref = resolveChannel(rig, rest);
401
+ if (ref.kind === "control")
402
+ for (const k of norm)
403
+ checkPoseValue(rig, ref.name, k.v, path);
353
404
  channelBuffer(seg[1], rest).push(...norm);
354
405
  }
355
406
  catch (e) {
407
+ if (e instanceof SceneError)
408
+ throw e;
356
409
  throw new SceneError(e.message, path);
357
410
  }
358
411
  }
@@ -378,23 +431,48 @@ export function compileScene(doc, assets) {
378
431
  const fx = [];
379
432
  const audio = [];
380
433
  const script = (doc.script ?? []).map((a, i) => ({ a, i })).sort((x, y) => x.a.at - y.a.at || x.i - y.i);
381
- const audioEvent = (id, at, volume, path) => {
434
+ const audioEvent = (id, at, volume, path, extra) => {
382
435
  const src = doc.audio?.[id];
383
436
  if (src === undefined)
384
437
  throw new SceneError(`unknown audio "${id}" (declare it in "audio")`, path);
385
- audio.push({ id, src, start: at, volume });
438
+ audio.push({ id, src, start: at, volume, ...extra });
386
439
  };
387
440
  // walkTo clips of 2.5D rigs, their speed matched to the view at the end (`drawnStride`).
388
441
  const walksIn3d = [];
442
+ /** The time span of each actor's walks (`walkTo`), for the overlap warning. */
443
+ const walkSpans = [];
444
+ // Every action is compiled, so a script with several mistakes reports them all (one error per
445
+ // action, in script order); the scene still does not compile.
446
+ const scriptErrors = [];
389
447
  for (const { a, i } of script) {
390
448
  const path = `script[${i}] (${a.action})`;
391
449
  try {
392
450
  compileAction(a, path);
393
451
  }
394
452
  catch (e) {
395
- if (e instanceof SceneError)
396
- throw e;
397
- throw new SceneError(e.message, path);
453
+ scriptErrors.push({ index: i, error: e instanceof SceneError ? e : new SceneError(e.message, path) });
454
+ }
455
+ }
456
+ if (scriptErrors.length === 1)
457
+ throw scriptErrors[0].error;
458
+ if (scriptErrors.length > 1) {
459
+ const problems = scriptErrors.sort((x, y) => x.index - y.index).flatMap((x) => x.error.problems);
460
+ throw new SceneError(`${problems.length} errors in the script:\n${problems.map((p) => ` - ${p.path}: ${p.message}`).join("\n")}`, undefined, problems);
461
+ }
462
+ // Two walks of one actor at the same time: the later one takes over where the actor is, which is
463
+ // rarely what was meant (a walk's length comes from its distance and speed when no duration is given).
464
+ const warnings = [];
465
+ const span = (w) => `${+w.start.toFixed(3)}–${+w.end.toFixed(3)} s`;
466
+ for (const [k, w] of walkSpans.entries()) {
467
+ for (const v of walkSpans.slice(0, k)) {
468
+ if (v.actor !== w.actor || !(w.start < v.end - 1e-6 && v.start < w.end - 1e-6))
469
+ continue;
470
+ const [first, second] = v.start <= w.start ? [v, w] : [w, v];
471
+ warnings.push({
472
+ path: second.path,
473
+ message: `walkTo of "${w.actor}" (${span(second)}) overlaps ${first.path.replace(/ \(.*\)$/, "")} (${span(first)}): the later walk takes over at ${+second.start.toFixed(3)} s` +
474
+ ` from wherever the earlier one has got to. Start it when the first one ends, or shorten the first (its "duration", or a higher "speed").`,
475
+ });
398
476
  }
399
477
  }
400
478
  function requireActor(id, path) {
@@ -449,6 +527,7 @@ export function compileScene(doc, assets) {
449
527
  }
450
528
  const ref = resolveChannel(rig, a.channel);
451
529
  if (ref.kind === "control" && rig.controls[ref.name].type === "pose") {
530
+ checkPoseValue(rig, ref.name, a.value, path);
452
531
  setPose(a.actor, ref.name, a.value, a.at, duration, ease);
453
532
  return;
454
533
  }
@@ -458,6 +537,7 @@ export function compileScene(doc, assets) {
458
537
  case "pose": {
459
538
  const { rig } = requireActor(a.actor, path);
460
539
  firstControl(rig, "pose", a.control, path);
540
+ checkPoseValue(rig, a.control, a.value, path);
461
541
  setPose(a.actor, a.control, a.value, a.at, a.duration ?? 0.3, easeOf(a.ease, "sineInOut"));
462
542
  return;
463
543
  }
@@ -467,7 +547,7 @@ export function compileScene(doc, assets) {
467
547
  const clipName = a.clip ?? "walk";
468
548
  const clip = rig.clips[clipName];
469
549
  if (!clip)
470
- throw new SceneError(`walkTo needs a "${clipName}" clip on "${rig.name}"`, path);
550
+ throw new SceneError(`walkTo needs a "${clipName}" clip on "${rig.name}". Known clips: ${Object.keys(rig.clips).join(", ") || "none"}.`, path);
471
551
  const x0 = buffers.placement.x.valueAt(a.at);
472
552
  const y0 = buffers.placement.y.valueAt(a.at);
473
553
  const y1 = a.y ?? y0;
@@ -483,6 +563,7 @@ export function compileScene(doc, assets) {
483
563
  if (distance < 1e-6)
484
564
  return;
485
565
  const duration = a.duration ?? distance / (a.speed ?? 220);
566
+ walkSpans.push({ actor: a.actor, path, start: a.at, end: a.at + duration });
486
567
  // Trapezoidal velocity profile: accelerate, cruise, decelerate (no foot sliding pops).
487
568
  const ramp = Math.min(0.3, duration / 3);
488
569
  const v = distance / (duration - ramp);
@@ -624,7 +705,7 @@ export function compileScene(doc, assets) {
624
705
  throw new SceneError("say needs one of: cues, lipsync, text", path);
625
706
  channelBuffer(a.actor, `controls.${control}`).push(...cuesToVisemeKeys(cues, a.at));
626
707
  if (a.audio)
627
- audioEvent(a.audio, a.at, a.volume ?? 1, path);
708
+ audioEvent(a.audio, a.at, a.volume ?? 1, path, { kind: "speech", length: cues.length ? cues[cues.length - 1].end : a.duration });
628
709
  return;
629
710
  }
630
711
  case "grab": {
@@ -780,19 +861,24 @@ export function compileScene(doc, assets) {
780
861
  seed: hashString(`shake${shakes.length}`),
781
862
  });
782
863
  return;
783
- case "sound":
784
- audioEvent(a.audio, a.at, a.volume ?? 1, path);
864
+ case "sound": {
865
+ // A loop without a duration plays to the end of the scene (and fades out there).
866
+ const maxDuration = a.duration ?? (a.loop ? Math.max(0, doc.duration - a.at) : undefined);
867
+ audioEvent(a.audio, a.at, a.volume ?? 1, path, { kind: "sound", ...(a.from ? { trimStart: a.from } : {}), maxDuration, loop: a.loop, fadeIn: a.fadeIn, fadeOut: a.fadeOut, duck: a.duck });
785
868
  return;
869
+ }
786
870
  case "fx": {
787
871
  if (a.actor) {
788
872
  requireActor(a.actor, path);
789
873
  const rig = rigCache.get(a.actor);
790
- if (a.anchor && a.anchor !== "origin" && !rig.anchors[a.anchor]) {
791
- throw new SceneError(`unknown anchor "${a.anchor}" on actor "${a.actor}". Known anchors: ${Object.keys(rig.anchors).join(", ") || "none"}, origin.`, path);
874
+ if (a.anchor && a.anchor !== "origin" && a.anchor !== "body" && !rig.anchors[a.anchor]) {
875
+ throw new SceneError(`unknown anchor "${a.anchor}" on actor "${a.actor}". Known anchors: ${Object.keys(rig.anchors).join(", ") || "none"}, origin, body.`, path);
792
876
  }
793
877
  }
794
878
  if (a.prop && !propIds.has(a.prop))
795
879
  throw new SceneError(`unknown prop "${a.prop}". Known props: ${[...propIds].join(", ") || "none"}.`, path);
880
+ if (a.layer && !LAYERED_FX.includes(a.type))
881
+ throw new SceneError(`fx "${a.type}" has no layer: only ${LAYERED_FX.join(" and ")} take one (the others are placed by their type).`, path);
796
882
  const dflt = fxDefaultPoint(a.type, a.style, doc.width, doc.height);
797
883
  fx.push({
798
884
  type: a.type,
@@ -811,6 +897,7 @@ export function compileScene(doc, assets) {
811
897
  ...(a.text !== undefined ? { text: a.text } : {}),
812
898
  ...(a.style ? { variant: a.style } : {}),
813
899
  ...(a.angle !== undefined ? { angle: a.angle } : {}),
900
+ ...(LAYERED_FX.includes(a.type) ? { layer: a.layer ?? FX_DEFAULT_LAYER } : {}),
814
901
  });
815
902
  return;
816
903
  }
@@ -1160,6 +1247,7 @@ export function compileScene(doc, assets) {
1160
1247
  fx,
1161
1248
  audio: audio.sort((x, y) => x.start - y.start),
1162
1249
  animation,
1250
+ ...(warnings.length ? { warnings } : {}),
1163
1251
  };
1164
1252
  // Every actor knows its scene: riding resolves the ridden actor, drawings need the frame rate.
1165
1253
  for (const actor of actors)
@@ -2686,19 +2774,43 @@ export function evaluateScene(scene, t) {
2686
2774
  continue;
2687
2775
  let m;
2688
2776
  let z = 100;
2777
+ let backdrop;
2689
2778
  if (SCREEN_FX.includes(e.type)) {
2690
2779
  // Fixed to the frame: x/y are screen coordinates (defaults resolved when compiled).
2691
2780
  m = [e.scale, 0, 0, e.scale, e.x, e.y];
2692
2781
  z = e.type === "caption" ? 1e6 : e.type === "impactFrame" ? 1e6 + 1 : 999;
2782
+ // Speed / focus lines behind the actors (over the set) or replacing the set: just under the
2783
+ // given actor, else under every actor on screen (and under their auras). Nobody there: on top.
2784
+ if (e.layer && e.layer !== "over") {
2785
+ const under = (e.actor ? scene.actors.filter((a) => a.id === e.actor) : scene.actors)
2786
+ .map((a) => actorPlacementState(a, t))
2787
+ .filter((p) => p.opacity > 0.01)
2788
+ .map((p) => p.z);
2789
+ if (under.length)
2790
+ z = Math.min(...under) - 0.02;
2791
+ if (e.layer === "replace") {
2792
+ // The whole frame, in fx space (the lines' origin and scale).
2793
+ const s = e.scale || 1;
2794
+ backdrop = { color: e.type === "speedLines" ? e.color : (e.fill ?? "#ffffff"), box: [-e.x / s, -e.y / s, scene.width / s, scene.height / s] };
2795
+ }
2796
+ }
2693
2797
  }
2694
2798
  else if (e.actor) {
2695
2799
  const actor = scene.actors.find((a) => a.id === e.actor);
2696
2800
  const pose = poses.get(actor.id);
2697
- const name = e.anchor ?? (actor.rig.anchors.head ? "head" : "origin");
2801
+ const name = e.anchor ?? FX_DEFAULT_ANCHOR[e.type] ?? (actor.rig.anchors.head ? "head" : "origin");
2802
+ const anchorAt = (n) => {
2803
+ const a = actor.rig.anchors[n];
2804
+ return apply(multiply(pose.world[a.bone], actor.rig.bones[a.bone].setupWorldInv), a.at);
2805
+ };
2698
2806
  let local = [0, 0];
2699
- if (name !== "origin") {
2700
- const a = actor.rig.anchors[name];
2701
- local = apply(multiply(pose.world[a.bone], actor.rig.bones[a.bone].setupWorldInv), a.at);
2807
+ if (name === "body" && !actor.rig.anchors.body) {
2808
+ // The chest: most of the way from the feet up to the head (the feet when there is no head).
2809
+ const head = actor.rig.anchors.head ? anchorAt("head") : [0, 0];
2810
+ local = [head[0] * BODY_ANCHOR_AT, head[1] * BODY_ANCHOR_AT];
2811
+ }
2812
+ else if (name !== "origin") {
2813
+ local = anchorAt(name);
2702
2814
  }
2703
2815
  const am = multiply(viewMatrix(scene, cam, actor.def.parallax ?? 1), actorPlacement(actor, t));
2704
2816
  const p = apply(am, [local[0] + e.offset[0], local[1] + e.offset[1]]);
@@ -2718,11 +2830,12 @@ export function evaluateScene(scene, t) {
2718
2830
  const s = Math.hypot(v[0], v[1]) * e.scale;
2719
2831
  m = [s, 0, 0, s, p[0], p[1]];
2720
2832
  }
2721
- const markup = fxMarkup(e.type, u, t - e.start, { color: e.color, fill: e.fill, seed: e.seed, text: e.text, variant: e.variant, angle: e.angle, width: scene.width, height: scene.height });
2833
+ // (Colours come from the document: the effect's markup is sanitized like art.)
2834
+ const markup = sanitizeSvg(fxMarkup(e.type, u, t - e.start, { color: e.color, fill: e.fill, seed: e.seed, text: e.text, variant: e.variant, angle: e.angle, width: scene.width, height: scene.height, ...(backdrop ? { backdrop } : {}) }));
2722
2835
  items.push({ z, order: order++, node: { kind: "markup", key: `fx-${e.seed}-${e.start}`, transform: m, markup } });
2723
2836
  }
2724
2837
  if (light) {
2725
- const markup = overlayMarkup(light, screenLights, scene.width, scene.height);
2838
+ const markup = sanitizeSvg(overlayMarkup(light, screenLights, scene.width, scene.height));
2726
2839
  if (markup)
2727
2840
  items.push({ z: Infinity, order: order++, node: { kind: "markup", key: "lighting", markup } });
2728
2841
  }
@@ -2731,7 +2844,7 @@ export function evaluateScene(scene, t) {
2731
2844
  const u = (t - tr.start) / tr.duration;
2732
2845
  if (u < 0 || u > 1)
2733
2846
  return;
2734
- const markup = transitionMarkup({
2847
+ const markup = sanitizeSvg(transitionMarkup({
2735
2848
  type: tr.type,
2736
2849
  coverage: transitionCoverage(tr.mode, u),
2737
2850
  uncovering: tr.mode === "in" || (tr.mode === "outIn" && u > 0.5),
@@ -2741,7 +2854,7 @@ export function evaluateScene(scene, t) {
2741
2854
  width: scene.width,
2742
2855
  height: scene.height,
2743
2856
  id: String(i),
2744
- });
2857
+ }));
2745
2858
  if (markup)
2746
2859
  items.push({ z: Infinity, order: order++ + 1e6, node: { kind: "markup", key: `transition-${i}`, markup } });
2747
2860
  });