@rig-c/parts 1.67.0 → 1.68.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/build.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { readSourceDepth } from './depthsheets.ts';
1
2
  import { alternateLayerSources, alternateLayerIslands, alternateLayerOthers } from './alternatelayers.ts';
2
3
  import { setFocusProblems } from './setfocus.ts';
3
4
  /**
@@ -49,7 +50,7 @@ import { type AnimFrame, EncodeError, encodeApng, encodeIndexedApng, INDEXED_DEF
49
50
  import { assemble, type AssembleResult, cutLines, type ExcludedCount, excludedLines, setExclusions, islandLines, setIslandSources, type IslandCount, hiddenLines, SINGLE_RUN_FACE_TAGS, singleRunHeadBox, driftLine, limbLines, FIGURE_MASK_FILE, figuresLine, holeKindsLine, holeLines, measureRecomposite, type ProjectRule, recomposite, recompositeRecord, scenePhrase, type SeamRule, sourceInRig, stageFields, uncoveredLine } from './assemble.ts';
50
51
  import { allocationClause, type Reducer, stageBClause, unboundedClause } from './automesh.ts';
51
52
  import { residualClause } from './autoenvelope.ts';
52
- import { type AutoMotionCase, failingRows, idleSchedule, localRow, motionClause, motionDeformation, motionDocument, motionInput, motionRowText, motionStimulus, motionVerdict, noStimulusProblem, type ReplayCandidate, runComparison, sourceSelfFailure, stimulusMotion, withStimulus } from './automotion.ts';
53
+ import { type AutoMotionCase, failingRows, idleSchedule, localRow, motionClause, motionDeformation, motionDocument, motionInput, motionRowText, motionStimulus, motionVerdict, noStimulusProblem, prepareComparison, type ReplayCandidate, runComparison, runPreparedComparison, sourceSelfFailure, stimulusMotion, withStimulus } from './automotion.ts';
53
54
  import {
54
55
  bisectAccepted,
55
56
  budgetProblem,
@@ -321,7 +322,7 @@ export function assembleStage(input: AssembleStageInput, outs: AssembleOutputs,
321
322
  const fields = stageFields(cfg, runs.single ? { w: src.width, h: src.height } : null);
322
323
  const under = readUnders(input.config, fields.cuts);
323
324
  const caps = fields.limbs === undefined ? undefined : readCaps(input.config, fields.limbs);
324
- const result = assemble({ source: src, full: runs.full, head: runs.head, ...fields, under, ...(caps === undefined ? {} : { caps }), seamRule: input.seam, projectRule: input.project });
325
+ const result = assemble({ source: src, full: runs.full, head: runs.head, depth: cfg.depth, depthBase: dirname(resolve(input.config)), ...fields, under, ...(caps === undefined ? {} : { caps }), seamRule: input.seam, projectRule: input.project });
325
326
 
326
327
  // Issue #454: alternate painting sets, assembled before any file is written.
327
328
  const configDir = dirname(resolve(input.config));
@@ -635,6 +636,7 @@ export function assembleStage(input: AssembleStageInput, outs: AssembleOutputs,
635
636
  try {
636
637
  altRes = assemble({
637
638
  source: altSrc,
639
+ depth: cfg.depth, depthBase: configDir,
638
640
  limbUnderCover: alt.parts !== undefined && input.setCover !== 'painting',
639
641
  ...(altTips === undefined ? {} : { boneTips: altTips }),
640
642
  capOwnership: input.setCapOwnership ?? 'target',
@@ -674,8 +676,8 @@ export function assembleStage(input: AssembleStageInput, outs: AssembleOutputs,
674
676
  }
675
677
  const keptImages = altRes.images
676
678
  .filter(({ record }) => coveredSet.has(record.name))
677
- .map(({ record, image }) => ({ name: `${alt.name}_${record.name}`, image }));
678
- const keptRecords = altRes.parts.parts.filter((p) => coveredSet.has(p.name));
679
+ .flatMap(({ record, image, depthImage }) => [{ name: `${alt.name}_${record.name}`, image }, ...(depthImage === undefined || record.depth === undefined ? [] : [{ name: `${alt.name}_${record.depth.image.slice(0, -4)}`, image: depthImage }])]);
680
+ const keptRecords = altRes.parts.parts.filter((p) => coveredSet.has(p.name)).map(p => p.depth === undefined ? p : { ...p, depth: { ...p.depth, image: `${alt.name}_${p.depth.image}` } });
679
681
  const slots: Record<string, string> = {};
680
682
  for (const r of keptRecords) slots[altFront.has(r.name) ? `${r.name}${FRONT_SUFFIX}` : r.name] = `${alt.name}_${r.name}`;
681
683
  let altRecomposite = altRes.parts.recomposite as RecompositeRecord;
@@ -715,6 +717,26 @@ export function assembleStage(input: AssembleStageInput, outs: AssembleOutputs,
715
717
  capSplits: altRes.capSplits,
716
718
  });
717
719
  }
720
+ const emittedAssets = [
721
+ ...result.images.flatMap(({ record, depthImage }) => [
722
+ `${record.name}.png`,
723
+ ...(depthImage !== undefined && record.depth !== undefined ? [record.depth.image] : []),
724
+ ]),
725
+ ...altBuilt.flatMap((b) => b.images.map(({ name }) => `${name}.png`)),
726
+ ];
727
+ const assetIndices = new Map<string, number>();
728
+ emittedAssets.forEach((file, index) => {
729
+ const previous = assetIndices.get(file);
730
+ if (previous !== undefined) {
731
+ altProblems.push({
732
+ code: 'DEPTH_SHEET_UNAMBIGUOUS',
733
+ object: file,
734
+ detail: `output assets[${previous}] and [${index}] require the same filename; choose distinct base, alternate and sheet names`,
735
+ });
736
+ } else {
737
+ assetIndices.set(file, index);
738
+ }
739
+ });
718
740
  refuseIfAny(altProblems);
719
741
  if (altBuilt.length > 0) {
720
742
  result.parts.alternates = altBuilt.map((b) => b.record);
@@ -726,7 +748,11 @@ export function assembleStage(input: AssembleStageInput, outs: AssembleOutputs,
726
748
  mkdirSync(dirname(outs.recomposite), { recursive: true });
727
749
  mkdirSync(dirname(outs.errorMap), { recursive: true });
728
750
  writeParts(outs.partsJson, result.parts);
729
- for (const { record, image } of result.images) writePng(join(outs.partsDir, `${record.name}.png`), image);
751
+ for (const { record, image, depthImage } of result.images) {
752
+ writePng(join(outs.partsDir, `${record.name}.png`), image);
753
+ if (depthImage !== undefined && record.depth !== undefined) writePng(join(outs.partsDir, record.depth.image), depthImage);
754
+ }
755
+ for (const row of result.depthReadings ?? []) log(` depth reading ${row.from}: ${row.reading.relation}; ordering median ${row.reading.orderingMedian}, source-sheet median ${row.reading.sheetMedian} (half-level quantization; reading only, polarity declared)`);
730
756
  for (const b of altBuilt) {
731
757
  for (const { name, image } of b.images) writePng(join(outs.partsDir, `${name}.png`), image);
732
758
  }
@@ -1206,6 +1232,9 @@ export function replaySearch(
1206
1232
  }
1207
1233
  const selection = motion.selection;
1208
1234
  if (selection !== undefined && selection.maxProbes < maxReplays(N, I)) return refuse(budgetProblem(c.object, selection.maxProbes, N, I));
1235
+ const { candidates: _unused, ...referenceInput } = motionInput(c, motion, refModel, refModel, probeSchedule);
1236
+ const prepared = prepareComparison(c.object, referenceInput);
1237
+ if ('code' in prepared) return refuse(prepared);
1209
1238
  const kept = new Map<number, ReplayCandidate>();
1210
1239
  const probeFrames: string[] = [];
1211
1240
  let fatal: Problem | null = null;
@@ -1234,7 +1263,7 @@ export function replaySearch(
1234
1263
  };
1235
1264
  return refused(`rigc exit ${gate.status}`);
1236
1265
  }
1237
- const cmp = runComparison(c.object, motionInput(c, motion, refModel, model, probeSchedule));
1266
+ const cmp = runPreparedComparison(c.object, prepared, motionInput(c, motion, refModel, model, probeSchedule));
1238
1267
  if ('code' in cmp) {
1239
1268
  fatal = cmp;
1240
1269
  return refused(cmp.code);
@@ -1358,17 +1387,21 @@ export function readRigInputs(config: string, partsDir: string): RigInputs {
1358
1387
  const { config: cfg, animations: from } = loadConfigAndAnimations(config);
1359
1388
  const parts = readParts(join(partsDir, 'parts.json'));
1360
1389
  const images = new Map<string, Raster>();
1390
+ const depthProblems: Problem[] = [];
1361
1391
  for (const p of parts.parts) {
1362
1392
  const png = join(partsDir, 'parts', `${p.name}.png`);
1363
1393
  if (existsSync(png)) images.set(p.name, readPng(png));
1394
+ if (p.depth !== undefined && images.has(p.name)) { try { images.set(p.depth.image, readSourceDepth(join(partsDir, 'parts', p.depth.image), images.get(p.name) as Raster, null).pixels); } catch (error) { if (error instanceof PartsError) depthProblems.push(...error.problems); else throw error; } }
1364
1395
  }
1365
1396
  for (const alt of parts.alternates ?? []) {
1366
1397
  for (const p of alt.records) {
1367
1398
  const attName = `${alt.name}_${p.name}`;
1368
1399
  const png = join(partsDir, 'parts', `${attName}.png`);
1369
1400
  if (existsSync(png)) images.set(attName, readPng(png));
1401
+ if (p.depth !== undefined && images.has(attName)) { try { images.set(p.depth.image, readSourceDepth(join(partsDir, 'parts', p.depth.image), images.get(attName) as Raster, null).pixels); } catch (error) { if (error instanceof PartsError) depthProblems.push(...error.problems); else throw error; } }
1370
1402
  }
1371
1403
  }
1404
+ refuseIfAny(depthProblems);
1372
1405
  return { cfg, from, parts, images };
1373
1406
  }
1374
1407
 
@@ -1380,6 +1413,7 @@ export function rigOutputTexts(r: RigOutput, animations: Parameters<typeof withA
1380
1413
  ['rig.json', rigJsonText(r.rig)],
1381
1414
  ['motion.json', rigJsonText(mergedMotion)],
1382
1415
  ['mesh_report.json', rigJsonText(r.meshReport)],
1416
+ ...(r.depthReferences === undefined ? [] : [['depth_sheets.json', rigJsonText({ spec: 'rig-parts-depth-sheets/1', parts: r.depthReferences })] as [string, string]]),
1383
1417
  ...(r.sets === undefined ? [] : [[SETS_FILE, rigJsonText(r.sets)] as [string, string]]),
1384
1418
  ];
1385
1419
  }
@@ -31,6 +31,7 @@ import { basename, dirname, join } from 'node:path';
31
31
  import { refuseIfAny } from '../errors.ts';
32
32
  import { checkGraph, fillSeeThrough, type SeeThroughParams } from '../graphs.ts';
33
33
  import { readWrapperLayers } from '../layers.ts';
34
+ import type { DepthBinding } from '../depthsheets.ts';
34
35
  import { decodePngBytes } from '../raster/png.ts';
35
36
  import { ComfyClient, historyImages, refuse } from './client.ts';
36
37
 
@@ -50,6 +51,8 @@ export interface SeeThroughRun {
50
51
  quant: 'none' | 'nf4';
51
52
  wait: number;
52
53
  timeout: number;
54
+ /** Explicit config/run context; absent means legacy art-only capture. */
55
+ depth?: DepthBinding;
53
56
  }
54
57
 
55
58
  export interface SeeThroughResult {
@@ -73,6 +76,7 @@ function safeName(name: string): boolean {
73
76
  }
74
77
 
75
78
  export async function runSeeThrough(client: ComfyClient, run: SeeThroughRun, say: (line: string) => void): Promise<SeeThroughResult> {
79
+ const depth = run.depth?.config === undefined ? undefined : run.depth;
76
80
  if (!existsSync(run.image)) refuse('COMFY_IMAGE_PRESENT', run.image, 'no such file; the PNG See-through is to decompose is required');
77
81
  const bytes = new Uint8Array(readFileSync(run.image));
78
82
  const img = decodePngBytes(bytes, run.image);
@@ -122,7 +126,7 @@ export async function runSeeThrough(client: ComfyClient, run: SeeThroughRun, say
122
126
  }
123
127
  const layers = Array.isArray(manifest.layers) ? (manifest.layers as Array<Record<string, unknown>>) : [];
124
128
  if (layers.length === 0) refuse('COMFY_MANIFEST_NAMED', `output/${infoLog}`, 'lists no layers; a See-through run writes one per tag');
125
- const bad = layers.filter((l) => typeof l.name !== 'string' || !safeName(l.name) || typeof l.filename !== 'string' || !safeName(l.filename));
129
+ const bad = layers.filter((l) => typeof l.name !== 'string' || !safeName(l.name) || typeof l.filename !== 'string' || !safeName(l.filename) || (depth !== undefined && 'depth_filename' in l && (typeof l.depth_filename !== 'string' || !safeName(l.depth_filename))));
126
130
  if (bad.length > 0) {
127
131
  refuse('COMFY_LAYER_NAME', `output/${infoLog}`, `names ${bad.length} layer(s) whose name or filename is not a plain file name (first ${JSON.stringify(bad[0]).slice(0, 200)}); each becomes parts/<name>.png`);
128
132
  }
@@ -135,8 +139,9 @@ export async function runSeeThrough(client: ComfyClient, run: SeeThroughRun, say
135
139
  try {
136
140
  for (const p of previews) writeFileSync(join(stage, 'previews', basename(p.filename)), await client.view(p.filename, p.subfolder, p.type));
137
141
  for (const l of layers) writeFileSync(join(stage, 'parts', `${l.name as string}.png`), await client.view(l.filename as string));
142
+ if (depth !== undefined) for (const l of layers) if ('depth_filename' in l) writeFileSync(join(stage, 'parts', `${l.name as string}_depth.png`), await client.view(l.depth_filename as string));
138
143
  writeFileSync(join(stage, 'layers.json'), manifestBytes);
139
- const set = readWrapperLayers(stage);
144
+ const set = readWrapperLayers(stage, depth);
140
145
  const meta = {
141
146
  prompt_id: id,
142
147
  image: run.image,
package/src/config.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import type { DepthConfig } from './depthsheets.ts';
1
2
  /**
2
3
  * The character config: everything character-specific the CPU stages read,
3
4
  * plus the optional blocks for the two GPU stages.
@@ -97,7 +98,7 @@ import { edgeLength } from './length.ts';
97
98
  import { setFocusProblems } from './setfocus.ts';
98
99
  import { isSkeletonName, KEYPOINT_NAMES, type KeypointName, type PosePoints, scaledPoints, SKELETON_NAMES, type SkeletonName } from './skeleton.ts';
99
100
  import { acceptedTagNames, AUTHOR_LABEL_RULE, AUTHOR_PREFIX, readLayerTag } from './tags.ts';
100
- import { EAR_DEPTH_RANGE, FACE_DEFORM_FRACTIONS, FACE_DEFORM_RANGES, type FaceDeformKey, FACE_RATED_PITCH_BAND, FACE_RATED_YAW_BAND, TURN_BONE, type TurnSpec, turnNearest } from './turn.ts';
101
+ import { EAR_DEPTH_RANGE, FACE_DEFORM_FRACTIONS, FACE_DEFORM_RANGES, type FaceDeformKey, FACE_RATED_PITCH_BAND, FACE_RATED_YAW_BAND, FACESHIFT_BONE, REAR_SHIFT_BONE, TURN_BONE, TURN_ROLES, type TurnSpec, turnNearest, turnSurfaceBone } from './turn.ts';
101
102
  import { FLOOR_FORMS, type FloorForm, type MeshInfluences } from './weights.ts';
102
103
 
103
104
  export type Point = [number, number];
@@ -1039,6 +1040,7 @@ export type LimbLayout = { parts?: string[] } & (
1039
1040
  );
1040
1041
 
1041
1042
  export interface CharacterConfig {
1043
+ depth?: DepthConfig;
1042
1044
  key: string;
1043
1045
  note?: string;
1044
1046
  generation?: Generation;
@@ -1378,6 +1380,7 @@ export interface PaintConfig {
1378
1380
  * bones, meshes, regions and motion that are written only after them.
1379
1381
  */
1380
1382
  export interface EarlyConfig {
1383
+ depth?: DepthConfig;
1381
1384
  key: string;
1382
1385
  seethrough: SeeThrough;
1383
1386
  assemble: { rig_scale: number; head_face_underfill?: boolean };
@@ -1385,6 +1388,7 @@ export interface EarlyConfig {
1385
1388
 
1386
1389
  /** What plain `assemble` reads: the early config plus the plan `--propose-plan` printed. */
1387
1390
  export interface AssembleConfig {
1391
+ depth?: DepthConfig;
1388
1392
  key: string;
1389
1393
  seethrough: SeeThrough;
1390
1394
  assemble: Assemble;
@@ -1397,7 +1401,7 @@ export interface AssembleConfig {
1397
1401
  proposed_rig_scale?: number;
1398
1402
  }
1399
1403
 
1400
- const TOP_KEYS = ['key', 'generation', 'seethrough', 'assemble', 'limbs', 'bones', 'meshes', 'regions', 'motion', 'constraints', 'stops', 'turn', 'scene', 'cloth', 'proposed_rig_scale', 'requirements', 'motion_seams'] as const;
1404
+ const TOP_KEYS = ['key', 'generation', 'seethrough', 'assemble', 'limbs', 'bones', 'meshes', 'regions', 'motion', 'constraints', 'stops', 'turn', 'scene', 'cloth', 'proposed_rig_scale', 'requirements', 'motion_seams', 'depth'] as const;
1401
1405
 
1402
1406
  /**
1403
1407
  * The one partial entry point. It validates exactly what its door requires —
@@ -1428,6 +1432,7 @@ function parseEarlyConfigFrom(raw: Json, door: EarlyDoor, base: string | null):
1428
1432
  const top = c.object('config', raw, required, TOP_KEYS.filter((k) => !required.includes(k)));
1429
1433
  if (top === null) refuseIfAny(c.problems);
1430
1434
  const t = top as Record<string, Json>;
1435
+ if ('depth' in t) checkDepthConfig(c, t.depth);
1431
1436
  if ('key' in t) c.string('config.key', t.key);
1432
1437
  if ('generation' in t) checkGeneration(c, t.generation);
1433
1438
  else if (needed.includes('generation')) {
@@ -1651,6 +1656,7 @@ function parseConfigFrom(raw: Json, base: string | null): { config: CharacterCon
1651
1656
  const top = c.object('config', raw, required, TOP_KEYS.filter((k) => !required.includes(k)));
1652
1657
  if (top === null) refuseIfAny(c.problems);
1653
1658
  const t = top as Record<string, Json>;
1659
+ if ('depth' in t) checkDepthConfig(c, t.depth);
1654
1660
  if ('key' in t) c.string('config.key', t.key);
1655
1661
  if ('generation' in t) checkGeneration(c, t.generation);
1656
1662
  if ('seethrough' in t) checkSeeThrough(c, t.seethrough);
@@ -1670,7 +1676,7 @@ function parseConfigFrom(raw: Json, base: string | null): { config: CharacterCon
1670
1676
  const attached = attachedParts(t.meshes, t.regions);
1671
1677
  if ('motion_seams' in t) c.problems.push(...motionSeamProblems(t.motion_seams, attached, 'config.motion_seams', 'CONFIG_MOTION_SEAM'));
1672
1678
  const hasAltFace = hasAlternateFaceSet(t.assemble, [...parts, ...cuts]);
1673
- if ('turn' in t) checkTurn(c, t.turn, attached, names.bones, hasAltFace);
1679
+ if ('turn' in t) checkTurn(c, t.turn, attached, names.bones, hasAltFace, parts);
1674
1680
  if ('scene' in t) checkScene(c, t.scene);
1675
1681
  if ('cloth' in t) checkCloth(c, t.cloth);
1676
1682
  if ('requirements' in t && c.string('config.requirements', t.requirements) && base !== null) checkRequirementsFile(c, resolve(base, t.requirements));
@@ -4125,6 +4131,7 @@ export function loadClothConfig(path: string): { key: string; cloth: ClothRecipe
4125
4131
  const top = c.object('config', raw, required, TOP_KEYS.filter((k) => !required.includes(k)));
4126
4132
  if (top === null) refuseIfAny(c.problems);
4127
4133
  const t = top as Record<string, Json>;
4134
+ if ('depth' in t) checkDepthConfig(c, t.depth);
4128
4135
  if ('key' in t) c.string('config.key', t.key);
4129
4136
  if ('cloth' in t) checkCloth(c, t.cloth);
4130
4137
  refuseIfAny(c.problems);
@@ -4189,7 +4196,7 @@ function checkFaceAnimationBand(c: Check, animations: AnimationsFrom, hasAltFace
4189
4196
  'config.turn',
4190
4197
  "is absent and required when motion.animations_from carries a turn or tilt slider animation with derive keys; copy the turn block propose drafted into config.turn so the head pivot and each head part's depth are declared",
4191
4198
  );
4192
- } else if (isPlainObject(turn) && isPlainObject(turn.depths) && attached !== undefined) {
4199
+ } else if (isPlainObject(turn) && isPlainObject(turn.depths) && !isPlainObject(turn.roles) && attached !== undefined) {
4193
4200
  for (const reqPart of ['face', 'hair_front', 'hair_back'] as const) {
4194
4201
  if (attached.has(reqPart) && !(reqPart in turn.depths)) {
4195
4202
  c.fail(
@@ -4353,11 +4360,98 @@ function checkAnimationSetKeys(
4353
4360
  }
4354
4361
  }
4355
4362
 
4356
- function checkTurn(c: Check, v: Json, attached: Set<string>, bones: Set<string>, hasAltFace: boolean): void {
4363
+ function checkTurn(c: Check, v: Json, attached: Set<string>, bones: Set<string>, hasAltFace: boolean, parts: readonly string[] = []): void {
4357
4364
  const at = 'config.turn';
4358
- const o = c.object(at, v, ['pivot', 'depths'], ['head', 'deform', 'band', 'radius', 'surface']);
4365
+ const hasRoles = isPlainObject(v) && 'roles' in v;
4366
+ const o = hasRoles
4367
+ ? c.object(at, v, ['roles'], ['pivot', 'depths', 'counter', 'grid', 'unitDepths', 'head', 'deform', 'band', 'radius', 'surface'])
4368
+ : c.object(at, v, ['pivot', 'depths'], ['roles', 'counter', 'grid', 'unitDepths', 'head', 'deform', 'band', 'radius', 'surface']);
4359
4369
  if (o === null) return;
4360
4370
  const pivot = 'pivot' in o && c.number(`${at}.pivot`, o.pivot) ? (o.pivot as number) : null;
4371
+ if ('counter' in o && c.number(`${at}.counter`, o.counter)) {
4372
+ const cnt = o.counter as number;
4373
+ if (cnt < 0 || cnt > 1) {
4374
+ c.fail('CONFIG_TURN_COUNTER_RANGE', `${at}.counter`, `is ${cnt}; a rear counter fraction in [0, 1] is required`);
4375
+ }
4376
+ }
4377
+ if ('grid' in o) {
4378
+ const checkGridPair = (gAt: string, gv: Json): void => {
4379
+ if (!Array.isArray(gv) || gv.length !== 2 || !gv.every((n) => typeof n === 'number' && Number.isInteger(n) && n >= 2)) {
4380
+ c.fail('CONFIG_FIELD_TYPE', gAt, `is ${show(gv)}; a [cols, rows] pair of integers >= 2 is required`);
4381
+ }
4382
+ };
4383
+ if (Array.isArray(o.grid)) {
4384
+ checkGridPair(`${at}.grid`, o.grid);
4385
+ } else if (isPlainObject(o.grid)) {
4386
+ for (const [part, gv] of Object.entries(o.grid)) {
4387
+ if (isRecordKey(part)) continue;
4388
+ if (!attached.has(part)) {
4389
+ c.fail('CONFIG_NAME_RESOLVES', `${at}.grid.${part}`, `names "${part}", which neither config.meshes nor config.regions attaches`);
4390
+ }
4391
+ checkGridPair(`${at}.grid.${part}`, gv);
4392
+ }
4393
+ } else {
4394
+ c.fail('CONFIG_FIELD_TYPE', `${at}.grid`, `is ${show(o.grid)}; a [cols, rows] pair or object of part -> [cols, rows] is required`);
4395
+ }
4396
+ }
4397
+ if ('unitDepths' in o) {
4398
+ if (!isPlainObject(o.unitDepths)) {
4399
+ c.fail('CONFIG_FIELD_TYPE', `${at}.unitDepths`, `is ${show(o.unitDepths)}; an object of part or bone name -> scalar depth is required`);
4400
+ } else {
4401
+ for (const [k, dv] of Object.entries(o.unitDepths)) {
4402
+ if (isRecordKey(k)) continue;
4403
+ if (!attached.has(k) && !bones.has(k)) {
4404
+ c.fail('CONFIG_NAME_RESOLVES', `${at}.unitDepths.${k}`, `names "${k}", which is neither an attached part nor a declared bone`);
4405
+ }
4406
+ c.number(`${at}.unitDepths.${k}`, dv);
4407
+ }
4408
+ }
4409
+ }
4410
+ if ('roles' in o) {
4411
+ const r = o.roles;
4412
+ if (!isPlainObject(r) || Object.keys(r).length === 0) {
4413
+ c.fail('CONFIG_FIELD_TYPE', `${at}.roles`, `is ${show(r)}; a non-empty object of part name -> ("surface" | "unit" | "rear") is required`);
4414
+ } else {
4415
+ const surfaceParts: string[] = [];
4416
+ const earParts: string[] = [];
4417
+ for (const [part, role] of Object.entries(r)) {
4418
+ if (isRecordKey(part)) continue;
4419
+ if (!attached.has(part)) {
4420
+ c.fail('CONFIG_NAME_RESOLVES', `${at}.roles.${part}`, `names "${part}", which neither config.meshes nor config.regions attaches; a part the rig draws is required`);
4421
+ }
4422
+ if (typeof role !== 'string' || !(TURN_ROLES as readonly string[]).includes(role)) {
4423
+ c.fail('CONFIG_TURN_ROLE_UNKNOWN', `${at}.roles.${part}`, `is ${show(role)}; expected one of ${TURN_ROLES.map((x) => `"${x}"`).join(', ')}`);
4424
+ } else {
4425
+ if (role === 'surface') surfaceParts.push(part);
4426
+ if (role === 'unit' && (part === 'ear_r' || part === 'ear_l')) earParts.push(part);
4427
+ }
4428
+ }
4429
+ if (surfaceParts.length === 0) {
4430
+ c.fail('CONFIG_TURN_SURFACE_REQUIRED', `${at}.roles`, 'declares no part with role "surface"; at least one surface part (such as "face") is required for 2.5D head turn');
4431
+ }
4432
+ for (const ear of earParts) {
4433
+ const earIdx = parts.indexOf(ear);
4434
+ for (const surf of surfaceParts) {
4435
+ const surfIdx = parts.indexOf(surf);
4436
+ if (earIdx !== -1 && surfIdx !== -1 && earIdx > surfIdx) {
4437
+ c.fail(
4438
+ 'CONFIG_TURN_EAR_DRAW_ORDER',
4439
+ `${at}.roles.${ear}`,
4440
+ `draws "${ear}" (plan index ${earIdx}) after surface part "${surf}" (plan index ${surfIdx}); place "${ear}" before "${surf}" in config.assemble.plan so the ear is occluded behind the face`,
4441
+ );
4442
+ }
4443
+ }
4444
+ }
4445
+ if (!bones.has('head')) {
4446
+ c.fail('CONFIG_TURN_HEAD_BONE', `${at}.roles`, 'requires a declared "head" bone in config.bones to parent the 2.5D turn carriers');
4447
+ }
4448
+ for (const reserved of [FACESHIFT_BONE, REAR_SHIFT_BONE, ...surfaceParts.map(turnSurfaceBone)]) {
4449
+ if (bones.has(reserved)) {
4450
+ c.fail('CONFIG_TURN_BONE_FREE', `bone "${reserved}"`, `is a carrier bone the rig stage adds under head for config.turn.roles, and config.bones already declares a bone of that name; rename it`);
4451
+ }
4452
+ }
4453
+ }
4454
+ }
4361
4455
  if ('radius' in o) c.number(`${at}.radius`, o.radius, 'positive');
4362
4456
  if ('surface' in o) {
4363
4457
  const so = c.object(`${at}.surface`, o.surface, [], ['radius']);
@@ -4453,7 +4547,7 @@ function checkTurn(c: Check, v: Json, attached: Set<string>, bones: Set<string>,
4453
4547
  }
4454
4548
  }
4455
4549
  }
4456
- if (pivot !== null && depthsOk) {
4550
+ if (!hasRoles && pivot !== null && depthsOk) {
4457
4551
  const nearest = turnNearest(depths);
4458
4552
  if (nearest !== null && !(pivot > nearest.depth)) {
4459
4553
  c.fail(
@@ -4463,7 +4557,7 @@ function checkTurn(c: Check, v: Json, attached: Set<string>, bones: Set<string>,
4463
4557
  );
4464
4558
  }
4465
4559
  }
4466
- if (headPivot !== null && depthsOk) {
4560
+ if (!hasRoles && headPivot !== null && depthsOk) {
4467
4561
  const nearest = turnNearest(depths);
4468
4562
  if (nearest !== null && !(headPivot > nearest.depth)) {
4469
4563
  c.fail(
@@ -4473,7 +4567,34 @@ function checkTurn(c: Check, v: Json, attached: Set<string>, bones: Set<string>,
4473
4567
  );
4474
4568
  }
4475
4569
  }
4476
- if (bones.has(TURN_BONE)) {
4570
+ if (!hasRoles && bones.has(TURN_BONE)) {
4477
4571
  c.fail('CONFIG_TURN_BONE_FREE', `bone "${TURN_BONE}"`, `is the control the rig stage adds under root for config.turn, and config.bones already declares a bone of that name; rename it`);
4478
4572
  }
4479
4573
  }
4574
+
4575
+ /** #773: all scalar units and user polarity are authored, never inferred. */
4576
+ function checkDepthConfig(c: Check, raw: Json): void {
4577
+ const d = c.object('config.depth', raw, [], ['zScale', 'full', 'head']);
4578
+ if (d === null) return;
4579
+ const scale = (path: string, v: Json | undefined): void => {
4580
+ if (typeof v !== 'number' || !Number.isFinite(v) || v <= 0) c.fail('DEPTH_ZSCALE_REQUIRED', path, `is ${show(v)}; positive finite authored world units are required`);
4581
+ };
4582
+ if ('zScale' in d) scale('config.depth.zScale', d.zScale);
4583
+ const sheet = (path: string, value: Json): void => {
4584
+ const q = c.object(path, value, ['image'], ['near', 'zScale']);
4585
+ if (q === null) return;
4586
+ if ('image' in q) c.string(`${path}.image`, q.image);
4587
+ if (q.near !== 'black' && q.near !== 'white') c.fail('DEPTH_NEAR_REQUIRED', `${path}.near`, `is ${show(q.near)}; a user sheet must declare black or white, with no guessed convention`);
4588
+ scale(`${path}.zScale`, q.zScale);
4589
+ };
4590
+ for (const run of ['full', 'head']) if (run in d) {
4591
+ const path = `config.depth.${run}`, q = c.object(path, d[run], [], ['layers', 'atlas']);
4592
+ if (q === null) continue;
4593
+ if ('atlas' in q) sheet(`${path}.atlas`, q.atlas);
4594
+ if ('layers' in q) {
4595
+ if (!isPlainObject(q.layers)) c.fail('CONFIG_FIELD_TYPE', `${path}.layers`, 'requires an object keyed by exact source layer name');
4596
+ else for (const [layer, value] of Object.entries(q.layers)) sheet(`${path}.layers.${layer}`, value);
4597
+ }
4598
+ if ('atlas' in q && isPlainObject(q.layers) && Object.keys(q.layers).length > 0) c.fail('DEPTH_SOURCE_AMBIGUOUS', path, 'declares canvas and per-layer sheets together; choose one fallback explicitly');
4599
+ }
4600
+ }