@rig-c/parts 1.67.0 → 1.69.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/parts.ts CHANGED
@@ -1,3 +1,5 @@
1
+ import { baseAnchorProblems, orderedBaseAnchor, type BaseAnchor } from './baseanchor.ts';
2
+ import { partDepthProblems, type PartDepthReference } from './depthsheets.ts';
1
3
  /**
2
4
  * The output contract of the assemble stage: `parts.json`, one record per
3
5
  * part, beside `parts/<name>.png`.
@@ -94,6 +96,8 @@ import { edgeLength } from './length.ts';
94
96
  import { recordedFocusProblems } from './setfocus.ts';
95
97
 
96
98
  export interface PartRecord {
99
+ /** Optional #773 input reference; production geometry does not consume it yet. */
100
+ depth?: PartDepthReference;
97
101
  name: string;
98
102
  from: string;
99
103
  /**
@@ -302,6 +306,7 @@ export interface RecompositeRecord {
302
306
  }
303
307
 
304
308
  export interface AlternateSetMap {
309
+ base_anchor?: BaseAnchor;
305
310
  /** Authored point in setup-world coordinates, only when supplied (issue #719). */
306
311
  focus?: [number, number];
307
312
  slots: Record<string, string>;
@@ -322,6 +327,7 @@ export const FRONT_SUFFIX = '_front';
322
327
 
323
328
  export interface AlternatePartsRecord {
324
329
  name: string;
330
+ base_anchor?: BaseAnchor;
325
331
  /** Original authored painting point and its source size, only when supplied. */
326
332
  focus?: [number, number];
327
333
  focus_source_size?: [number, number];
@@ -427,6 +433,7 @@ export const PART_KEYS = [
427
433
  'seam_override_px',
428
434
  'fringe_pushed_back',
429
435
  'limb',
436
+ 'depth',
430
437
  ] as const;
431
438
  /** The one part field that is not a count: a list of `{part, px}`, written only when it is not empty. */
432
439
  const FRINGE_KEY = 'fringe_pushed_back';
@@ -434,10 +441,10 @@ const FRINGE_KEY = 'fringe_pushed_back';
434
441
  const CUT_FROM_KEY = 'cut_from';
435
442
  /** The one part field that is a record of its own: a limb segment's provenance (issue #349), written only on one. */
436
443
  const LIMB_KEY = 'limb';
437
- const COUNT_KEYS = PART_KEYS.slice(2).filter((k) => k !== FRINGE_KEY && k !== CUT_FROM_KEY && k !== LIMB_KEY) as ReadonlyArray<(typeof PART_KEYS)[number]>;
444
+ const COUNT_KEYS = PART_KEYS.slice(2).filter((k) => k !== FRINGE_KEY && k !== CUT_FROM_KEY && k !== LIMB_KEY && k !== 'depth') as ReadonlyArray<(typeof PART_KEYS)[number]>;
438
445
  /** The port's own counts: all three or none (none = a record the reference wrote). */
439
446
  export const VISIBILITY_KEYS = ['visible_px', 'occluded_px', 'visible_not_projected_px'] as const;
440
- const REQUIRED_KEYS = PART_KEYS.filter((k) => !(VISIBILITY_KEYS as readonly string[]).includes(k) && k !== FRINGE_KEY && k !== CUT_FROM_KEY && k !== LIMB_KEY);
447
+ const REQUIRED_KEYS = PART_KEYS.filter((k) => !(VISIBILITY_KEYS as readonly string[]).includes(k) && k !== FRINGE_KEY && k !== CUT_FROM_KEY && k !== LIMB_KEY && k !== 'depth');
441
448
 
442
449
  /** Where a part came from: a See-through run and a v3 tag or an author-made layer's `author:<label>` (issue #256), or the painting itself for a patch. */
443
450
  export type From = { run: 'full' | 'head'; tag: string } | { run: 'painting'; patch: string };
@@ -488,6 +495,7 @@ export function serializeParts(file: PartsFile): string {
488
495
  : {
489
496
  alternates: file.alternates.map((a) => ({
490
497
  name: a.name,
498
+ ...(a.base_anchor === undefined ? {} : { base_anchor: orderedBaseAnchor(a.base_anchor) }),
491
499
  ...(a.parts === undefined ? {} : { parts: a.parts }),
492
500
  ...(a.hides === undefined ? {} : { hides: a.hides }),
493
501
  ...(a.front === undefined ? {} : { front: a.front }),
@@ -572,6 +580,7 @@ function checkParts(raw: unknown, path: string): PartsFile {
572
580
  return;
573
581
  }
574
582
  const r = p as Record<string, unknown>;
583
+ if ('depth' in r) problems.push(...partDepthProblems(r.depth, `${path} part depth`));
575
584
  const label = typeof r.name === 'string' ? `part "${r.name}"` : at;
576
585
  for (const k of Object.keys(r)) if (!(PART_KEYS as readonly string[]).includes(k)) fail('PARTS_KEY_KNOWN', `${label} key "${k}"`, `is not a part field; known: ${PART_KEYS.join(', ')}`);
577
586
  for (const k of REQUIRED_KEYS) if (!(k in r)) fail('PARTS_FIELD_PRESENT', `${label} field "${k}"`, 'is absent and required');
@@ -697,6 +706,11 @@ function checkParts(raw: unknown, path: string): PartsFile {
697
706
  if (typeof a !== 'object' || a === null || Array.isArray(a)) return;
698
707
  const set = a as Record<string, unknown>;
699
708
  const at = `${path} alternates[${i}]${typeof set.name === 'string' ? ` (set "${set.name}")` : ''}`;
709
+ if ('base_anchor' in set) {
710
+ const names = new Set(Array.isArray(set.records) ? set.records.flatMap(v => typeof v === 'object' && v !== null && typeof v.name === 'string' ? [v.name] : []) : []);
711
+ const patches = new Set(Array.isArray(set.records) ? set.records.flatMap(v => typeof v === 'object' && v !== null && typeof v.name === 'string' && typeof v.from === 'string' && v.from.startsWith('painting:') ? [v.name] : []) : []);
712
+ problems.push(...baseAnchorProblems(set.base_anchor, `${at}.base_anchor`, names, patches, undefined, 'PARTS_ALT_BASE_ANCHOR'));
713
+ }
700
714
  if (sizeOk && typeof scale === 'number') problems.push(...recordedFocusProblems(set, `${at}.focus`, size as number[], scale));
701
715
  if ('tips' in set || 'tips_source_size' in set) {
702
716
  const sourceSize = set.tips_source_size;
package/src/propose.ts CHANGED
@@ -291,7 +291,7 @@ export interface Proposal {
291
291
  /** Only with `propose --cloth` (issue #364, `src/cloth.ts`): the physics (and a skirt swing's transforms) of the trees it drafted; absent otherwise, so a proposal without it is the one written before it. */
292
292
  constraints?: ConfigConstraint[];
293
293
  /** Only with `propose --full`/`--head` (issue #251, {@link draftTurn}); absent otherwise, so a proposal without them is the one written before it. */
294
- turn?: TurnSpec;
294
+ turn?: TurnSpec & { pivot: number; depths: Record<string, number> };
295
295
  /** The `assemble.rig_scale` (`parts.json`'s `scale_rig_per_source`) its coordinates were drafted at (issue #354). */
296
296
  proposed_rig_scale: number;
297
297
  notes: string[];
@@ -524,7 +524,7 @@ export type TurnRuns = Partial<Record<'full' | 'head', LayerSet>>;
524
524
  * each carrier the other run places more than {@link TURN_RUN_APART} of the
525
525
  * span away.
526
526
  */
527
- export function draftTurn(P: PartSet, runs: TurnRuns, binds?: PartBinding): { turn: TurnSpec | null; notes: string[] } {
527
+ export function draftTurn(P: PartSet, runs: TurnRuns, binds?: PartBinding): { turn: (TurnSpec & { pivot: number; depths: Record<string, number> }) | null; notes: string[] } {
528
528
  P = P.beforeLimbs();
529
529
  const problems: Problem[] = [];
530
530
  const read: Array<{ part: string; run: 'full' | 'head'; tag: string; base: string | null; own: number; area: number; order: number; piece: boolean }> = [];
@@ -615,7 +615,7 @@ export function draftTurn(P: PartSet, runs: TurnRuns, binds?: PartBinding): { tu
615
615
  notes.push(`turn: every carried part lies at depth ${nearest.depth}, so none is nearer than the pivot and no turn control is drafted`);
616
616
  return { turn: null, notes };
617
617
  }
618
- const turn: TurnSpec = { pivot, depths };
618
+ const turn = { pivot, depths };
619
619
  const fr = turnFractions(turn, rows.map((r) => r.part));
620
620
  notes.push(
621
621
  `turn: control "${TURN_BONE}" under root, keyed by nothing — its x is the dial. Pivot depth ${pivot}: the mean of the ${rows.length} carried parts' depths weighted by opaque_px, the one depth at which the painted pixels' centroid does not slide (correct it in turn.pivot). ` +
@@ -651,7 +651,7 @@ export const TURN_DEPTH_CAVEAT: readonly string[] = [
651
651
  ];
652
652
 
653
653
  /** The proposal with `turn` written after `motion` and `notes` extended; the proposal itself when `turn` is null. */
654
- export function withTurn(p: Proposal, draft: { turn: TurnSpec | null; notes: string[] }): Proposal {
654
+ export function withTurn(p: Proposal, draft: { turn: (TurnSpec & { pivot: number; depths: Record<string, number> }) | null; notes: string[] }): Proposal {
655
655
  // Issue #349: a part a limb takes is not made; each of its limb parts carries its depth instead.
656
656
  let turn = draft.turn;
657
657
  if (turn !== null && p.limbs !== undefined) {
@@ -663,7 +663,7 @@ export function withTurn(p: Proposal, draft: { turn: TurnSpec | null; notes: str
663
663
  if (parts === undefined) depths[part] = d;
664
664
  else for (const q of parts) depths[q] = d;
665
665
  }
666
- turn = { pivot: turn.pivot, depths };
666
+ turn = { ...turn, pivot: turn.pivot, depths };
667
667
  }
668
668
  return { bones: p.bones, meshes: p.meshes, regions: p.regions, ...(p.limbs === undefined ? {} : { limbs: p.limbs }), ...(p.motion_seams === undefined ? {} : { motion_seams: p.motion_seams }), motion: p.motion, ...(p.constraints === undefined ? {} : { constraints: p.constraints }), ...(turn === null ? {} : { turn }), proposed_rig_scale: p.proposed_rig_scale, notes: [...p.notes, ...draft.notes] };
669
669
  }
package/src/rig.ts CHANGED
@@ -1,3 +1,5 @@
1
+ import { baseAnchorProblems, orderedBaseAnchor, baseAnchorMoves, type AnchorRegion } from './baseanchor.ts';
2
+ import { padDepthSheet, padTurnDepthSheet, depthSheetProblems, type PartDepthReference } from './depthsheets.ts';
1
3
  import { explicitBoneNames, explicitSlotBones, explicitWeightRows, regionBone } from './config.ts';
2
4
  import { explicitAttachment, type ExplicitMeshReport } from './explicitmesh.ts';
3
5
  /**
@@ -182,7 +184,7 @@ import { alphaAbove, crop, pad, type Raster } from './raster/index.ts';
182
184
  import { pyRound } from './round.ts';
183
185
  import { boneHeat, type HeatDust, heatInfluences, HEAT_LIMITS, heatRow, type HeatRow, latticeSilhouette, tracedSilhouette } from './heat.ts';
184
186
  import type { PosePoints } from './skeleton.ts';
185
- import { applyFaceSurfaceDeform, FACE_RATED_BAND, TURN_BONE, TURN_CARRIER_TAG, TURN_PLACES, TURN_RIDER_APART, TURN_RIDER_TAGS, turnRiderDepth, type TurnSpec, turnConstraintName, turnFractions, turnNearest, turnTwin } from './turn.ts';
187
+ import { applyFaceSurfaceDeform, buildDepth25DTurn, FACE_RATED_BAND, FACESHIFT_BONE, PITCH_DIAL_BONE, REAR_SHIFT_BONE, resolveTurnGrid, TURN_BONE, TURN_CARRIER_TAG, TURN_GRID_MAX_TRIANGLES_PER_SLOT, TURN_GRID_MAX_TRIANGLES_TOTAL, TURN_PLACES, TURN_RIDER_APART, TURN_RIDER_TAGS, turnRiderDepth, type TurnSpec, turnConstraintName, turnFractions, turnNearest, turnSurfaceBone, turnTwin, YAW_DIAL_BONE } from './turn.ts';
186
188
  import { DISTANCE_EXPONENT, type FloorForm, type Influence, influences, type InfluenceLimits, type MeshInfluences, meshLimits, type Segment } from './weights.ts';
187
189
 
188
190
  /** Transparent pixels added round every part image — the reference's `PAD`. */
@@ -500,6 +502,12 @@ export interface MeshAttachment {
500
502
  triangles: number[];
501
503
  hull: number;
502
504
  weights: WeightEntry[][];
505
+ generator?: {
506
+ kind: 'grid';
507
+ cols: number;
508
+ rows: number;
509
+ depth?: Omit<PartDepthReference, 'sources'>;
510
+ };
503
511
  }
504
512
 
505
513
  export interface RegionAttachment {
@@ -536,7 +544,14 @@ export interface RigSpec {
536
544
  * the idle keys a mesh-driving bone. `detached`: written only when a
537
545
  * constraint follows a bone ({@link detachedRules}).
538
546
  */
539
- invariants?: { idleDrivesMeshes?: { why: string }; detached?: DetachedRule[]; deformMayFold?: Array<{ slot: string; why: string }>; axes?: RigAxis[] };
547
+ invariants?: {
548
+ idleDrivesMeshes?: { why: string };
549
+ detached?: DetachedRule[];
550
+ deformMayFold?: Array<{ slot: string; why: string }>;
551
+ axes?: RigAxis[];
552
+ meshSlots?: number;
553
+ meshTriangles?: number;
554
+ };
540
555
  }
541
556
 
542
557
  /** One `invariants.detached` entry: rig-c's `RigDetachedRule`, checked by its gate rule `A25`. */
@@ -597,6 +612,9 @@ function signed4(v: number): string {
597
612
  * layer) is read by its tag, never by its bones, as `propose` reads it.
598
613
  */
599
614
  function turnRiderProblems(turn: TurnSpec, cfg: CharacterConfig, recs: PartsFile['parts']): Problem[] {
615
+ if (turn.depths === undefined || turn.pivot === undefined) return [];
616
+ const depths = turn.depths;
617
+ const pivot = turn.pivot;
600
618
  const baseOf = (from: string): string | null => {
601
619
  const t = tagOf(from);
602
620
  return t === null ? null : (readTag(t)?.base ?? null);
@@ -606,12 +624,12 @@ function turnRiderProblems(turn: TurnSpec, cfg: CharacterConfig, recs: PartsFile
606
624
  const b = baseOf(from);
607
625
  return faces.length === 1 && b !== null && TURN_RIDER_TAGS.includes(b);
608
626
  };
609
- const carried = recs.filter((r) => Object.hasOwn(turn.depths, r.name) && !tagRider(r.from));
627
+ const carried = recs.filter((r) => Object.hasOwn(depths, r.name) && !tagRider(r.from));
610
628
  const { riders } = turnRidersByBone(cfg, carried.map((r) => ({ part: r.name, area: r.opaque_px })));
611
629
  if (riders.size === 0) return [];
612
- const nearest = turnNearest(turn.depths);
630
+ const nearest = turnNearest(depths);
613
631
  if (nearest === null) return [];
614
- const span = turn.pivot - nearest.depth;
632
+ const span = pivot - nearest.depth;
615
633
  const order = recs.map((r) => r.name);
616
634
  const frac = new Map(turnFractions(turn, order).map((f) => [f.part, f.fraction]));
617
635
  const problems: Problem[] = [];
@@ -621,13 +639,13 @@ function turnRiderProblems(turn: TurnSpec, cfg: CharacterConfig, recs: PartsFile
621
639
  const diff = Math.abs(fp - fh);
622
640
  if (!(diff > TURN_RIDER_APART)) continue;
623
641
  const above = order.indexOf(part) > order.indexOf(ride.host);
624
- const want = pyRound(turnRiderDepth(turn.depths[ride.host], above), TURN_PLACES + 3);
642
+ const want = pyRound(turnRiderDepth(depths[ride.host], above), TURN_PLACES + 3);
625
643
  problems.push({
626
644
  code: 'CONFIG_TURN_RIDER_DEPTH',
627
645
  object: `config.turn.depths.${part}`,
628
646
  detail:
629
- `is ${turn.depths[part]}, fraction ${signed4(fp)} of the dial; "${part}" rides "${ride.host}" by bone — every ownable bone it binds (${ride.bones.join(', ')}) is hosted by "${ride.host}", the carried part binding it with the most opaque px — ` +
630
- `whose depth ${turn.depths[ride.host]} travels ${signed4(fh)}: the difference ${pyRound(diff, 4)} is more than ${TURN_RIDER_APART} of pivot − nearest (${turn.pivot} − ${nearest.depth} = ${pyRound(span, TURN_PLACES)}), so at the dial's x the part leaves what it rides by ${pyRound(diff, 4)} of it; ` +
647
+ `is ${depths[part]}, fraction ${signed4(fp)} of the dial; "${part}" rides "${ride.host}" by bone — every ownable bone it binds (${ride.bones.join(', ')}) is hosted by "${ride.host}", the carried part binding it with the most opaque px — ` +
648
+ `whose depth ${depths[ride.host]} travels ${signed4(fh)}: the difference ${pyRound(diff, 4)} is more than ${TURN_RIDER_APART} of pivot − nearest (${pivot} − ${nearest.depth} = ${pyRound(span, TURN_PLACES)}), so at the dial's x the part leaves what it rides by ${pyRound(diff, 4)} of it; ` +
631
649
  `the host's depth ${above ? '−' : '+'} 0.001 (${want}, drawn ${above ? 'above' : 'under'} it) is required, or redraft the turn with propose --full/--head`,
632
650
  });
633
651
  }
@@ -714,7 +732,7 @@ export function applyTurn(
714
732
  };
715
733
  for (const sl of mine) {
716
734
  bind(sl.bone);
717
- for (const att of Object.values(skin[sl.name] ?? {})) if ('type' in att) for (const v of att.weights) for (const w of v) bind(w.bone);
735
+ for (const att of Object.values(skin[sl.name] ?? {})) if ('type' in att && att.weights !== undefined) for (const v of att.weights) for (const w of v) bind(w.bone);
718
736
  }
719
737
  for (const b of bound) orderOf(b);
720
738
  if (orderByDeclaration) bound.sort((a, b) => orderOf(a) - orderOf(b));
@@ -741,7 +759,7 @@ export function applyTurn(
741
759
  sl.bone = twinOf.get(sl.bone) as string;
742
760
  const atts = skin[sl.name] ?? {};
743
761
  for (const [k, att] of Object.entries(atts)) {
744
- if ('type' in att) atts[k] = { ...att, weights: att.weights.map((v) => v.map((w) => ({ ...w, bone: twinOf.get(w.bone) as string }))) };
762
+ if ('type' in att && att.weights !== undefined) atts[k] = { ...att, weights: att.weights.map((v) => v.map((w) => ({ ...w, bone: twinOf.get(w.bone) as string }))) };
745
763
  }
746
764
  }
747
765
  const cname = turnConstraintName(row.part);
@@ -813,7 +831,7 @@ export const IDLE_DRIVES_MESHES_WHY = 'painting rig: the idle is meant to deform
813
831
  * every mode; `remesh --delta`'s row (`deltaRow`, `src/remesh.ts`) takes the same function.
814
832
  */
815
833
  export function meshBoundBones(att: Pick<MeshAttachment, 'weights'>): string[] {
816
- return [...new Set(att.weights.flatMap((w) => w.map((e) => e.bone)))].sort();
834
+ return [...new Set((att.weights ?? []).flatMap((w) => w.map((e) => e.bone)))].sort();
817
835
  }
818
836
 
819
837
  /** One row of `mesh_report.json`: a lattice mesh's row is as it always was; a contour mesh's says so. */
@@ -1110,6 +1128,7 @@ export interface AttachmentSetsFile {
1110
1128
  }
1111
1129
 
1112
1130
  export interface RigOutput {
1131
+ depthReferences?: Array<{ part: string; size: [number, number]; depth: PartDepthReference }>;
1113
1132
  rig: RigSpec;
1114
1133
  /** Internal explicit-layout provenance; serialized only as an external companion. */
1115
1134
  layout?: LayoutPlan;
@@ -1303,11 +1322,27 @@ export function buildRig(
1303
1322
  const CX = W / 2;
1304
1323
  const byPart = new Map(parts.parts.map((p) => [p.name, p]));
1305
1324
 
1325
+ const configuredAlts = cfg.assemble.alternates ?? cfg.alternates ?? [];
1326
+ const anchorRegions = new Set(Object.keys(cfg.regions).filter(n => !(n in cfg.meshes)));
1327
+ for (const a of configuredAlts) {
1328
+ if (a.base_anchor === undefined) continue;
1329
+ const covered = new Set((a.parts ?? parts.parts.map(p => p.name)).filter(n => !(a.hides ?? []).includes(n)));
1330
+ problems.push(...baseAnchorProblems(a.base_anchor, `config alternate set "${a.name}".base_anchor`, covered, new Set((cfg.assemble.patches ?? []).map(p => p.name)), anchorRegions, 'RIG_ALT_BASE_ANCHOR'));
1331
+ }
1306
1332
  for (const a of parts.alternates ?? []) {
1333
+ if (a.base_anchor !== undefined) problems.push(...baseAnchorProblems(a.base_anchor, `parts.json alternate set "${a.name}".base_anchor`, new Set(a.records.map(p => p.name)), new Set(a.records.filter(p => p.from.startsWith('painting:')).map(p => p.name)), anchorRegions, 'RIG_ALT_BASE_ANCHOR'));
1334
+ }
1335
+ // Direct callers need the same shape checks as serialized readers. Collect
1336
+ // both sides before any canonical ordering can inspect their axes or pairs.
1337
+ refuseIfAny(problems);
1338
+ for (const a of parts.alternates ?? []) {
1339
+ const configured = configuredAlts.find(c => c.name === a.name)?.base_anchor;
1340
+ if (JSON.stringify(configured === undefined ? null : orderedBaseAnchor(configured)) !== JSON.stringify(a.base_anchor === undefined ? null : orderedBaseAnchor(a.base_anchor))) fail('RIG_ALT_BASE_ANCHOR_MATCH_CONFIG', `alternate set "${a.name}" base_anchor`, 'config and parts.json declare different base anchors; re-run assemble before rig');
1307
1341
  problems.push(...recordedFocusProblems(a, `parts.json alternate set "${a.name}".focus`, parts.rig_size, parts.scale_rig_per_source));
1308
1342
  }
1309
1343
  for (const a of cfg.assemble.alternates ?? cfg.alternates ?? []) {
1310
1344
  const record = parts.alternates?.find((p) => p.name === a.name);
1345
+ if (a.base_anchor !== undefined && record === undefined) fail('RIG_ALT_BASE_ANCHOR_MATCH_CONFIG', `alternate set "${a.name}" base_anchor`, 'has no assembled set; re-run assemble before rig');
1311
1346
  if ((a.focus !== undefined || record?.focus !== undefined)
1312
1347
  && JSON.stringify(a.focus) !== JSON.stringify(record?.focus)) {
1313
1348
  fail('CONFIG_SET_FOCUS', `config.assemble alternate set "${a.name}".focus`, 'does not match the assembled painting point; re-run assemble after changing or removing focus');
@@ -1833,6 +1868,21 @@ export function buildRig(
1833
1868
  const skin: RigSpec['skins']['default'] = {};
1834
1869
  const meshReport: MeshReport[] = [];
1835
1870
  const outImages: Array<[string, Raster]> = [];
1871
+ const depthReferences: NonNullable<RigOutput['depthReferences']> = [];
1872
+ const emitDepth = (part: string, reference: PartDepthReference, scalar: Raster): void => {
1873
+ if (outImages.some(([file]) => file === reference.image)) {
1874
+ fail('DEPTH_SHEET_UNAMBIGUOUS', reference.image, 'collides with an emitted asset; choose noncolliding part/sheet names');
1875
+ return;
1876
+ }
1877
+ const art = images.get(part);
1878
+ const image =
1879
+ cfg.turn?.roles?.[part] !== undefined && art !== undefined && art.width === scalar.width && art.height === scalar.height
1880
+ ? padTurnDepthSheet(scalar, art, PAD)
1881
+ : padDepthSheet(scalar, PAD);
1882
+ outImages.push([reference.image, image]);
1883
+ depthReferences.push({ part, size: [image.width, image.height], depth: reference });
1884
+ };
1885
+
1836
1886
  const loopPasses: Record<string, number> = {};
1837
1887
  const autoMotion: AutoMotionCase[] = [];
1838
1888
  // A region's centre in its bone's setup frame; on a turned bone the image
@@ -2333,9 +2383,59 @@ export function buildRig(
2333
2383
  for (const p of parts.parts) {
2334
2384
  const img = pad(images.get(p.name) as Raster, PAD, PAD, PAD, PAD, [0, 0, 0, 0]);
2335
2385
  const file = `${p.name}.png`;
2386
+ const artIndex = outImages.length;
2336
2387
  outImages.push([file, img]);
2388
+ const scalar = p.depth === undefined ? undefined : images.get(p.depth.image);
2389
+ if (p.depth !== undefined) {
2390
+ if (scalar === undefined) fail('DEPTH_SHEET_PRESENT', p.depth.image, `part "${p.name}" declares a sheet; the unpadded source sheet must be handed to buildRig`);
2391
+ else {
2392
+ problems.push(...depthSheetProblems(scalar, [p.w, p.h], p.depth.image));
2393
+ if (parts.parts.some(q => `${q.name}.png` === p.depth?.image)) fail('DEPTH_SHEET_UNAMBIGUOUS', p.depth.image, 'collides with artwork; use noncolliding part names');
2394
+ else if (cfg.meshes[p.name] !== undefined || stills[p.name] === undefined) emitDepth(p.name, p.depth, scalar);
2395
+ }
2396
+ }
2397
+
2337
2398
  const mesh = cfg.meshes[p.name];
2338
2399
  if (mesh === undefined) {
2400
+ if (cfg.turn?.roles?.[p.name] === 'surface') {
2401
+ if (p.depth === undefined || scalar === undefined) {
2402
+ fail(
2403
+ 'RIG_TURN_SURFACE_DEPTH_REQUIRED',
2404
+ `config.turn.roles.${p.name}`,
2405
+ `declares role "surface" for "${p.name}", which requires a depth sheet in parts.json; run assemble with config.depth or provide "${p.name}_depth.png"`,
2406
+ );
2407
+ continue;
2408
+ }
2409
+ const [cols, rows] = resolveTurnGrid(cfg.turn, p.name);
2410
+ const triCount = 2 * (cols - 1) * (rows - 1);
2411
+ if (triCount > TURN_GRID_MAX_TRIANGLES_PER_SLOT) {
2412
+ fail(
2413
+ 'RIG_TURN_GRID_BUDGET',
2414
+ `config.turn.grid (${p.name})`,
2415
+ `specifies a ${cols}x${rows} grid (${triCount} triangles), which exceeds the per-slot budget of ${TURN_GRID_MAX_TRIANGLES_PER_SLOT} triangles`,
2416
+ );
2417
+ continue;
2418
+ }
2419
+ const surfBone = turnSurfaceBone(p.name);
2420
+ const { sources: _sources, ...coreDepth } = p.depth;
2421
+ const gridAtt: Omit<MeshAttachment, 'uvs' | 'triangles' | 'hull' | 'weights'> = {
2422
+ type: 'mesh',
2423
+ image: file,
2424
+ width: img.width,
2425
+ height: img.height,
2426
+ generator: {
2427
+ kind: 'grid',
2428
+ cols,
2429
+ rows,
2430
+ depth: coreDepth,
2431
+ },
2432
+ };
2433
+ skin[p.name] = {
2434
+ [p.name]: gridAtt as MeshAttachment,
2435
+ };
2436
+ addSlots(p.name, { name: p.name, bone: surfBone, attachment: p.name });
2437
+ continue;
2438
+ }
2339
2439
  const bone = B.get(regionBone(cfg.regions[p.name])) as Bone;
2340
2440
  const cx = p.x + p.w / 2;
2341
2441
  const st = stills[p.name];
@@ -2350,8 +2450,15 @@ export function buildRig(
2350
2450
  const lower = pad(crop(src, 0, r, p.w, p.h - r), PAD, PAD, PAD, PAD, [0, 0, 0, 0]);
2351
2451
  const upper = pad(crop(src, 0, 0, p.w, r), PAD, PAD, PAD, PAD, [0, 0, 0, 0]);
2352
2452
  const sb = B.get(st.bone) as Bone;
2353
- outImages[outImages.length - 1] = [file, lower];
2453
+ outImages[artIndex] = [file, lower];
2354
2454
  outImages.push([stillFile, upper]);
2455
+ if (p.depth !== undefined && scalar !== undefined) {
2456
+ // The SAME source row r as the art; each drawing owns a distinct
2457
+ // padded scalar grid, while original-source provenance stays intact.
2458
+ emitDepth(p.name, p.depth, crop(scalar, 0, r, p.w, p.h - r));
2459
+ emitDepth(still, { ...p.depth, image: `${still}_depth.png` }, crop(scalar, 0, 0, p.w, r));
2460
+ }
2461
+
2355
2462
  const cyLow = st.row + (p.h - r) / 2;
2356
2463
  const cyUp = p.y + r / 2;
2357
2464
  skin[p.name] = { [p.name]: region(file, bone.name, cx, cyLow) };
@@ -2646,6 +2753,12 @@ export function buildRig(
2646
2753
  const img = pad(rawImg, PAD, PAD, PAD, PAD, [0, 0, 0, 0]);
2647
2754
  const file = `${attName}.png`;
2648
2755
  outImages.push([file, img]);
2756
+ if (p.depth !== undefined) {
2757
+ const scalar = images.get(p.depth.image);
2758
+ if (scalar === undefined) fail('DEPTH_SHEET_PRESENT', p.depth.image, `alternate "${attName}" requires its declared source sheet`);
2759
+ else { problems.push(...depthSheetProblems(scalar, [p.w, p.h], p.depth.image)); emitDepth(attName, p.depth, scalar); }
2760
+ }
2761
+
2649
2762
  const mesh = cfg.meshes[p.name];
2650
2763
  if (mesh === undefined) {
2651
2764
  const bone = B.get(regionBone(cfg.regions[p.name])) as Bone;
@@ -2659,7 +2772,7 @@ export function buildRig(
2659
2772
  const fullSegs = meshSegments.get(p.name) as Segment[];
2660
2773
  const explicitSegments = new Map(fullSegs.map((s, k) => [s, typeof mesh.segments[(meshSegmentEntries.get(p.name) as number[])[k]] !== 'string']));
2661
2774
  const baseAtt = skin[p.name]?.[p.name];
2662
- const baseBones = baseAtt !== undefined && 'type' in baseAtt ? new Set(baseAtt.weights.flatMap((v) => v.map((e) => e.bone))) : null;
2775
+ const baseBones = baseAtt !== undefined && 'type' in baseAtt ? new Set((baseAtt.weights ?? []).flatMap((v) => v.map((e) => e.bone))) : null;
2663
2776
  const filteredSegs = baseBones !== null && baseBones.size > 0 ? fullSegs.filter((s) => baseBones.has(s.bone)) : fullSegs;
2664
2777
  let segs = filteredSegs.length > 0 ? filteredSegs : fullSegs;
2665
2778
  if (drawn !== undefined) {
@@ -2771,6 +2884,22 @@ export function buildRig(
2771
2884
  for (const [x, y] of lm.vertices) uvs.push(pyRound(x / w, 6), pyRound(y / h, 6));
2772
2885
  skin[skinSlot][attName] = { type: 'mesh', image: file, width: w, height: h, uvs, triangles: lm.triangles, hull: lm.hull, weights };
2773
2886
  }
2887
+ if (alt.base_anchor !== undefined) {
2888
+ const baseRegions = new Map<string, AnchorRegion>(), altRegions = new Map<string, AnchorRegion>();
2889
+ for (const p of alt.records) {
2890
+ if (cfg.meshes[p.name] !== undefined || cfg.regions[p.name] === undefined) continue;
2891
+ const bone = regionBone(cfg.regions[p.name]), slot = altFront.has(p.name) ? `${p.name}${FRONT_SUFFIX}` : p.name;
2892
+ const original = skin[p.name]?.[p.name], art = skin[slot]?.[`${alt.name}_${p.name}`];
2893
+ if (original !== undefined && !('type' in original)) baseRegions.set(p.name, { bone, x: original.x, y: original.y });
2894
+ if (art !== undefined && !('type' in art)) altRegions.set(p.name, { bone, x: art.x, y: art.y });
2895
+ }
2896
+ const moves = baseAnchorMoves(alt.base_anchor, baseRegions, altRegions, altWorld);
2897
+ for (const [name, move] of moves) {
2898
+ const slot = altFront.has(name) ? `${name}${FRONT_SUFFIX}` : name;
2899
+ const attachment = skin[slot][`${alt.name}_${name}`] as RegionAttachment;
2900
+ skin[slot][`${alt.name}_${name}`] = { ...attachment, x: places(attachment.x + move.local[0]), y: places(attachment.y + move.local[1]) };
2901
+ }
2902
+ }
2774
2903
  const slotMap: Record<string, string> = {};
2775
2904
  for (const [slotName, att] of Object.entries(alt.slots)) slotMap[slotName] = att;
2776
2905
  const hideList: string[] = [];
@@ -2786,6 +2915,7 @@ export function buildRig(
2786
2915
  const coversFace = Object.hasOwn(slotMap, 'face');
2787
2916
  setEntries[alt.name] = {
2788
2917
  slots: slotMap,
2918
+ ...(alt.base_anchor === undefined ? {} : { base_anchor: orderedBaseAnchor(alt.base_anchor) }),
2789
2919
  ...(alt.focus === undefined ? {} : { focus: paintingToSetupPoint(alt.focus, alt.focus_source_size as [number, number], parts.rig_size) }),
2790
2920
  ...(hideList.length > 0 ? { hides: hideList } : {}),
2791
2921
  ...(drawn === undefined ? {} : { drawn }),
@@ -2852,8 +2982,136 @@ export function buildRig(
2852
2982
  // ---- the turn control (issue #251) -------------------------------------
2853
2983
  // Only when the config has `turn`: every other build adds nothing here, so no byte moves.
2854
2984
  if (cfg.turn !== undefined) refuseIfAny(turnRiderProblems(cfg.turn, cfg, parts.parts));
2855
- const turned = cfg.turn === undefined ? null : applyTurn(cfg.turn, parts.parts.map((p) => p.name), bones, rebound, skin, cfg.constraints ?? [], declaredFront, slotFamilies, stops, turnOrderByDeclaration);
2985
+ const turned = cfg.turn === undefined || cfg.turn.roles !== undefined ? null : applyTurn(cfg.turn, parts.parts.map((p) => p.name), bones, rebound, skin, cfg.constraints ?? [], declaredFront, slotFamilies, stops, turnOrderByDeclaration);
2856
2986
  for (const row of turned?.rows ?? []) for (const t of row.twins) layoutAlias(explicitLayout.plan, t.bone, t.twin);
2987
+ const finalSlots = frontSlots.length === 0 ? explicitLayout.slots : spliceFrontSlots(explicitLayout.slots, frontSlots, frontTargets, slotFamilies);
2988
+ let generatedMeshBudget: { meshSlots: number; meshTriangles: number } | null = null;
2989
+ if (cfg.turn?.roles !== undefined) {
2990
+ const roles = cfg.turn.roles;
2991
+ let totalGridTriangles = 0;
2992
+ const headIdx = bones.findIndex((b) => b.name === 'head');
2993
+ if (headIdx === -1) {
2994
+ fail('RIG_TURN_HEAD_BONE', 'config.turn.roles', 'requires a declared "head" bone in config.bones to parent the 2.5D turn carriers');
2995
+ } else {
2996
+ const headTransform = world.get('head') as BoneTransform;
2997
+ const headTurnDeg = turn.get('head') ?? 0;
2998
+ const surfBones: RigBone[] = [];
2999
+ for (const p of parts.parts) {
3000
+ if (roles[p.name] !== 'surface' || cfg.meshes[p.name] !== undefined) continue;
3001
+ const [cols, rows] = resolveTurnGrid(cfg.turn, p.name);
3002
+ totalGridTriangles += 2 * (cols - 1) * (rows - 1);
3003
+ const cx = p.x + p.w / 2;
3004
+ const cy = p.y + p.h / 2;
3005
+ const [lx, ly] = toBoneLocal(headTransform, spineX(cx), spineY(cy));
3006
+ const rot = places(normaliseDegrees(-headTurnDeg));
3007
+ surfBones.push({
3008
+ name: turnSurfaceBone(p.name),
3009
+ parent: FACESHIFT_BONE,
3010
+ x: places(lx),
3011
+ y: places(ly),
3012
+ ...(rot === 0 ? {} : { rotation: rot }),
3013
+ });
3014
+ }
3015
+ if (totalGridTriangles > TURN_GRID_MAX_TRIANGLES_TOTAL) {
3016
+ fail(
3017
+ 'RIG_TURN_GRID_BUDGET',
3018
+ 'config.turn.grid',
3019
+ `allocates ${totalGridTriangles} total grid triangles across surface slots, which exceeds the total budget of ${TURN_GRID_MAX_TRIANGLES_TOTAL} triangles`,
3020
+ );
3021
+ }
3022
+ const hasRear = Object.values(roles).includes('rear');
3023
+ const carriers: RigBone[] = [
3024
+ { name: FACESHIFT_BONE, parent: 'head', x: 0, y: 0 },
3025
+ ...(hasRear ? [{ name: REAR_SHIFT_BONE, parent: 'head', x: 0, y: 0 }] : []),
3026
+ ...surfBones,
3027
+ ];
3028
+ bones.splice(headIdx + 1, 0, ...carriers);
3029
+ const existingNames = new Set(bones.map((b) => b.name));
3030
+ if (!existingNames.has(YAW_DIAL_BONE)) bones.push({ name: YAW_DIAL_BONE, parent: ROOT_BONE, x: 0, y: 0 });
3031
+ if (!existingNames.has(PITCH_DIAL_BONE)) bones.push({ name: PITCH_DIAL_BONE, parent: ROOT_BONE, x: 0, y: 0 });
3032
+
3033
+ const boneByName = new Map(bones.map((b) => [b.name, b]));
3034
+ const slotByName = new Map(finalSlots.map((s) => [s.name, s]));
3035
+ const reparentFromHead = (boneName: string, targetParent: string): void => {
3036
+ const b = boneByName.get(boneName);
3037
+ if (b !== undefined && b.parent === 'head') b.parent = targetParent;
3038
+ };
3039
+ const rebindPartToCarrier = (part: string, carrierBone: string): void => {
3040
+ const sl = slotByName.get(part);
3041
+ if (sl !== undefined && sl.bone === 'head') sl.bone = carrierBone;
3042
+ const stillSl = slotByName.get(`${part}${STILL_SUFFIX}`);
3043
+ if (stillSl !== undefined) {
3044
+ if (stillSl.bone === 'head') stillSl.bone = carrierBone;
3045
+ else reparentFromHead(stillSl.bone, carrierBone);
3046
+ }
3047
+ const atts = skin[part] ?? {};
3048
+ for (const att of Object.values(atts)) {
3049
+ if (!('type' in att) || att.weights === undefined) continue;
3050
+ for (const row of att.weights) {
3051
+ for (const w of row) {
3052
+ if (w.bone === 'head') {
3053
+ w.bone = carrierBone;
3054
+ } else {
3055
+ // Find the ancestor of w.bone that hangs directly under head and reparent it to carrierBone.
3056
+ let cur = boneByName.get(w.bone);
3057
+ while (cur !== undefined && cur.parent !== undefined && cur.parent !== 'head' && cur.parent !== carrierBone) {
3058
+ cur = boneByName.get(cur.parent);
3059
+ }
3060
+ if (cur !== undefined && cur.parent === 'head') cur.parent = carrierBone;
3061
+ }
3062
+ }
3063
+ }
3064
+ }
3065
+ };
3066
+
3067
+ for (const [part, role] of Object.entries(roles)) {
3068
+ if (role === 'unit') {
3069
+ if (cfg.regions[part] !== undefined) {
3070
+ const bName = regionBone(cfg.regions[part]);
3071
+ if (bName === 'head') {
3072
+ const sl = slotByName.get(part);
3073
+ if (sl !== undefined) sl.bone = FACESHIFT_BONE;
3074
+ } else {
3075
+ reparentFromHead(bName, FACESHIFT_BONE);
3076
+ }
3077
+ const st = stills[part];
3078
+ if (st !== undefined) reparentFromHead(st.bone, FACESHIFT_BONE);
3079
+ } else if (cfg.meshes[part] !== undefined) {
3080
+ rebindPartToCarrier(part, FACESHIFT_BONE);
3081
+ }
3082
+ } else if (role === 'rear' && hasRear) {
3083
+ if (cfg.regions[part] !== undefined) {
3084
+ const bName = regionBone(cfg.regions[part]);
3085
+ if (bName === 'head') {
3086
+ const sl = slotByName.get(part);
3087
+ if (sl !== undefined) sl.bone = REAR_SHIFT_BONE;
3088
+ } else {
3089
+ reparentFromHead(bName, REAR_SHIFT_BONE);
3090
+ }
3091
+ } else if (cfg.meshes[part] !== undefined) {
3092
+ rebindPartToCarrier(part, REAR_SHIFT_BONE);
3093
+ }
3094
+ }
3095
+ }
3096
+
3097
+ let meshSlots = 0;
3098
+ let meshTriangles = 0;
3099
+ for (const atts of Object.values(skin)) {
3100
+ let slotHasMesh = false;
3101
+ for (const att of Object.values(atts)) {
3102
+ if (!('type' in att)) continue;
3103
+ slotHasMesh = true;
3104
+ const tris =
3105
+ att.generator?.kind === 'grid'
3106
+ ? 2 * (att.generator.cols - 1) * (att.generator.rows - 1)
3107
+ : (att.triangles?.length ?? 0) / 3;
3108
+ if (tris > meshTriangles) meshTriangles = tris;
3109
+ }
3110
+ if (slotHasMesh) meshSlots++;
3111
+ }
3112
+ generatedMeshBudget = { meshSlots, meshTriangles };
3113
+ }
3114
+ }
2857
3115
  // issue #536: every row names the bones the emitted attachment binds, read once the turn and the stops have
2858
3116
  // rebound the weights; a rig with neither rebinds nothing, so this reads back the names each row already holds.
2859
3117
  for (const row of meshReport) {
@@ -2870,6 +3128,15 @@ export function buildRig(
2870
3128
  const att = skin[row.part]?.[row.part];
2871
3129
  if (att !== undefined && 'type' in att) row.bones = meshBoundBones(att);
2872
3130
  }
3131
+ // Check the complete namespace: an alternate's art can arrive after a base
3132
+ // sheet (or a still asset) with the same filename. Never let write order
3133
+ // decide which drawing or measurement survives on disk.
3134
+ const assetIndices = new Map<string, number>();
3135
+ outImages.forEach(([file], index) => {
3136
+ const previous = assetIndices.get(file);
3137
+ if (previous !== undefined) fail('DEPTH_SHEET_UNAMBIGUOUS', file, `output assets[${previous}] and [${index}] require the same filename; choose distinct base, still, alternate and sheet names`);
3138
+ else assetIndices.set(file, index);
3139
+ });
2873
3140
  refuseIfAny(problems);
2874
3141
  const name = `${cfg.key}_painting`;
2875
3142
  const rig: RigSpec = {
@@ -2878,7 +3145,7 @@ export function buildRig(
2878
3145
  images: 'images',
2879
3146
  skeleton: { x: -CX, y: 0, width: W, height: H },
2880
3147
  bones,
2881
- slots: frontSlots.length === 0 ? explicitLayout.slots : spliceFrontSlots(explicitLayout.slots, frontSlots, frontTargets, slotFamilies),
3148
+ slots: finalSlots,
2882
3149
  skins: { default: skin },
2883
3150
  };
2884
3151
  if (cfg.constraints !== undefined) rig.constraints = cfg.constraints.map(constraintForRig);
@@ -2893,23 +3160,53 @@ export function buildRig(
2893
3160
  // issue #239: the face's line, written only when the face bones were turned to one, so no other rig moves.
2894
3161
  const axes = [faceAxis.axis, faceAxis.tipAxis].flatMap((x) => (x === null ? [] : [x]));
2895
3162
  if (axes.length > 0) rig.invariants = { ...rig.invariants, axes };
3163
+ if (generatedMeshBudget !== null) {
3164
+ rig.invariants = { ...rig.invariants, ...generatedMeshBudget };
3165
+ }
2896
3166
  const faceImg = outImages.find(([k]) => k === 'face.png')?.[1];
2897
3167
  const facePart = parts.parts.find((p) => p.name === 'face');
2898
3168
  const partAreas: Record<string, number> = {};
2899
3169
  for (const p of parts.parts) partAreas[p.name] = p.opaque_px;
2900
- bindFaceSurfaceDeform(motion, (merged) => {
2901
- expandSetAttachmentKeys(rig, sets, merged);
2902
- applyFaceSurfaceDeform(rig, merged, {
2903
- imageWidth: faceImg?.width,
2904
- imageHeight: faceImg?.height,
2905
- opaqueWidth: facePart?.w,
2906
- opaqueHeight: facePart?.h,
2907
- overrides: cfg.turn?.deform,
2908
- hasAlternateFaceSet,
3170
+ const boneLandmarks = new Map<string, readonly [number, number]>();
3171
+ for (const [bName, bEntry] of B) {
3172
+ boneLandmarks.set(bName, [bEntry.x, bEntry.y]);
3173
+ }
3174
+ if (cfg.turn?.roles !== undefined) {
3175
+ buildDepth25DTurn(rig, motion, {
2909
3176
  turn: cfg.turn,
2910
- partAreas,
2911
- requireTurn: true,
3177
+ parts: parts.parts,
3178
+ images,
3179
+ regions: cfg.regions,
3180
+ stills,
3181
+ boneLandmarks,
3182
+ hasAlternateFaceSet,
2912
3183
  });
3184
+ }
3185
+ bindFaceSurfaceDeform(motion, (merged) => {
3186
+ expandSetAttachmentKeys(rig, sets, merged);
3187
+ if (cfg.turn?.roles !== undefined) {
3188
+ buildDepth25DTurn(rig, merged, {
3189
+ turn: cfg.turn,
3190
+ parts: parts.parts,
3191
+ images,
3192
+ regions: cfg.regions,
3193
+ stills,
3194
+ boneLandmarks,
3195
+ hasAlternateFaceSet,
3196
+ });
3197
+ } else {
3198
+ applyFaceSurfaceDeform(rig, merged, {
3199
+ imageWidth: faceImg?.width,
3200
+ imageHeight: faceImg?.height,
3201
+ opaqueWidth: facePart?.w,
3202
+ opaqueHeight: facePart?.h,
3203
+ overrides: cfg.turn?.deform,
3204
+ hasAlternateFaceSet,
3205
+ turn: cfg.turn,
3206
+ partAreas,
3207
+ requireTurn: true,
3208
+ });
3209
+ }
2913
3210
  if (sets !== undefined && (merged.animations.turn !== undefined || merged.animations.tilt !== undefined)) {
2914
3211
  for (const entry of Object.values(sets.sets)) {
2915
3212
  if (Object.hasOwn(entry.slots, 'face')) {
@@ -2923,6 +3220,7 @@ export function buildRig(
2923
3220
  motion,
2924
3221
  meshReport,
2925
3222
  images: outImages,
3223
+ ...(depthReferences.length === 0 ? {} : { depthReferences }),
2926
3224
  controls,
2927
3225
  meshKeyed,
2928
3226
  idleKeys,