@rig-c/parts 2.42.0 → 2.44.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/src/scene.ts CHANGED
@@ -96,17 +96,19 @@ import { existsSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync }
96
96
  import { dirname, join, resolve } from 'node:path';
97
97
  import type { RigStop } from '@rig-c/core/rig';
98
98
  import { checkStage, gateThroughRigc, type Log } from './build.ts';
99
- import { ACCEPTABLE_BARS, barsNotMet, type CheckReport, DEFAULT_PACK_SHAPE, DEFAULT_PAGE_EDGES, type PackMode, requirementsNotPass, type RigcRunner } from './check.ts';
99
+ import { ACCEPTABLE_BARS, barsNotMet, type CheckReport, DEFAULT_PACK_SHAPE, DEFAULT_PAGE_EDGES, type PackMode, parsePageSize, requirementsNotPass, type RigcRunner } from './check.ts';
100
100
  import { CONSTRAINT_BONE_FIELDS, editorReceiptProblems, ROOT_BONE } from './config.ts';
101
101
  import { cropToSpineY } from './coords.ts';
102
102
  import { failLine, PartsError, type Problem, refuseIfAny } from './errors.ts';
103
103
  import { readParts } from './parts.ts';
104
104
  import { missingReceipts, readEditorReceipts, type EditorReceipts } from './editreceipt.ts';
105
105
  import type { MotionSpec } from './motion.ts';
106
- import { readPng } from './raster/png.ts';
106
+ import { decodePngBytes } from './raster/png.ts';
107
+ import { clearComposeRun, COMPOSE_RUN_FILE, COMPOSE_RUN_SPEC, type ComposeRun, type RunStampFileEntry } from './runstamp.ts';
107
108
  import { readRequirements, type RequirementsFile } from './requirements.ts';
108
109
  import { OFFSET_PLACES, rigJsonText, type RigSpec } from './rig.ts';
109
110
  import { pyRound } from './round.ts';
111
+ import { mergeSceneAnimations, readSceneAnimations, sceneBoneContext, sceneClipLoopProblems, type SceneAnimations } from './sceneclips.ts';
110
112
 
111
113
  /** The scene file's `spec`. */
112
114
  export const SCENE_SPEC = 'spine-parts-scene/1';
@@ -132,7 +134,7 @@ export const PROVENANCES = ['observed', 'generated', 'unknown'] as const;
132
134
  export type Provenance = (typeof PROVENANCES)[number];
133
135
 
134
136
  /** Every path `compose` writes under `--out`, relative — and so every path it clears first. */
135
- export const COMPOSE_OWNS: readonly string[] = ['rig', 'check', SCENE_REPORT_FILE];
137
+ export const COMPOSE_OWNS: readonly string[] = ['rig', 'check', SCENE_REPORT_FILE, COMPOSE_RUN_FILE];
136
138
 
137
139
  /** `<id>:<name>`. */
138
140
  export function prefixed(id: string, name: string): string {
@@ -168,10 +170,26 @@ export interface ScenePlate {
168
170
  note: string | null;
169
171
  }
170
172
 
173
+ /** An opt-in layer. at is the image top-left in canvas pixels, y down; no scale. */
174
+ export interface NamedScenePlate extends ScenePlate {
175
+ name: string;
176
+ at: [number, number];
177
+ opaque_backdrop?: boolean;
178
+ }
179
+
180
+ /** Separate from character image names; collisions are still refused before emission. */
181
+ export function plateImageName(index: number): string {
182
+ return `scene-plate.${index}.png`;
183
+ }
184
+
171
185
  export interface SceneFile {
172
186
  path: string;
187
+ /** Hash of the exact bytes parsed by loadScene, before any gate runs. */
188
+ sha256: string;
173
189
  canvas: { width: number; height: number };
174
190
  plate: ScenePlate | null;
191
+ plates?: NamedScenePlate[];
192
+ animations?: SceneAnimations;
175
193
  characters: SceneCharacter[];
176
194
  order: string[];
177
195
  }
@@ -235,8 +253,11 @@ export function loadScene(path: string): SceneFile {
235
253
  const at = resolve(path);
236
254
  if (!existsSync(at) || !statSync(at).isFile()) refuseIfAny([{ code: 'SCENE_FILE', object: at, detail: `no such file; a ${SCENE_SPEC} file is required` }]);
237
255
  let raw: unknown;
256
+ let sha256 = '';
238
257
  try {
239
- raw = JSON.parse(readFileSync(at, 'utf8'));
258
+ const bytes = readFileSync(at);
259
+ raw = JSON.parse(bytes.toString('utf8'));
260
+ sha256 = createHash('sha256').update(bytes).digest('hex');
240
261
  } catch (err) {
241
262
  refuseIfAny([{ code: 'SCENE_FILE', object: at, detail: `${(err as Error).message}; a JSON object is required` }]);
242
263
  }
@@ -252,7 +273,7 @@ export function loadScene(path: string): SceneFile {
252
273
  if (!keys.includes(k) && !freeKey(k, v)) fail('SCENE_KEY_KNOWN', `${where}.${k}`, `is a key ${SCENE_SPEC} does not read; it reads ${keys.join(', ')} (and "note", "…_note" strings and "x-…" records, which nothing reads)`);
253
274
  }
254
275
  };
255
- known(o, 'scene', ['spec', 'canvas', 'plate', 'characters', 'order']);
276
+ known(o, 'scene', ['spec', 'canvas', 'plate', 'plates', 'characters', 'order', 'animations']);
256
277
  if (o.spec !== SCENE_SPEC) fail('SCENE_SPEC', 'scene.spec', `is ${show(o.spec)}; "${SCENE_SPEC}" is required`);
257
278
 
258
279
  // canvas
@@ -291,6 +312,40 @@ export function loadScene(path: string): SceneFile {
291
312
  }
292
313
  }
293
314
 
315
+ // Named layers are opt-in; keep the legacy plate reader and its bytes intact.
316
+ const plates: NamedScenePlate[] = [];
317
+ if ('plates' in o) {
318
+ if (!Array.isArray(o.plates)) fail('SCENE_FIELD_TYPE', 'scene.plates', `is ${show(o.plates)}; a list of named plates is required`);
319
+ else {
320
+ const seen = new Map<string, number>();
321
+ o.plates.forEach((p, i) => {
322
+ const where = `scene.plates[${i}]`;
323
+ if (!isRecord(p)) { fail('SCENE_FIELD_TYPE', where, `is ${show(p)}; {name, image, provenance, at} is required`); return; }
324
+ known(p, where, ['name', 'image', 'provenance', 'at', 'opaque_backdrop', 'editor_receipts', 'note']);
325
+ for (const key of ['name', 'image', 'provenance']) {
326
+ if (!(key in p)) fail('SCENE_FIELD_PRESENT', `${where}.${key}`, 'is absent and required');
327
+ else if (typeof p[key] !== 'string' || p[key] === '') fail('SCENE_FIELD_TYPE', `${where}.${key}`, `is ${show(p[key])}; a nonempty string is required`);
328
+ }
329
+ if (typeof p.name === 'string' && p.name !== '') {
330
+ const first = seen.get(p.name);
331
+ if (first !== undefined) fail('SCENE_PLATE_NAME_UNIQUE', `${where}.name`, `is ${show(p.name)}, also declared at scene.plates[${first}]; every plate has one name`);
332
+ else seen.set(p.name, i);
333
+ }
334
+ if (typeof p.provenance === 'string' && !(PROVENANCES as readonly string[]).includes(p.provenance)) fail('SCENE_PLATE_PROVENANCE', `${where}.provenance`, `is ${show(p.provenance)}; one of ${PROVENANCES.join(', ')} is required`);
335
+ const at = p.at;
336
+ const placed = Array.isArray(at) && at.length === 2 && at.every(v => typeof v === 'number' && Number.isFinite(v) && Number.isInteger(v));
337
+ if (!placed) fail('SCENE_PLATE_AT', `${where}.at`, `is ${show(at)}; [x, y], two finite integers locating the image top-left in canvas pixels (y down), is required; negative and outside coordinates are allowed`);
338
+ if ('opaque_backdrop' in p && typeof p.opaque_backdrop !== 'boolean') fail('SCENE_FIELD_TYPE', `${where}.opaque_backdrop`, `is ${show(p.opaque_backdrop)}; a boolean is required`);
339
+ if ('editor_receipts' in p) problems.push(...editorReceiptProblems(p.editor_receipts, `${where}.editor_receipts`).map(problem => ({ ...problem, code: 'SCENE_EDITOR_RECEIPT' })));
340
+ if (typeof p.name === 'string' && p.name !== '' && typeof p.image === 'string' && p.image !== '' && (PROVENANCES as readonly unknown[]).includes(p.provenance) && placed) {
341
+ plates.push({ name: p.name, image: p.image, imagePath: resolve(base, p.image), provenance: p.provenance as Provenance, at: at as [number, number], note: typeof p.note === 'string' ? p.note : null,
342
+ ...('opaque_backdrop' in p ? { opaque_backdrop: p.opaque_backdrop as boolean } : {}),
343
+ ...('editor_receipts' in p ? { editor_receipts: p.editor_receipts as EditorReceipts } : {}) });
344
+ }
345
+ });
346
+ }
347
+ }
348
+
294
349
  // characters
295
350
  const characters: SceneCharacter[] = [];
296
351
  if (!('characters' in o)) fail('SCENE_FIELD_PRESENT', 'scene.characters', 'is absent and required; a list of {"id", "build", "offset"}, at least one');
@@ -366,8 +421,16 @@ export function loadScene(path: string): SceneFile {
366
421
  else order.push(e);
367
422
  });
368
423
  }
424
+ let animations: SceneAnimations | undefined;
425
+ if ('animations' in o) {
426
+ try { animations = readSceneAnimations(o.animations, at); }
427
+ catch (err) {
428
+ if (!(err instanceof PartsError)) throw err;
429
+ problems.push(...err.problems);
430
+ }
431
+ }
369
432
  refuseIfAny(problems);
370
- return { path: at, canvas, plate, characters, order };
433
+ return { path: at, sha256, canvas, plate, ...('plates' in o ? { plates } : {}), ...(animations === undefined ? {} : { animations }), characters, order };
371
434
  }
372
435
 
373
436
  // ---------------------------------------------------------------------------
@@ -386,37 +449,48 @@ export interface CharacterBuild {
386
449
  artBox: [number, number, number, number];
387
450
  /** Every image the build's skin names, as `rig/images/<file>` holds it, in the order the skin names them. */
388
451
  images: Array<[string, Uint8Array]>;
452
+ /** Build-relative paths and hashes of the JSON and image bytes consumed here. */
453
+ files: RunStampFileEntry[];
389
454
  /** The bars its own check failed that were accepted (issue #203), in check's order; empty for a green build. */
390
455
  accepted: string[];
391
456
  }
392
457
 
393
- const BONE_KEYS = ['name', 'parent', 'length', 'rotation', 'x', 'y'];
458
+ const BONE_KEYS = ['name', 'parent', 'length', 'rotation', 'x', 'y', 'inherit'];
394
459
  const SLOT_KEYS = ['name', 'bone', 'attachment'];
395
- const ATTACHMENT_KEYS = ['type', 'path', 'image', 'width', 'height', 'uvs', 'triangles', 'hull', 'weights', 'x', 'y', 'rotation'];
460
+ const ATTACHMENT_KEYS = ['type', 'path', 'image', 'width', 'height', 'uvs', 'triangles', 'hull', 'weights', 'x', 'y', 'rotation', 'generator'];
396
461
  const RIG_KEYS = ['spec', 'name', 'images', 'skeleton', 'bones', 'slots', 'skins', 'constraints', 'stops', 'invariants'];
397
462
  const STOP_KEYS = ['chain', 'links', 'against', 'at', 'inward', 'outward', 'lower'];
398
463
  const STOP_LOWER_KEYS = ['inward', 'outward'];
399
- const INVARIANT_KEYS = ['idleDrivesMeshes', 'detached', 'axes'];
464
+ const INVARIANT_KEYS = ['idleDrivesMeshes', 'detached', 'axes', 'meshSlots', 'meshTriangles', 'deformMayFold'];
400
465
  const MOTION_KEYS = ['spec', 'archetype', 'cut', 'easings', 'groups', 'animations'];
401
- const IDLE_KEYS = ['duration', 'loop', 'note', 'tracks'];
466
+ const IDLE_KEYS = ['duration', 'loop', 'note', 'tracks', 'deform'];
402
467
  const TRACK_KEYS = ['bone', 'group', 'property', 'keys'];
403
- const KEY_KEYS = ['t', 'v', 'curve', 'ease'];
468
+ const KEY_KEYS = ['t', 'v', 'curve', 'ease', 'derive'];
469
+ // Only the turn producer's models, not Core's general transform vocabulary.
470
+ const DERIVE_KEYS = ['kind', 'degrees', 'depth', 'carried', 'about', 'narrowing'];
471
+ const DEFORM_KEYS = ['skin', 'slot', 'attachment', 'keys'];
472
+ const DEFORM_KEY_KEYS = ['t', 'vertices', 'transform'];
473
+ const TURN_TRANSFORM_KEYS = ['kind', 'degrees', 'depth', 'narrowing'];
474
+ type SceneDeform = { skin?: string; slot: string; attachment: string; keys: Array<Record<string, unknown>> };
404
475
 
405
476
  /** One animation of a motion.json: the idle, or one beside it as the file `motion.animations_from` named it (issue #183). */
406
- type SceneAnimation = { duration: number; loop?: boolean; note?: string; tracks: MotionSpec['animations']['idle']['tracks'] };
477
+ type SceneAnimation = { duration: number; loop?: boolean; note?: string; tracks: MotionSpec['animations']['idle']['tracks']; deform?: SceneDeform[] };
407
478
 
408
479
  /** Every animation a motion.json holds, the idle first, in its own order. */
409
480
  function animationsOf(motion: MotionSpec): Record<string, SceneAnimation> {
410
481
  return motion.animations as unknown as Record<string, SceneAnimation>;
411
482
  }
412
483
 
413
- function readJson(path: string, what: string, problems: Problem[]): unknown {
484
+ function readJson(path: string, what: string, problems: Problem[], consumed: (bytes: Uint8Array) => void): unknown {
414
485
  if (!existsSync(path)) {
415
486
  problems.push({ code: 'SCENE_BUILD_PRESENT', object: path, detail: `no such file; ${what}` });
416
487
  return undefined;
417
488
  }
418
489
  try {
419
- return JSON.parse(readFileSync(path, 'utf8'));
490
+ const bytes = readFileSync(path);
491
+ const parsed: unknown = JSON.parse(bytes.toString('utf8'));
492
+ consumed(bytes);
493
+ return parsed;
420
494
  } catch (err) {
421
495
  problems.push({ code: 'SCENE_BUILD_PRESENT', object: path, detail: `${(err as Error).message}; ${what}` });
422
496
  return undefined;
@@ -440,11 +514,16 @@ export function readCharacterBuild(c: SceneCharacter, problems: Problem[], accep
440
514
  const before = problems.length;
441
515
  const dir = c.buildDir;
442
516
  const who = `character "${c.id}" (${c.build})`;
517
+ const files: RunStampFileEntry[] = [];
518
+ const consumed = (path: string, bytes: Uint8Array): void => {
519
+ files.push({ path, sha256: createHash('sha256').update(bytes).digest('hex') });
520
+ };
521
+ const json = (path: string, what: string): unknown => readJson(join(dir, path), what, problems, bytes => consumed(path, bytes));
443
522
  if (!existsSync(dir) || !statSync(dir).isDirectory()) {
444
523
  problems.push({ code: 'SCENE_BUILD_PRESENT', object: who, detail: `${dir} is not a directory; the --out of a green \`rig-parts build\` is required` });
445
524
  return null;
446
525
  }
447
- const check = readJson(join(dir, 'check', 'check.json'), "the build's own check; a build that ran its check writes it", problems);
526
+ const check = json('check/check.json', "the build's own check; a build that ran its check writes it");
448
527
  const joined = new Set([...accept, ...c.accept]);
449
528
  let accepted: string[] = [];
450
529
  if (check !== undefined) {
@@ -474,7 +553,7 @@ export function readCharacterBuild(c: SceneCharacter, problems: Problem[], accep
474
553
  });
475
554
  }
476
555
  }
477
- const parts = readJson(join(dir, 'parts.json'), "assemble's parts.json, which holds the rig_scale and the art's place", problems);
556
+ const parts = json('parts.json', "assemble's parts.json, which holds the rig_scale and the art's place");
478
557
  // Legacy scene records keep their existing checks; a declared package raster
479
558
  // goes through the same file binding reader as rig, check, sheet and propose.
480
559
  if (isRecord(parts) && 'painting_in_rig' in parts) {
@@ -484,8 +563,8 @@ export function readCharacterBuild(c: SceneCharacter, problems: Problem[], accep
484
563
  problems.push(...err.problems);
485
564
  }
486
565
  }
487
- const rigRaw = readJson(join(dir, 'rig', 'rig.json'), "the rig stage's rig.json", problems);
488
- const motionRaw = readJson(join(dir, 'rig', 'motion.json'), "the rig stage's motion.json", problems);
566
+ const rigRaw = json('rig/rig.json', "the rig stage's rig.json");
567
+ const motionRaw = json('rig/motion.json', "the rig stage's motion.json");
489
568
  const unknown = (where: string, obj: unknown, keys: readonly string[]): void => {
490
569
  if (!isRecord(obj)) {
491
570
  problems.push({ code: 'SCENE_BUILD_FIELD_KNOWN', object: `${who} ${where}`, detail: `is ${show(obj)}; an object is required` });
@@ -565,19 +644,51 @@ export function readCharacterBuild(c: SceneCharacter, problems: Problem[], accep
565
644
  });
566
645
  }
567
646
  }
568
- if (isRecord(r.invariants)) unknown('rig.json invariants', r.invariants, INVARIANT_KEYS);
647
+ if (isRecord(r.invariants)) {
648
+ unknown('rig.json invariants', r.invariants, INVARIANT_KEYS);
649
+ for (const key of ['meshSlots', 'meshTriangles']) if (key in r.invariants && !(typeof r.invariants[key] === 'number' && Number.isSafeInteger(r.invariants[key]) && r.invariants[key] >= 0)) {
650
+ problems.push({ code: 'SCENE_BUILD_FIELD_KNOWN', object: `${who} rig.json invariants.${key}`, detail: `is ${show(r.invariants[key])}; a non-negative integer mesh budget is required` });
651
+ }
652
+ if ('deformMayFold' in r.invariants) {
653
+ if (!Array.isArray(r.invariants.deformMayFold)) unknown('rig.json invariants.deformMayFold', r.invariants.deformMayFold, []);
654
+ else r.invariants.deformMayFold.forEach((entry, i) => unknown(`rig.json invariants.deformMayFold[${i}]`, entry, ['slot', 'why']));
655
+ }
656
+ }
569
657
  const skins = isRecord(r.skins) ? r.skins : {};
570
658
  unknown('rig.json skins', skins, ['default']);
571
659
  const seen = new Set<string>();
572
660
  for (const [slot, atts] of Object.entries(isRecord(skins.default) ? skins.default : {})) {
573
661
  for (const [name, att] of Object.entries(isRecord(atts) ? atts : {})) {
574
662
  unknown(`rig.json skins.default.${slot}.${name}`, att, ATTACHMENT_KEYS);
575
- const file = isRecord(att) ? att.image : undefined;
576
- if (typeof file !== 'string' || seen.has(file)) continue;
577
- seen.add(file);
578
- const png = join(dir, 'rig', 'images', file);
579
- if (!existsSync(png)) problems.push({ code: 'SCENE_BUILD_PRESENT', object: `${who} skins.default.${slot}.${name}`, detail: `names the image "${file}", and ${png} does not exist` });
580
- else images.push([file, new Uint8Array(readFileSync(png))]);
663
+ const at = `rig.json skins.default.${slot}.${name}`;
664
+ let depthImage: unknown;
665
+ if (isRecord(att) && 'generator' in att) {
666
+ const g = att.generator;
667
+ unknown(`${at}.generator`, g, ['kind', 'cols', 'rows', 'depth']);
668
+ const shape = (field: string, detail: string): void => { problems.push({ code: 'SCENE_BUILD_FIELD_KNOWN', object: `${who} ${at}.generator.${field}`, detail }); };
669
+ if (isRecord(g)) {
670
+ if (g.kind !== 'grid') shape('kind', `is ${show(g.kind)}; only the rig producer's depth grid is supported`);
671
+ for (const key of ['cols', 'rows']) if (!(typeof g[key] === 'number' && Number.isSafeInteger(g[key]) && g[key] >= 2)) shape(key, `is ${show(g[key])}; an integer grid count of at least two is required`);
672
+ unknown(`${at}.generator.depth`, g.depth, ['image', 'near', 'zScale']);
673
+ if (isRecord(g.depth)) {
674
+ depthImage = g.depth.image;
675
+ if (typeof depthImage !== 'string' || depthImage === '') shape('depth.image', `is ${show(depthImage)}; a depth PNG name is required`);
676
+ if (g.depth.near !== 'white' && g.depth.near !== 'black') shape('depth.near', `is ${show(g.depth.near)}; white or black is required`);
677
+ if (!(typeof g.depth.zScale === 'number' && Number.isFinite(g.depth.zScale) && g.depth.zScale > 0)) shape('depth.zScale', `is ${show(g.depth.zScale)}; a positive finite depth scale is required`);
678
+ }
679
+ }
680
+ }
681
+ for (const file of [isRecord(att) ? att.image : undefined, depthImage]) {
682
+ if (typeof file !== 'string' || seen.has(file)) continue;
683
+ seen.add(file);
684
+ const png = join(dir, 'rig', 'images', file);
685
+ if (!existsSync(png)) problems.push({ code: 'SCENE_BUILD_PRESENT', object: `${who} skins.default.${slot}.${name}`, detail: `names the image "${file}", and ${png} does not exist` });
686
+ else {
687
+ const bytes = new Uint8Array(readFileSync(png));
688
+ images.push([file, bytes]);
689
+ consumed(`rig/images/${file}`, bytes);
690
+ }
691
+ }
581
692
  }
582
693
  }
583
694
  }
@@ -611,8 +722,54 @@ export function readCharacterBuild(c: SceneCharacter, problems: Problem[], accep
611
722
  } else problems.push({ code: 'SCENE_BUILD_PRESENT', object: `${who} motion.json animations.idle`, detail: 'is absent; the rig stage writes one idle, which the scene holds every character\'s tracks in' });
612
723
  }
613
724
  }
725
+ if (isRecord(motionRaw) && isRecord(motionRaw.animations)) {
726
+ const shape = (where: string, detail: string): void => { problems.push({ code: 'SCENE_BUILD_FIELD_KNOWN', object: `${who} ${where}`, detail }); };
727
+ const finite = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v);
728
+ const turn = (v: unknown, at: string, model: 'derive' | 'transform'): void => {
729
+ unknown(at, v, model === 'derive' ? DERIVE_KEYS : TURN_TRANSFORM_KEYS);
730
+ if (!isRecord(v)) return;
731
+ if (v.kind !== 'yaw' && v.kind !== 'pitch') shape(`${at}.kind`, `is ${show(v.kind)}; the turn producer's yaw or pitch is required`);
732
+ if (!finite(v.degrees)) shape(`${at}.degrees`, `is ${show(v.degrees)}; finite degrees are required`);
733
+ if (model === 'derive') {
734
+ if (!finite(v.depth) && !(isRecord(v.depth) && Object.values(v.depth).every(finite))) shape(`${at}.depth`, `is ${show(v.depth)}; a finite depth or a map of bone to finite depth is required`);
735
+ for (const k of ['carried', 'about']) if (k in v && !finite(v[k])) shape(`${at}.${k}`, `is ${show(v[k])}; a finite length is required`);
736
+ } else if (v.depth !== true) shape(`${at}.depth`, `is ${show(v.depth)}; the turn producer's depth: true is required`);
737
+ if ('narrowing' in v && typeof v.narrowing !== 'boolean') shape(`${at}.narrowing`, `is ${show(v.narrowing)}; a boolean is required`);
738
+ };
739
+ for (const [name, anim] of Object.entries(motionRaw.animations)) {
740
+ if (!isRecord(anim)) continue;
741
+ const at = `motion.json animations.${name}`;
742
+ for (const [i, tr] of (Array.isArray(anim.tracks) ? anim.tracks : []).entries()) {
743
+ if (!isRecord(tr) || !Array.isArray(tr.keys)) continue;
744
+ for (const [j, key] of tr.keys.entries()) if (isRecord(key) && 'derive' in key) {
745
+ const where = `${at}.tracks[${i}].keys[${j}]`;
746
+ turn(key.derive, `${where}.derive`, 'derive');
747
+ if ('v' in key) shape(where, 'carries both v and derive; one source of values is required');
748
+ }
749
+ }
750
+ if (!('deform' in anim)) continue;
751
+ if (!Array.isArray(anim.deform)) { shape(`${at}.deform`, `is ${show(anim.deform)}; a list of turn deform timelines is required`); continue; }
752
+ for (const [i, deform] of anim.deform.entries()) {
753
+ const where = `${at}.deform[${i}]`;
754
+ unknown(where, deform, DEFORM_KEYS);
755
+ if (!isRecord(deform)) continue;
756
+ for (const k of ['slot', 'attachment']) if (typeof deform[k] !== 'string' || deform[k] === '') shape(`${where}.${k}`, `is ${show(deform[k])}; a non-empty name is required`);
757
+ if (!Array.isArray(deform.keys)) { shape(`${where}.keys`, `is ${show(deform.keys)}; a list of turn deform keys is required`); continue; }
758
+ for (const [j, key] of deform.keys.entries()) {
759
+ const keyAt = `${where}.keys[${j}]`;
760
+ unknown(keyAt, key, DEFORM_KEY_KEYS);
761
+ if (!isRecord(key)) continue;
762
+ if (!finite(key.t)) shape(`${keyAt}.t`, `is ${show(key.t)}; a finite time is required`);
763
+ if ('vertices' in key && !(Array.isArray(key.vertices) && key.vertices.every(finite))) shape(`${keyAt}.vertices`, `is ${show(key.vertices)}; finite offset pairs are required`);
764
+ if ('transform' in key) turn(key.transform, `${keyAt}.transform`, 'transform');
765
+ if ('vertices' in key && 'transform' in key) shape(keyAt, 'carries both vertices and transform; one source of offsets is required');
766
+ }
767
+ }
768
+ }
769
+ }
614
770
  if (problems.length > before) return null;
615
- return { id: c.id, dir, rig: rigRaw as RigSpec, motion: motionRaw as MotionSpec, rigSize, rigScale, artBox, images, accepted };
771
+ files.sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0);
772
+ return { id: c.id, dir, rig: rigRaw as RigSpec, motion: motionRaw as MotionSpec, rigSize, rigScale, artBox, images, files, accepted };
616
773
  }
617
774
 
618
775
  // ---------------------------------------------------------------------------
@@ -701,12 +858,15 @@ export function scaleProblems(c: SceneCharacter, b: CharacterBuild): Problem[] {
701
858
  (t.keys as unknown as Array<Record<string, unknown>>).forEach((key, j) => {
702
859
  const v = key.v;
703
860
  const numbers = (x: unknown): boolean => Array.isArray(x) && x.every((n) => typeof n === 'number');
704
- if (!numbers(v) && !(isRecord(v) && Object.values(v).every(numbers))) {
861
+ if (!isRecord(key.derive) && !numbers(v) && !(isRecord(v) && Object.values(v).every(numbers))) {
705
862
  out.push({ code: 'SCENE_SCALE_EXACT', object: `${where}.keys[${j}].v`, detail: `is ${show(v)}; a ${prop} key's value is a length, which compose scales in a list of numbers or a map of member to list, and this is neither` });
706
863
  }
707
864
  });
708
865
  });
709
866
  }
867
+ for (const [slot, atts] of Object.entries(b.rig.skins.default)) for (const [name, att] of Object.entries(atts)) {
868
+ if ('generator' in att) out.push({ code: 'SCENE_SCALE_EXACT', object: `${who} rig.json skins.default.${slot}.${name}.generator`, detail: 'is an image-sized depth grid; scaling its bone offsets and zScale does not scale its generated bind geometry — compose it at scale 1, or rebuild it at another assemble.rig_scale' });
869
+ }
710
870
  (b.rig.constraints ?? []).forEach((con, k) => {
711
871
  const forces = con.type === 'physics' ? physicsForce(con as Record<string, unknown>) : [];
712
872
  if (forces.length > 0) {
@@ -808,6 +968,15 @@ function scaledTrack<T extends { property: string; keys: unknown[] }>(t: T, s: n
808
968
  const list = (v: unknown): unknown => (Array.isArray(v) ? v.map((n) => scaledBy(n as number, s)) : v);
809
969
  const keys = (t.keys as Array<Record<string, unknown>>).map((k) => {
810
970
  const out: Record<string, unknown> = { ...k, v: isRecord(k.v) ? Object.fromEntries(Object.entries(k.v).map(([m, x]) => [m, list(x)])) : list(k.v) };
971
+ if (isRecord(k.derive)) {
972
+ const d = { ...k.derive };
973
+ for (const field of ['depth', 'carried', 'about']) {
974
+ const v = d[field];
975
+ if (typeof v === 'number') d[field] = scaledBy(v, s);
976
+ else if (isRecord(v)) d[field] = Object.fromEntries(Object.entries(v).map(([name, n]) => [name, scaledBy(n as number, s)]));
977
+ }
978
+ out.derive = d;
979
+ }
811
980
  // A raw curve is four numbers per channel, (time, value, time, value): the values are at the odd places.
812
981
  if (Array.isArray(k.curve)) out.curve = (k.curve as number[]).map((n, i) => (i % 2 === 1 ? scaledBy(n, s) : n));
813
982
  return out;
@@ -849,9 +1018,10 @@ export interface SceneReport {
849
1018
  scene: string;
850
1019
  canvas: { width: number; height: number };
851
1020
  rig_name: string;
852
- pack_mode: { page_edges: string; pack_shape: string };
1021
+ pack_mode: { page_edges: string; pack_shape: string; page_size?: number };
853
1022
  /** `sha256` (issue #1183) is of the plate PNG's bytes as compose read them, so a verdict can bind to them. */
854
1023
  plate: { image: string; provenance: Provenance; note: string | null; bone: string; slot: string; size: [number, number]; sha256: string; judged_by: 'nothing' } | null;
1024
+ plates?: Array<{ name: string; image: string; provenance: Provenance; note: string | null; at: [number, number]; opaque_backdrop: boolean; bone: string; slot: string; size: [number, number]; sha256: string; judged_by: 'nothing' }>;
855
1025
  characters: SceneCharacterReport[];
856
1026
  order: { declared: string[]; slots: string[]; judged_by: 'nothing' };
857
1027
  idle_duration: number;
@@ -863,6 +1033,8 @@ export interface ComposedScene {
863
1033
  /** Every image file of the composed rig, by its composed name: the plate's first, then each character's. */
864
1034
  images: Array<[string, Uint8Array]>;
865
1035
  report: SceneReport;
1036
+ /** Opt-in declaration retained for pre-emission pose measurement; never serialized. */
1037
+ sceneAnimations?: SceneAnimations;
866
1038
  }
867
1039
 
868
1040
  /** The plate image's bytes and size, read by the caller. */
@@ -889,7 +1061,9 @@ export function composeScene(
889
1061
  problems: Problem[],
890
1062
  mode: PackMode = { pageEdges: DEFAULT_PAGE_EDGES, packShape: DEFAULT_PACK_SHAPE },
891
1063
  requirements: RequirementsFile | null = null,
1064
+ plateLayers: ReadonlyArray<PlateImage | null> = [],
892
1065
  ): ComposedScene {
1066
+ const pageSize = parsePageSize(mode.pageSize);
893
1067
  const fail = (code: string, object: string, detail: string): void => {
894
1068
  problems.push({ code, object, detail });
895
1069
  };
@@ -904,6 +1078,34 @@ export function composeScene(
904
1078
  fail('SCENE_PLATE_SIZE', `scene.plate.image (${scene.plate.image})`, `is ${plate.width}x${plate.height}; the canvas's size, ${canvas.width}x${canvas.height}, is required — the plate is drawn at canvas (0, 0) and is never scaled`);
905
1079
  }
906
1080
 
1081
+ const layers = scene.plates ?? [];
1082
+ const layerNames = new Set(layers.map(p => p.name));
1083
+ const reserved = new Set([ROOT_BONE, PLATE, 'idle', ...ids, ...ready.flatMap(b => [
1084
+ ...b.rig.bones.map(x => prefixed(b.id, x.name)),
1085
+ ...b.rig.slots.map(x => prefixed(b.id, x.name)),
1086
+ ...Object.keys(b.motion.animations).map(n => prefixed(b.id, n)),
1087
+ ])]);
1088
+ layers.forEach((p, i) => {
1089
+ const where = `scene.plates[${i}] (${show(p.name)})`;
1090
+ if (reserved.has(p.name)) fail('SCENE_PLATE_NAME_FREE', `${where}.name`, `is ${show(p.name)}, reserved by the shared root, legacy plate, character id, bone, slot or animation; a distinct name is required`);
1091
+ if (layers.findIndex(q => q.name === p.name) !== i) fail('SCENE_PLATE_NAME_UNIQUE', `${where}.name`, `is ${show(p.name)}, already declared; every plate has one name`);
1092
+ if (!(Array.isArray(p.at) && p.at.length === 2 && p.at.every(v => Number.isFinite(v) && Number.isInteger(v)))) fail('SCENE_PLATE_AT', `${where}.at`, `is ${show(p.at)}; two finite integers of canvas pixels locating the image top-left are required`);
1093
+ const img = plateLayers[i];
1094
+ if (img === undefined || img === null) {
1095
+ fail('SCENE_PLATE_PRESENT', `${where}.image`, 'has no decoded PNG; an image with its own dimensions is required');
1096
+ return;
1097
+ }
1098
+ const raster = decodePngBytes(img.bytes, `${where}.image`);
1099
+ if (raster.width !== img.width || raster.height !== img.height) fail('SCENE_PLATE_SIZE', `${where}.image`, `decoded ${raster.width}x${raster.height}, declared ${img.width}x${img.height}; the image dimensions must agree`);
1100
+ const transparent = raster.data.some((v, k) => k % 4 === 3 && v < 255);
1101
+ if (!transparent) {
1102
+ if (p.opaque_backdrop !== true) fail('SCENE_PLATE_ALPHA', `${where}.image`, `is opaque in every texel; a layer must use alpha below 255 unless this layer explicitly declares opaque_backdrop: true; A19_OVERLAY_PNGS_HAVE_ALPHA remains enabled`);
1103
+ // Core 3.8.0 a19.ts:38-39,64-69: no named rig-spec base plate;
1104
+ // both attachment dimensions must meet the stage, which sceneStage makes the canvas.
1105
+ else if (img.width < stage.width || img.height < stage.height) fail('SCENE_PLATE_BACKDROP_SIZE', `${where}.image`, `is an opaque backdrop of ${img.width}x${img.height}; width >= ${stage.width} and height >= ${stage.height} (the ${canvas.width}x${canvas.height} canvas stage) are required by rigc A19's size inference; use transparency or a sufficiently sized backdrop`);
1106
+ }
1107
+ });
1108
+
907
1109
  // ---- one rig_scale, one idle length -------------------------------------
908
1110
  const scales = ready.map((b) => `"${b.id}" ${b.rigScale}`);
909
1111
  if (new Set(ready.map((b) => b.rigScale)).size > 1) {
@@ -958,8 +1160,15 @@ export function composeScene(
958
1160
  const slotsOf = new Map(ready.map((b) => [b.id, b.rig.slots.map((s) => s.name)]));
959
1161
  const explicit = new Map<string, number>();
960
1162
  const idAt = new Map<string, number>();
1163
+ const layerAt = new Map<string, number>();
961
1164
  scene.order.forEach((e, i) => {
962
1165
  const at = `scene.order[${i}]`;
1166
+ if (layerNames.has(e)) {
1167
+ const first = layerAt.get(e);
1168
+ if (first !== undefined) fail('SCENE_ORDER_ONCE', at, `names the plate ${show(e)} again (first at scene.order[${first}]); every plate slot is drawn exactly once`);
1169
+ else layerAt.set(e, i);
1170
+ return;
1171
+ }
963
1172
  const cut = e.indexOf(PREFIX_SEP);
964
1173
  if (cut < 0) {
965
1174
  if (!ids.includes(e)) {
@@ -995,8 +1204,10 @@ export function composeScene(
995
1204
  fail('SCENE_ORDER_COMPLETE', `scene.order (character "${id}")`, `names ${missing.length} of the ${own.length} slot(s) of "${id}" nowhere: ${missing.map((s) => `"${prefixed(id, s)}"`).join(', ')}; every slot is drawn exactly once — name "${id}" (its remaining slots, in its own order) or each slot`);
996
1205
  }
997
1206
  }
1207
+ for (const p of layers) if (!layerAt.has(p.name)) fail('SCENE_ORDER_COMPLETE', 'scene.order', `names plate ${show(p.name)} nowhere; every plate slot is drawn exactly once`);
998
1208
  const drawn: string[] = [];
999
1209
  for (const e of scene.order) {
1210
+ if (layerNames.has(e)) { drawn.push(e); continue; }
1000
1211
  if (e.includes(PREFIX_SEP)) {
1001
1212
  if (explicit.has(e)) drawn.push(e);
1002
1213
  continue;
@@ -1047,6 +1258,37 @@ export function composeScene(
1047
1258
  ax.bones.forEach((n, j) => ownBone(b.id, n, `character "${b.id}" rig.json invariants.axes[${k}].bones[${j}]`));
1048
1259
  }
1049
1260
  }
1261
+ // Turn names are resolved before any output or call to Core, including map keys.
1262
+ for (const b of ready) {
1263
+ const anims = animationsOf(b.motion);
1264
+ const missing = (where: string, detail: string): void => { fail('SCENE_NAME_RESOLVES', `character "${b.id}" ${where}`, detail); };
1265
+ for (const [name, anim] of Object.entries(anims)) {
1266
+ for (const [i, tr] of anim.tracks.entries()) {
1267
+ const t = tr as unknown as Record<string, unknown>;
1268
+ const members = typeof t.bone === 'string' ? [t.bone] : typeof t.group === 'string' ? b.motion.groups[t.group] : undefined;
1269
+ for (const [j, key] of (t.keys as Array<Record<string, unknown>>).entries()) {
1270
+ const at = `motion.json animations.${name}.tracks[${i}].keys[${j}]`;
1271
+ const maps: Array<[string, unknown]> = [['v', key.v], ['derive.depth', isRecord(key.derive) ? key.derive.depth : undefined]];
1272
+ for (const [field, map] of maps) if (isRecord(map)) for (const member of Object.keys(map)) {
1273
+ ownBone(b.id, member, `character "${b.id}" ${at}.${field}.${member}`);
1274
+ if (members === undefined || !members.includes(member)) missing(`${at}.${field}.${member}`, `names "${member}", which is not a member of this track's target; a named member of that target is required`);
1275
+ }
1276
+ }
1277
+ }
1278
+ for (const [i, d] of (anim.deform ?? []).entries()) {
1279
+ const at = `motion.json animations.${name}.deform[${i}]`;
1280
+ if (d.skin !== undefined && d.skin !== 'default') missing(`${at}.skin`, `names ${show(d.skin)}; the composed rig shares only the default skin`);
1281
+ if (!(slotsOf.get(b.id) ?? []).includes(d.slot)) missing(`${at}.slot`, `names "${d.slot}", which this character does not declare`);
1282
+ if (b.rig.skins.default[d.slot]?.[d.attachment] === undefined) missing(`${at}.attachment`, `names "${d.attachment}" on slot "${d.slot}", which this character's default skin does not hold`);
1283
+ }
1284
+ }
1285
+ for (const [i, entry] of (b.rig.invariants?.deformMayFold ?? []).entries()) {
1286
+ if (!(slotsOf.get(b.id) ?? []).includes(entry.slot)) missing(`rig.json invariants.deformMayFold[${i}].slot`, `names ${show(entry.slot)}, which this character does not declare`);
1287
+ }
1288
+ for (const [i, con] of (b.rig.constraints ?? []).entries()) if (con.type === 'slider') {
1289
+ if (typeof con.animation !== 'string' || !(con.animation in anims)) missing(`rig.json constraints[${i}].animation`, `names ${show(con.animation)}, which this character's motion does not declare; an animation of its own is required`);
1290
+ }
1291
+ }
1050
1292
  // The root is shared: a character that drives it would move every character.
1051
1293
  for (const b of ready) {
1052
1294
  const where = `character "${b.id}"`;
@@ -1078,6 +1320,7 @@ export function composeScene(
1078
1320
  // ---- image names ------------------------------------------------------------
1079
1321
  const taken = new Map<string, string>();
1080
1322
  if (scene.plate !== null) taken.set(PLATE_IMAGE, 'the plate');
1323
+ layers.forEach((p, i) => taken.set(plateImageName(i), `plate ${show(p.name)}`));
1081
1324
  for (const b of ready) {
1082
1325
  for (const [file] of b.images) {
1083
1326
  const n = imageName(b.id, file);
@@ -1086,7 +1329,7 @@ export function composeScene(
1086
1329
  else taken.set(n, `character "${b.id}" image "${file}"`);
1087
1330
  }
1088
1331
  }
1089
- if (requirements !== null) problems.push(...requirementPrefixProblems(requirements, ready, scene.plate !== null));
1332
+ if (requirements !== null) problems.push(...requirementPrefixProblems(requirements, ready, scene.plate !== null, [...layerNames]));
1090
1333
  refuseIfAny(problems);
1091
1334
 
1092
1335
  // ---- the rig ----------------------------------------------------------------
@@ -1114,6 +1357,13 @@ export function composeScene(
1114
1357
  skin[PLATE] = { [PLATE]: { image: PLATE_IMAGE, x: stage.x + canvas.width / 2, y: cropToSpineY(canvas.height / 2, canvas.height) } };
1115
1358
  images.push([PLATE_IMAGE, plate.bytes]);
1116
1359
  }
1360
+ layers.forEach((p, i) => {
1361
+ const img = plateLayers[i] as PlateImage;
1362
+ bones.push({ name: p.name, parent: ROOT_BONE, x: 0, y: 0 });
1363
+ skin[p.name] = { [p.name]: { image: plateImageName(i), x: stage.x + p.at[0] + img.width / 2, y: cropToSpineY(p.at[1] + img.height / 2, canvas.height) } };
1364
+ slotDefs.set(p.name, { name: p.name, bone: p.name, attachment: p.name });
1365
+ images.push([plateImageName(i), img.bytes]);
1366
+ });
1117
1367
  const constraints: Array<Record<string, unknown>> = [];
1118
1368
  const stops: RigStop[] = [];
1119
1369
  const detached: NonNullable<NonNullable<RigSpec['invariants']>['detached']> = [];
@@ -1146,6 +1396,9 @@ export function composeScene(
1146
1396
  ...(typeof att.path === 'string' ? { path: imageName(id, att.path) } : {}),
1147
1397
  image: imageName(id, att.image as string),
1148
1398
  };
1399
+ if (isRecord(att.generator) && isRecord(att.generator.depth)) {
1400
+ a.generator = { ...att.generator, depth: { ...att.generator.depth, image: imageName(id, att.generator.depth.image as string) } };
1401
+ }
1149
1402
  if (Array.isArray(att.weights)) {
1150
1403
  a.weights = (att.weights as Array<Array<Record<string, unknown>>>).map((v) =>
1151
1404
  v.map((w) =>
@@ -1180,6 +1433,7 @@ export function composeScene(
1180
1433
  out[field] = arity === 'one' ? P(id, con[field] as string) : (con[field] as string[]).map((n) => P(id, n));
1181
1434
  }
1182
1435
  if (type === 'path' && typeof con.slot === 'string') out.slot = prefixed(id, con.slot);
1436
+ if (type === 'slider' && typeof con.animation === 'string') out.animation = con.animation === 'idle' ? 'idle' : prefixed(id, con.animation);
1183
1437
  constraints.push(out);
1184
1438
  }
1185
1439
  for (const st of b.rig.stops ?? []) {
@@ -1207,12 +1461,32 @@ export function composeScene(
1207
1461
  if (whys.length === 1) invariants.idleDrivesMeshes = { why: whys[0] };
1208
1462
  if (detached.length > 0) invariants.detached = detached;
1209
1463
  if (axes.length > 0) invariants.axes = axes;
1464
+ const mayFold = ready.flatMap(b => (b.rig.invariants?.deformMayFold ?? []).map(e => ({ ...e, slot: prefixed(b.id, e.slot) })));
1465
+ if (mayFold.length > 0) invariants.deformMayFold = mayFold;
1466
+ const meshCounts = (b: CharacterBuild): { meshSlots: number; meshTriangles: number } => {
1467
+ let meshSlots = 0, meshTriangles = 0;
1468
+ for (const atts of Object.values(b.rig.skins.default)) {
1469
+ let mesh = false;
1470
+ for (const att of Object.values(atts)) if ('type' in att && att.type === 'mesh') {
1471
+ mesh = true;
1472
+ const triangles = att.generator?.kind === 'grid' ? 2 * (att.generator.cols - 1) * (att.generator.rows - 1) : att.triangles.length / 3;
1473
+ meshTriangles = Math.max(meshTriangles, triangles);
1474
+ }
1475
+ if (mesh) meshSlots++;
1476
+ }
1477
+ return { meshSlots, meshTriangles };
1478
+ };
1479
+ for (const field of ['meshSlots', 'meshTriangles'] as const) if (ready.some(b => b.rig.invariants?.[field] !== undefined)) {
1480
+ const values = ready.map(b => b.rig.invariants?.[field] ?? meshCounts(b)[field]);
1481
+ invariants[field] = field === 'meshSlots' ? values.reduce((a, b) => a + b, 0) : Math.max(...values);
1482
+ }
1210
1483
  if (Object.keys(invariants).length > 0) rig.invariants = invariants;
1211
1484
 
1212
1485
  // ---- the motion ---------------------------------------------------------------
1213
1486
  const easings: MotionSpec['easings'] = {};
1214
1487
  const groups: MotionSpec['groups'] = {};
1215
1488
  const tracks: MotionSpec['animations']['idle']['tracks'] = [];
1489
+ const idleDeform: SceneDeform[] = [];
1216
1490
  // Every animation beside a character's idle rides along under its character's prefix (issue #183), its tracks
1217
1491
  // prefixed as the idle's are and nothing else changed: the scene plays the idle, and schedules none of these.
1218
1492
  const beside: Record<string, SceneAnimation> = {};
@@ -1226,27 +1500,45 @@ export function composeScene(
1226
1500
  const tr = { ...t } as Record<string, unknown>;
1227
1501
  if (typeof tr.bone === 'string') tr.bone = P(id, tr.bone);
1228
1502
  if (typeof tr.group === 'string') tr.group = prefixed(id, tr.group);
1229
- tr.keys = (t.keys as unknown as Array<Record<string, unknown>>).map((k) => (typeof k.ease === 'string' ? { ...k, ease: prefixed(id, k.ease) } : k));
1503
+ const memberMap = (v: Record<string, unknown>): Record<string, unknown> => Object.fromEntries(Object.entries(v).map(([n, value]) => [P(id, n), value]));
1504
+ tr.keys = (t.keys as unknown as Array<Record<string, unknown>>).map((k) => ({
1505
+ ...k,
1506
+ ...(typeof k.ease === 'string' ? { ease: prefixed(id, k.ease) } : {}),
1507
+ ...(isRecord(k.v) ? { v: memberMap(k.v) } : {}),
1508
+ ...(isRecord(k.derive) ? { derive: { ...k.derive, ...(isRecord(k.derive.depth) ? { depth: memberMap(k.derive.depth) } : {}) } } : {}),
1509
+ }));
1230
1510
  return tr as unknown as MotionSpec['animations']['idle']['tracks'][number];
1231
1511
  };
1232
1512
  for (const t of b.motion.animations.idle.tracks) tracks.push(scaledTrack(prefixTrack(t), c.scale));
1233
- for (const [n, a] of Object.entries(animationsOf(b.motion))) if (n !== 'idle') beside[prefixed(id, n)] = { ...a, tracks: a.tracks.map((t) => scaledTrack(prefixTrack(t), c.scale)) };
1513
+ const deforms = (a: SceneAnimation): { deform?: SceneDeform[] } => a.deform === undefined ? {} : { deform: a.deform.map((d) => ({
1514
+ ...d, slot: prefixed(id, d.slot), attachment: prefixed(id, d.attachment),
1515
+ // default is the one shared skin, not a per-character name.
1516
+ keys: d.keys.map((k) => ({ ...k, ...(Array.isArray(k.vertices) && c.scale !== 1 ? { vertices: k.vertices.map((v) => scaledBy(v as number, c.scale)) } : {}) })),
1517
+ })) };
1518
+ idleDeform.push(...(deforms(animationsOf(b.motion).idle).deform ?? []));
1519
+ for (const [n, a] of Object.entries(animationsOf(b.motion))) if (n !== 'idle') beside[prefixed(id, n)] = { ...a, tracks: a.tracks.map((t) => scaledTrack(prefixTrack(t), c.scale)), ...deforms(a) };
1234
1520
  }
1235
1521
  const note = notes.size === 1 ? [...notes][0] : ready.map((b) => `${b.id}: ${b.motion.animations.idle.note}`).join(' | ');
1236
- const motion: MotionSpec = { spec: 'rigc-motion/1', archetype: name, cut: name, easings, groups, animations: { idle: { duration: durations[0], loop: true, note, tracks }, ...beside } };
1522
+ const motion: MotionSpec = { spec: 'rigc-motion/1', archetype: name, cut: name, easings, groups, animations: { idle: { duration: durations[0], loop: true, note, tracks, ...(idleDeform.length === 0 ? {} : { deform: idleDeform }) }, ...beside } };
1523
+
1524
+ if (scene.animations !== undefined) mergeSceneAnimations(rig, motion, scene.animations);
1237
1525
 
1238
1526
  const report: SceneReport = {
1239
1527
  spec: SCENE_REPORT_SPEC,
1240
1528
  scene: scene.path,
1241
1529
  canvas: { ...canvas },
1242
1530
  rig_name: name,
1243
- pack_mode: { page_edges: mode.pageEdges, pack_shape: mode.packShape },
1531
+ pack_mode: { page_edges: mode.pageEdges, pack_shape: mode.packShape, ...(pageSize === undefined ? {} : { page_size: pageSize }) },
1244
1532
  plate: scene.plate === null || plate === null ? null : { image: scene.plate.image, provenance: scene.plate.provenance, note: scene.plate.note, bone: PLATE, slot: PLATE, size: [plate.width, plate.height], sha256: createHash('sha256').update(plate.bytes).digest('hex'), judged_by: 'nothing' },
1533
+ ...(scene.plates === undefined ? {} : { plates: layers.map((p, i) => {
1534
+ const img = plateLayers[i] as PlateImage;
1535
+ return { name: p.name, image: p.image, provenance: p.provenance, note: p.note, at: [...p.at] as [number, number], opaque_backdrop: p.opaque_backdrop === true, bone: p.name, slot: p.name, size: [img.width, img.height] as [number, number], sha256: createHash('sha256').update(img.bytes).digest('hex'), judged_by: 'nothing' as const };
1536
+ }) }),
1245
1537
  characters: rows,
1246
1538
  order: { declared: [...scene.order], slots: slots.map((s) => s.name), judged_by: 'nothing' },
1247
1539
  idle_duration: durations[0],
1248
1540
  };
1249
- return { rig, motion, images, report };
1541
+ return { rig, motion, images, report, ...(scene.animations === undefined ? {} : { sceneAnimations: scene.animations }) };
1250
1542
  }
1251
1543
 
1252
1544
  // ---------------------------------------------------------------------------
@@ -1260,7 +1552,7 @@ export function composeScene(
1260
1552
  * refused naming the prefixed names it could have meant. Any other miss is
1261
1553
  * left to `check`'s own `REQUIREMENTS_RESOLVES`, which names it in its words.
1262
1554
  */
1263
- export function requirementPrefixProblems(file: RequirementsFile, builds: readonly CharacterBuild[], plate: boolean): Problem[] {
1555
+ export function requirementPrefixProblems(file: RequirementsFile, builds: readonly CharacterBuild[], plate: boolean, plates: readonly string[] = []): Problem[] {
1264
1556
  const out: Problem[] = [];
1265
1557
  const bare = {
1266
1558
  bone: (b: CharacterBuild) => b.rig.bones.map((x) => x.name).filter((n) => n !== ROOT_BONE),
@@ -1269,7 +1561,7 @@ export function requirementPrefixProblems(file: RequirementsFile, builds: readon
1269
1561
  attachment: (b: CharacterBuild) => Object.values(b.rig.skins.default).flatMap((a) => Object.keys(a)),
1270
1562
  } as const;
1271
1563
  // What the composed rig will hold, by kind: each character's names under its prefix, and the shared root and plate.
1272
- const own = (kind: keyof typeof bare): Set<string> => new Set([...builds.flatMap((b) => bare[kind](b).map((n) => prefixed(b.id, n))), ...(kind === 'bone' ? [ROOT_BONE] : []), ...(plate && kind !== 'constraint' ? [PLATE] : [])]);
1564
+ const own = (kind: keyof typeof bare): Set<string> => new Set([...builds.flatMap((b) => bare[kind](b).map((n) => prefixed(b.id, n))), ...(kind === 'bone' ? [ROOT_BONE] : []), ...(plate && kind !== 'constraint' ? [PLATE] : []), ...(kind !== 'constraint' ? plates : [])]);
1273
1565
  const kinds = {
1274
1566
  bone: { have: own('bone'), bare: bare.bone },
1275
1567
  constraint: { have: own('constraint'), bare: bare.constraint },
@@ -1314,9 +1606,9 @@ export function requirementPrefixProblems(file: RequirementsFile, builds: readon
1314
1606
  * control runs over what `compose` wrote. Each entry is `<where> "<name>"`.
1315
1607
  * Images are held to `<id>.` the same way.
1316
1608
  */
1317
- export function unprefixedNames(rig: RigSpec, motion: MotionSpec, ids: readonly string[], plate: boolean): string[] {
1609
+ export function unprefixedNames(rig: RigSpec, motion: MotionSpec, ids: readonly string[], plate: boolean, plates: readonly string[] = [], sceneAnimations: readonly string[] = []): string[] {
1318
1610
  const bad: string[] = [];
1319
- const ok = (n: string, allowPlate: boolean): boolean => n === ROOT_BONE || (allowPlate && plate && n === PLATE) || ids.some((id) => n.startsWith(`${id}${PREFIX_SEP}`) && n.length > id.length + 1);
1611
+ const ok = (n: string, allowPlate: boolean): boolean => n === ROOT_BONE || (allowPlate && ((plate && n === PLATE) || plates.includes(n))) || ids.some((id) => n.startsWith(`${id}${PREFIX_SEP}`) && n.length > id.length + 1);
1320
1612
  const name = (where: string, n: unknown, allowPlate = true): void => {
1321
1613
  if (typeof n !== 'string' || !ok(n, allowPlate)) bad.push(`${where} ${show(n)}`);
1322
1614
  };
@@ -1335,7 +1627,12 @@ export function unprefixedNames(rig: RigSpec, motion: MotionSpec, ids: readonly
1335
1627
  for (const [a, att] of Object.entries(atts)) {
1336
1628
  name(`skin ${slot} attachment`, a);
1337
1629
  const img = (att as unknown as Attachment).image;
1338
- if (typeof img !== 'string' || !((plate && img === PLATE_IMAGE) || ids.some((id) => img.startsWith(`${id}${IMAGE_SEP}`)))) bad.push(`skin ${slot} ${a} image ${show(img)}`);
1630
+ if (typeof img !== 'string' || !((plate && img === PLATE_IMAGE) || plates.some((_, i) => img === plateImageName(i)) || ids.some((id) => img.startsWith(`${id}${IMAGE_SEP}`)))) bad.push(`skin ${slot} ${a} image ${show(img)}`);
1631
+ const generator = (att as unknown as Attachment).generator;
1632
+ if (isRecord(generator) && isRecord(generator.depth)) {
1633
+ const image = generator.depth.image;
1634
+ if (typeof image !== 'string' || !ids.some(id => image.startsWith(`${id}${IMAGE_SEP}`))) bad.push(`skin ${slot} ${a} depth image ${show(image)}`);
1635
+ }
1339
1636
  const w = (att as unknown as Attachment).weights;
1340
1637
  if (Array.isArray(w)) for (const v of w as Array<Array<{ bone: string }>>) for (const e of v) name(`skin ${slot} ${a} weight bone`, e.bone, false);
1341
1638
  }
@@ -1348,12 +1645,14 @@ export function unprefixedNames(rig: RigSpec, motion: MotionSpec, ids: readonly
1348
1645
  else if (Array.isArray(v)) for (const n of v) name(`constraint ${String(c.name)} ${field}`, n, false);
1349
1646
  }
1350
1647
  if (c.type === 'path') name(`constraint ${String(c.name)} slot`, c.slot, false);
1648
+ if (c.type === 'slider' && c.animation !== 'idle') name(`constraint ${String(c.name)} animation`, c.animation, false);
1351
1649
  }
1352
1650
  for (const s of rig.stops ?? []) {
1353
1651
  name('stop chain', s.chain, false);
1354
1652
  for (const l of s.links) name(`stop ${s.chain} link`, l, false);
1355
1653
  name(`stop ${s.chain} against`, s.against, false);
1356
1654
  }
1655
+ for (const entry of rig.invariants?.deformMayFold ?? []) name('invariants.deformMayFold slot', entry.slot, false);
1357
1656
  for (const d of rig.invariants?.detached ?? []) {
1358
1657
  name('invariants.detached bone', d.bone, false);
1359
1658
  name('invariants.detached notUnder', d.notUnder, false);
@@ -1367,11 +1666,22 @@ export function unprefixedNames(rig: RigSpec, motion: MotionSpec, ids: readonly
1367
1666
  name('group', g, false);
1368
1667
  for (const m of members) name(`group ${g} member`, m, false);
1369
1668
  }
1370
- for (const t of Object.values(animationsOf(motion)).flatMap((a) => a.tracks)) {
1669
+ for (const [animation, a] of Object.entries(animationsOf(motion))) for (const t of a.tracks) {
1371
1670
  const tr = t as unknown as Record<string, unknown>;
1372
- if ('bone' in tr) name('track bone', tr.bone, false);
1671
+ if ('bone' in tr) name('track bone', tr.bone, sceneAnimations.includes(animation));
1373
1672
  if ('group' in tr) name('track group', tr.group, false);
1374
- for (const k of (tr.keys as Array<Record<string, unknown>>) ?? []) if (typeof k.ease === 'string') name('key ease', k.ease, false);
1673
+ for (const k of (tr.keys as Array<Record<string, unknown>>) ?? []) {
1674
+ if (typeof k.ease === 'string') name('key ease', k.ease, false);
1675
+ for (const map of [k.v, isRecord(k.derive) ? k.derive.depth : undefined]) if (isRecord(map)) for (const member of Object.keys(map)) name('key member', member, false);
1676
+ }
1677
+ }
1678
+ for (const [animation, a] of Object.entries(animationsOf(motion))) {
1679
+ if (animation !== 'idle' && !sceneAnimations.includes(animation)) name('animation', animation, false);
1680
+ for (const d of a.deform ?? []) {
1681
+ name('deform slot', d.slot, false);
1682
+ name('deform attachment', d.attachment, false);
1683
+ if (d.skin !== undefined && d.skin !== 'default') bad.push(`deform skin ${show(d.skin)}`);
1684
+ }
1375
1685
  }
1376
1686
  return bad;
1377
1687
  }
@@ -1387,7 +1697,7 @@ export function unprefixedNames(rig: RigSpec, motion: MotionSpec, ids: readonly
1387
1697
  * {@link composeScene} — one refusal naming every problem the
1388
1698
  * files hold. Pure but for the reads.
1389
1699
  */
1390
- export function composeFromFiles(scenePath: string, requirementsPath?: string, mode: PackMode = { pageEdges: DEFAULT_PAGE_EDGES, packShape: DEFAULT_PACK_SHAPE }, accept: readonly string[] = []): ComposedScene {
1700
+ export function composeFromFiles(scenePath: string, requirementsPath?: string, mode: PackMode = { pageEdges: DEFAULT_PAGE_EDGES, packShape: DEFAULT_PACK_SHAPE }, accept: readonly string[] = []): ComposedScene & { runRecord: ComposeRun } {
1391
1701
  const scene = loadScene(scenePath);
1392
1702
  const problems: Problem[] = acceptProblems(accept, '--accept');
1393
1703
  const builds = scene.characters.map((c) => readCharacterBuild(c, problems, accept));
@@ -1405,13 +1715,28 @@ export function composeFromFiles(scenePath: string, requirementsPath?: string, m
1405
1715
  if (!existsSync(scene.plate.imagePath)) problems.push({ code: 'SCENE_PLATE_PRESENT', object: where, detail: `${scene.plate.imagePath} does not exist; a PNG of the canvas's size is required` });
1406
1716
  else {
1407
1717
  try {
1408
- const r = readPng(scene.plate.imagePath);
1409
- plate = { bytes: new Uint8Array(readFileSync(scene.plate.imagePath)), width: r.width, height: r.height };
1718
+ const bytes = new Uint8Array(readFileSync(scene.plate.imagePath));
1719
+ const r = decodePngBytes(bytes, scene.plate.imagePath);
1720
+ plate = { bytes, width: r.width, height: r.height };
1410
1721
  } catch (err) {
1411
1722
  problems.push({ code: 'SCENE_PLATE_PRESENT', object: where, detail: `${(err as Error).message}; a PNG is required` });
1412
1723
  }
1413
1724
  }
1414
1725
  }
1726
+ const plateLayers = (scene.plates ?? []).map((p, i): PlateImage | null => {
1727
+ const where = `scene.plates[${i}]`;
1728
+ const ledger = readEditorReceipts(p.editor_receipts, scene.path, `${where}.editor_receipts`, 'scene file');
1729
+ const codes: Readonly<Record<string, string>> = { ASSEMBLE_EDITOR_RECEIPT_FILE: 'SCENE_EDITOR_RECEIPT_FILE', ASSEMBLE_EDITOR_RECEIPT_SHA256: 'SCENE_EDITOR_RECEIPT_SHA256', ASSEMBLE_EDITOR_RECEIPT_MISSING: 'SCENE_EDITOR_RECEIPT_MISSING' };
1730
+ problems.push(...[...ledger.problems, ...missingReceipts(ledger, [{ object: `${where}.image`, path: p.imagePath }])].map(problem => ({ ...problem, code: codes[problem.code] ?? problem.code })));
1731
+ try {
1732
+ const bytes = new Uint8Array(readFileSync(p.imagePath));
1733
+ const r = decodePngBytes(bytes, `${where}.image`);
1734
+ return { bytes, width: r.width, height: r.height };
1735
+ } catch (err) {
1736
+ problems.push({ code: 'SCENE_PLATE_PRESENT', object: `${where}.image (${p.image})`, detail: `${(err as Error).message}; a PNG is required` });
1737
+ return null;
1738
+ }
1739
+ });
1415
1740
  let req: RequirementsFile | null = null;
1416
1741
  if (requirementsPath !== undefined) {
1417
1742
  try {
@@ -1421,12 +1746,24 @@ export function composeFromFiles(scenePath: string, requirementsPath?: string, m
1421
1746
  problems.push(...err.problems);
1422
1747
  }
1423
1748
  }
1424
- return composeScene(scene, builds, plate, problems, mode, req);
1749
+ const composed = composeScene(scene, builds, plate, problems, mode, req, plateLayers);
1750
+ const runRecord: ComposeRun = {
1751
+ spec: COMPOSE_RUN_SPEC,
1752
+ scene: { path: scenePath, sha256: scene.sha256 },
1753
+ characters: scene.characters.map(c => ({ id: c.id, build: c.build, files: builds.find(b => b?.id === c.id)!.files }))
1754
+ .sort((a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0),
1755
+ plate: scene.plate === null || plate === null ? null : { path: scene.plate.image, sha256: createHash('sha256').update(plate.bytes).digest('hex') },
1756
+ plates: (scene.plates ?? []).map((p, i) => ({ name: p.name, path: p.image, sha256: createHash('sha256').update(plateLayers[i]!.bytes).digest('hex') }))
1757
+ .sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0),
1758
+ };
1759
+ return { ...composed, runRecord };
1425
1760
  }
1426
1761
 
1427
1762
  export interface ComposeInput {
1428
1763
  scene: string;
1429
1764
  out: string;
1765
+ /** The packed builds' `--page-size`; rigc's default when absent (issue #1352). */
1766
+ pageSize?: number;
1430
1767
  requirements?: string;
1431
1768
  /** `--accept`: the bars every character's own check may fail and still be composed (issue #203). */
1432
1769
  accept?: readonly string[];
@@ -1459,6 +1796,8 @@ export interface ComposeResult {
1459
1796
  * first. A crash that is not a refusal is rethrown.
1460
1797
  */
1461
1798
  export function composeStage(input: ComposeInput, run: ComposeRunners, log: Log): ComposeResult {
1799
+ // Clear before even option validation: a refused rerun cannot retain an earlier receipt.
1800
+ clearComposeRun(input.out);
1462
1801
  const prefix = (stage: ComposeStage): Log => (line) => log(`[${stage}] ${line}`);
1463
1802
  const say = prefix('compose');
1464
1803
  const refused = (stage: ComposeStage, err: unknown, composed: ComposedScene | null = null): ComposeResult => {
@@ -1469,11 +1808,12 @@ export function composeStage(input: ComposeInput, run: ComposeRunners, log: Log)
1469
1808
  log(`compose: stopped at ${stage}; nothing ${stage === 'compose' ? 'was written' : 'after the check was written'}`);
1470
1809
  return { stoppedAt: stage, composed, check: null };
1471
1810
  };
1811
+ const pageSize = parsePageSize(input.pageSize);
1472
1812
  mkdirSync(input.out, { recursive: true });
1473
1813
  for (const p of COMPOSE_OWNS) rmSync(join(input.out, p), { recursive: true, force: true });
1474
- const mode: PackMode = { pageEdges: DEFAULT_PAGE_EDGES, packShape: DEFAULT_PACK_SHAPE };
1814
+ const mode: PackMode = { pageEdges: DEFAULT_PAGE_EDGES, packShape: DEFAULT_PACK_SHAPE, ...(pageSize === undefined ? {} : { pageSize }) };
1475
1815
  log(`rig-parts compose: ${input.scene} -> ${input.out}, page edges ${mode.pageEdges}, pack shape ${mode.packShape}`);
1476
- let composed: ComposedScene;
1816
+ let composed: ReturnType<typeof composeFromFiles>;
1477
1817
  try {
1478
1818
  composed = composeFromFiles(input.scene, input.requirements, mode, input.accept ?? []);
1479
1819
  } catch (err) {
@@ -1490,7 +1830,16 @@ export function composeStage(input: ComposeInput, run: ComposeRunners, log: Log)
1490
1830
  ['rig.json', rigJsonText(composed.rig)],
1491
1831
  ['motion.json', rigJsonText(composed.motion)],
1492
1832
  ];
1493
- const gate = gateThroughRigc(composed.images, texts, run.rig, run.scratch, mode);
1833
+ let gate: ReturnType<typeof gateThroughRigc>;
1834
+ try {
1835
+ const clips = composed.sceneAnimations;
1836
+ gate = gateThroughRigc(composed.images, texts, run.rig, run.scratch, mode, clips === undefined ? undefined : build => {
1837
+ refuseIfAny(sceneClipLoopProblems(readFileSync(join(build, 'skeleton.model.json'), 'utf8'), clips));
1838
+ });
1839
+ } catch (err) { return refused('compose', err); }
1840
+ if (composed.sceneAnimations !== undefined) for (const g of gate) {
1841
+ g.lines = g.lines.map(line => sceneBoneContext(line, composed.report.characters.map(c => c.id)));
1842
+ }
1494
1843
  for (const g of gate) {
1495
1844
  say(` rigc ${g.label}: exit ${g.status}`);
1496
1845
  for (const l of g.lines) say(` ${l.trim()}`);
@@ -1516,7 +1865,7 @@ export function composeStage(input: ComposeInput, run: ComposeRunners, log: Log)
1516
1865
  say(`wrote ${join(rigDir, 'rig.json')}, motion.json and ${composed.images.length} image(s) under ${join(rigDir, 'images')}, and ${join(input.out, SCENE_REPORT_FILE)}`);
1517
1866
  let report: CheckReport;
1518
1867
  try {
1519
- report = checkStage({ rig: rigDir, out: join(input.out, 'check'), pageEdges: mode.pageEdges, packShape: mode.packShape, ...(input.requirements === undefined ? {} : { requirements: input.requirements }) }, run.check, run.checkBin, prefix('check'));
1868
+ report = checkStage({ rig: rigDir, out: join(input.out, 'check'), pageEdges: mode.pageEdges, packShape: mode.packShape, ...(pageSize === undefined ? {} : { pageSize }), ...(input.requirements === undefined ? {} : { requirements: input.requirements }) }, run.check, run.checkBin, prefix('check'));
1520
1869
  } catch (err) {
1521
1870
  return refused('check', err, composed);
1522
1871
  }
@@ -1532,6 +1881,7 @@ export function composeStage(input: ComposeInput, run: ComposeRunners, log: Log)
1532
1881
  log(`compose: stopped at check; the composed rig's check is PASS${acceptedLine} (the composed rig and scene.json are written; the scene is for looking, not shipping)`);
1533
1882
  return { stoppedAt: 'check', composed, check: report };
1534
1883
  }
1884
+ writeFileSync(join(input.out, COMPOSE_RUN_FILE), rigJsonText(composed.runRecord));
1535
1885
  log(`compose: PASS — ${report.bars.measured.length} of ${report.bars.measured.length + report.bars.skipped.length} bar(s) measured; the packed atlas under ${join(input.out, 'check', 'build')} is the artifact`);
1536
1886
  return { stoppedAt: null, composed, check: report };
1537
1887
  }