rig-parts 2.52.0 → 2.53.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
@@ -11,6 +11,7 @@ import { DEFAULT_PROJECT_RULE } from './projectrule.ts';
11
11
  import { type PaintingAllocationReading, type PaintingAllocationEvent, EDGE_CONTRAST, PAINTING_ALLOCATION_FILE, PAINTING_EDGE_COVERAGE_TRANSFER } from './paintingedges.ts';
12
12
  import { SETUP_PAINTING_LINE, setupPaintingLines } from './setuppainting.ts';
13
13
  import { boundaryColourLines } from './boundarycolour.ts';
14
+ import { SOURCE_EXPOSURE_LINE, sourceExposureLines } from './sourceexposure.ts';
14
15
  import { behindSeamLines } from './behindseams.ts';
15
16
  import { writeMaterialSources } from './cutmaterialio.ts';
16
17
  import { CUT_MATERIAL_LINE, CUT_MATERIAL_SOURCES, materialLines } from './cutmaterial.ts';
@@ -107,6 +108,8 @@ import type { MeshQualityReport, MotionSchedule } from '@rig-c/core/mesh';
107
108
  import { encodeGif } from './gif.ts';
108
109
  import { CONTROL_SUFFIX, withAnimations } from './motion.ts';
109
110
  import type { PaletteError } from './palette.ts';
111
+ import { PartVisibility } from './partvisibility.ts';
112
+ import { readRunVisibility } from './visibility.ts';
110
113
  import { type LayerSet, readLayers } from './layers.ts';
111
114
  import { placeBoneEntriesForSkeleton, poseBoneEntriesForDrawn, REGISTER_OFFSET_BAR, REGISTER_SCALE_BAR, registeredWithinBar, registerSkeleton, SKELETON_LIMB_BONES, skeletonDrawnLength, skeletonLimbJoints } from './limbs.ts';
112
115
  import { type AlternatePartsRecord, PAINTING_IN_RIG_FILE, FRONT_SUFFIX, type OccluderPlateRecord, type PartRecord, partImageReference, depthImageReference, readParts, readPartsManifest, type RecompositeRecord, type SingleRunPad, tagOf, writeParts } from './parts.ts';
@@ -148,10 +151,20 @@ export function readSource(path: string): Raster {
148
151
  * head run (`head` null, issue #359) the full run is read once and stands for
149
152
  * both, and `single` says so: the stage then holds it to `checkSingleRun`.
150
153
  */
151
- export function readRuns(full: string, head: string | null): { full: LayerSet; head: LayerSet; single: boolean } {
154
+ export function readRuns(full: string, head: string | null, recordVisibility = false): {
155
+ full: LayerSet; head: LayerSet; single: boolean; visibility?: PartVisibility;
156
+ } {
152
157
  const problems: Problem[] = [];
153
- const one = (path: string): LayerSet | null => {
158
+ let recorded: ReturnType<typeof readRunVisibility>;
159
+ const one = (path: string, verify = false): LayerSet | null => {
154
160
  try {
161
+ if (verify && !/\.psd$/i.test(path) && existsSync(path)) {
162
+ const wrapperDir = statSync(path).isDirectory() ? path : basename(path) === 'layers.json' ? dirname(path) : undefined;
163
+ if (wrapperDir !== undefined) {
164
+ recorded = readRunVisibility(wrapperDir);
165
+ if (recorded !== undefined) return recorded.set;
166
+ }
167
+ }
155
168
  return readLayers(path);
156
169
  } catch (err) {
157
170
  if (err instanceof PartsError) {
@@ -161,10 +174,19 @@ export function readRuns(full: string, head: string | null): { full: LayerSet; h
161
174
  throw err;
162
175
  }
163
176
  };
164
- const f = one(full);
177
+ const f = one(full, recordVisibility);
165
178
  const h = head === null ? f : one(head);
166
179
  if (problems.length > 0) throw new PartsError(problems);
167
- return { full: f as LayerSet, head: h as LayerSet, single: head === null };
180
+ const runs = { full: f as LayerSet, head: h as LayerSet, single: head === null };
181
+ if (recorded === undefined) return runs;
182
+ const visibility = new PartVisibility();
183
+ const { manifest, masks } = recorded;
184
+ const byTag = new Map(manifest.layers.map((layer, i) => [layer.tag, masks[i]]));
185
+ for (const layer of [...runs.full.layers, ...runs.full.hidden]) {
186
+ visibility.layer(layer.pixels, `full:${layer.name}`, byTag.get(layer.name));
187
+ }
188
+ if (!runs.single) for (const layer of [...runs.head.layers, ...runs.head.hidden]) visibility.layer(layer.pixels, `head:${layer.name}`);
189
+ return { ...runs, visibility };
168
190
  }
169
191
 
170
192
  /** One `--alt <name>=<source>:<full>[:<head>]` argument (issue #454). */
@@ -545,14 +567,14 @@ export function assembleStage(input: AssembleStageInput, outs: AssembleOutputs,
545
567
  const { seam, project } = effectiveAssemblyRules(cfg.assemble, input);
546
568
  const { requirements, effectiveSetup } = resolveAssemblyRequirements(input, cfg, project, requirementsFile);
547
569
  const src = readSource(input.source);
548
- const read = readRuns(input.full, input.head);
570
+ const read = readRuns(input.full, input.head, true);
549
571
  // Issue #946: every declared receipt is held to its file, and under `required` every edited image needs one, before anything is assembled.
550
572
  const receipts = readEditorReceipts(cfg.assemble.editor_receipts, input.config);
551
573
  const editedParts = readEditedParts(cfg.assemble.edited_parts, input.config, cfg.assemble.plan ?? []);
552
574
  // Issue #947: under `trace_parts`, a shape drawn in the config through a part's pixels is refused with them.
553
575
  refuseIfAny([...receipts.problems, ...missingReceipts(receipts, [...editedRunImages(read), ...editedConfigImages(input.config, cfg.assemble.cuts ?? [], cfg.limbs)]), ...untracedPartSources(cfg)]);
554
- const takenRuns = applyTakenLayers(read, src, cfg, input.config);
555
- const runs = applyTakenRegions(takenRuns, src, cfg, input.config, effectiveSetup, receipts, input.source, requirements?.read);
576
+ const takenRuns = applyTakenLayers(read, src, cfg, input.config, read.visibility);
577
+ const runs = applyTakenRegions(takenRuns, src, cfg, input.config, effectiveSetup, receipts, input.source, requirements?.read, read.visibility);
556
578
  for (const note of runs.notes) log(note.startsWith('WARN ') ? note : `note: ${note}`);
557
579
  const fields = projectedStageFields(cfg, runs.single ? { w: src.width, h: src.height } : null);
558
580
  const setupPainting = requirements === null || fields.ground !== 'busy' || project !== 'visible' ? undefined
@@ -565,7 +587,7 @@ export function assembleStage(input: AssembleStageInput, outs: AssembleOutputs,
565
587
  const under = readUnders(input.config, fields.cuts, { sourcePath: input.source, rigSize, platesOut: underPlates });
566
588
  const caps = fields.limbs === undefined ? undefined : readCaps(input.config, fields.limbs);
567
589
  const occluders = cfg.assemble.occluders === undefined ? undefined : readOccluderInputs(cfg.assemble.occluders, input.config, src);
568
- const result = assemble({ editedParts, allocationEvent: input.allocationEvent === undefined ? undefined : event => input.allocationEvent!(event, null), source: src, full: runs.full, head: runs.head, depth: cfg.depth, depthBase: dirname(resolve(input.config)), ...fields, under, ...(declaredFigure === undefined ? {} : { declaredFigure }),
590
+ const result = assemble({ editedParts, allocationEvent: input.allocationEvent === undefined ? undefined : event => input.allocationEvent!(event, null), source: src, full: runs.full, head: runs.head, visibility: read.visibility, depth: cfg.depth, depthBase: dirname(resolve(input.config)), ...fields, under, ...(declaredFigure === undefined ? {} : { declaredFigure }),
569
591
  ...((cfg.assemble.take ?? []).some(t => 'seed' in t) ? { regionTake: { full: takenRuns.full, head: takenRuns.head, targets: (cfg.assemble.take ?? []).flatMap(t => 'seed' in t ? [t.part] : []) } } : {}), ...(caps === undefined ? {} : { caps }), ...(occluders === undefined ? {} : { occluders }), seamRule: seam, projectRule: project });
570
592
  refuseIfAny(verifyUnderPlateMasks(result, fields.cuts, underPlates));
571
593
 
@@ -735,7 +757,7 @@ export function assembleStage(input: AssembleStageInput, outs: AssembleOutputs,
735
757
  const invalidFocus = setFocusProblems(alt.focus, `${alt.at}.focus`, [altSrc.width, altSrc.height]);
736
758
  if (invalidFocus.length > 0) { altProblems.push(...invalidFocus); continue; }
737
759
  }
738
- const altRuns = readRuns(alt.full, alt.head ?? null);
760
+ const altRuns = readRuns(alt.full, alt.head ?? null, true);
739
761
  altProblems.push(...missingReceipts(receipts, [...editedRunImages(altRuns, `alternate set "${alt.name}" `), ...editedConfigImages(input.config, alt.cuts ?? [], undefined, `${alt.at}.cuts`)]));
740
762
  const hidesSet = new Set(alt.hides ?? []);
741
763
  const declaredSlots = alt.parts !== undefined ? alt.parts.filter((p) => !hidesSet.has(p)) : baseSlots.filter((p) => !hidesSet.has(p));
@@ -927,6 +949,7 @@ export function assembleStage(input: AssembleStageInput, outs: AssembleOutputs,
927
949
  capOwnership: input.setCapOwnership ?? 'target',
928
950
  full: altRuns.full,
929
951
  head: altRuns.head,
952
+ visibility: altRuns.visibility,
930
953
  ...(hiddenExtent === undefined ? {} : { requireHiddenExtent: hiddenExtent }),
931
954
  ...(fields.keepUnderOccluders === undefined ? {} : { keepUnderOccluders: fields.keepUnderOccluders.filter(name => altPlanNames.has(name)) }),
932
955
  resolution: fields.resolution,
@@ -973,10 +996,26 @@ export function assembleStage(input: AssembleStageInput, outs: AssembleOutputs,
973
996
  altProblems.push(...altMaskProblems);
974
997
  continue;
975
998
  }
999
+ // Issue #1474: a set's overlap rows pair its kept parts in the order the set draws them, the order of its
1000
+ // recomposite and its rig slots: base order, with a part the set draws on its front slot after that slot's target.
1001
+ const keptOverlaps = altRuns.visibility === undefined ? undefined : (() => {
1002
+ const rank = new Map(frontOrdered(result.images, altFront, frontAfter).map(({ record }, i) => [record.name, i]));
1003
+ const kept = altRes.images.filter(({ record }) => coveredSet.has(record.name))
1004
+ .map((item, i) => ({ item, at: rank.get(item.record.name) ?? rank.size + i }))
1005
+ .sort((a, b) => a.at - b.at).map(({ item }) => item);
1006
+ const rows = altRuns.visibility.overlaps(kept.map(({ record, image }) => ({ name: record.name, x: record.x, y: record.y, image })));
1007
+ return new Map(kept.map(({ record }, i) => [record.name, rows[i]]));
1008
+ })();
976
1009
  const keptImages = altRes.images
977
1010
  .filter(({ record }) => coveredSet.has(record.name))
978
- .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 }])]);
979
- 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}` } });
1011
+ .flatMap(({ record, image, depthImage, sourceStates }) => [{ name: `${alt.name}_${record.name}`, image }, ...(depthImage === undefined || record.depth === undefined ? [] : [{ name: `${alt.name}_${record.depth.image.slice(0, -4)}`, image: depthImage }]),
1012
+ ...(sourceStates === undefined || record.source_state_map === undefined ? [] : [{ name: `${alt.name}_${record.source_state_map.image.slice(0, -4)}`, image: sourceStates }])]);
1013
+ const keptRecords = altRes.parts.parts.filter((p) => coveredSet.has(p.name)).map(p => {
1014
+ const rows = keptOverlaps?.get(p.name);
1015
+ const overlaps = rows === undefined ? p : { ...p, source_overlaps: rows };
1016
+ const depth = overlaps.depth === undefined ? overlaps : { ...overlaps, depth: { ...overlaps.depth, image: `${alt.name}_${overlaps.depth.image}` } };
1017
+ return p.source_state_map === undefined ? depth : { ...depth, source_state_map: { ...p.source_state_map, image: `${alt.name}_${p.source_state_map.image}` } };
1018
+ });
980
1019
  if (result.stageMap !== undefined && altRes.stageMap !== undefined) {
981
1020
  altRes.stageMap.parts = altRes.stageMap.parts.filter(p => coveredSet.has(p.name));
982
1021
  (result.stageMap.alternates ??= []).push({ name: alt.name, map: altRes.stageMap });
@@ -1056,9 +1095,10 @@ export function assembleStage(input: AssembleStageInput, outs: AssembleOutputs,
1056
1095
  });
1057
1096
  }
1058
1097
  const emittedAssets = [
1059
- ...result.images.flatMap(({ record, depthImage }) => [
1098
+ ...result.images.flatMap(({ record, depthImage, sourceStates }) => [
1060
1099
  `${record.name}.png`,
1061
1100
  ...(depthImage !== undefined && record.depth !== undefined ? [record.depth.image] : []),
1101
+ ...(sourceStates !== undefined && record.source_state_map !== undefined ? [record.source_state_map.image] : []),
1062
1102
  ]),
1063
1103
  ...altBuilt.flatMap((b) => b.images.map(({ name }) => `${name}.png`)),
1064
1104
  ];
@@ -1174,6 +1214,7 @@ export function assembleStage(input: AssembleStageInput, outs: AssembleOutputs,
1174
1214
  else writeFileSync(join(outs.partsDir, `${record.name}.png`), encodedBytes);
1175
1215
  if (depthImage !== undefined && record.depth !== undefined) writePng(join(outs.partsDir, record.depth.image), depthImage);
1176
1216
  }
1217
+ for (const { record, sourceStates } of result.images) if (sourceStates !== undefined && record.source_state_map !== undefined) writePng(join(outs.partsDir, record.source_state_map.image), sourceStates);
1177
1218
  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)`);
1178
1219
  for (const row of result.depthClamps ?? []) log(` depth edge clamp ${row.part}: ${row.samples} visible samples less than 1 source pixel outside the crop; edge texels retained`);
1179
1220
  for (const b of altBuilt) for (const row of b.depthClamps ?? []) log(` set "${b.record.name}" depth edge clamp ${row.part}: ${row.samples} visible samples less than 1 source pixel outside the crop; edge texels retained`);
@@ -2243,18 +2284,22 @@ export function judgementLine(name: string, line: JudgementLine | ReportedLine):
2243
2284
  * where `may_fold` takes it.
2244
2285
  */
2245
2286
  export function foldsLines(line: FoldsLine): string[] {
2246
- const physics = line.physics_left_out === 0 ? '' : `, with its ${line.physics_left_out} physics constraint(s) on and off`;
2287
+ const skipped = new Set(line.physics_off_skipped);
2288
+ const sides = skipped.size === 0 ? 'on and off' : skipped.size === line.animations.length ? 'on' : 'on and off where a keyed animation remains';
2289
+ const physics = line.physics_left_out === 0 ? '' : `, with its ${line.physics_left_out} physics constraint(s) ${sides}`;
2247
2290
  const head =
2248
2291
  `${FOLD_LINE}: ${line.status} — ${line.animations.length} animation(s) read by rigc render --folds at ${line.fps} fps${physics} (${line.animations.join(', ')}): ` +
2249
2292
  `${line.folding.length} folding mesh(es), ${line.folding_undeclared} not declared in may_fold (<= ${line.bar})` +
2250
2293
  (line.declared_not_folding.length === 0 ? '' : `; may_fold declares ${line.declared_not_folding.map((d) => `slot "${d.slot}" in "${d.animation}"`).join(', ')}, which do(es) not fold`);
2251
2294
  return [
2252
2295
  head,
2296
+ ...[...skipped].map(name => ` folds physics off: SKIP — ${JSON.stringify(name)} has no timeline after removing physics tracks`),
2253
2297
  ...line.folding.map((r) => {
2298
+ const off = skipped.has(r.animation) ? 'SKIP' : r.physics_off === null ? '0 frame(s)' : `${r.physics_off.frames} frame(s), worst frame ${r.physics_off.worst_frame} (${r.physics_off.worst_triangles}/${r.triangles} triangle(s))`;
2254
2299
  const side =
2255
2300
  line.physics_left_out === 0
2256
2301
  ? ''
2257
- : ` — physics on: ${r.physics_on === null ? '0 frame(s)' : `${r.physics_on.frames} frame(s), worst frame ${r.physics_on.worst_frame} (${r.physics_on.worst_triangles}/${r.triangles} triangle(s))`}; physics off: ${r.physics_off === null ? '0 frame(s)' : `${r.physics_off.frames} frame(s), worst frame ${r.physics_off.worst_frame} (${r.physics_off.worst_triangles}/${r.triangles} triangle(s))`}` +
2302
+ : ` — physics on: ${r.physics_on === null ? '0 frame(s)' : `${r.physics_on.frames} frame(s), worst frame ${r.physics_on.worst_frame} (${r.physics_on.worst_triangles}/${r.triangles} triangle(s))`}; physics off: ${off}` +
2258
2303
  (r.physics_constraints.length === 0 ? '' : `; physics constraint(s): ${r.physics_constraints.join(', ')}`);
2259
2304
  return ` folds ${r.line}${side}${r.declared === null ? '' : ` — declared in may_fold: ${r.declared}`}`;
2260
2305
  }),
@@ -2405,7 +2450,7 @@ export function checkStage(input: CheckStageInput, rigc: RigcRunner, bin: string
2405
2450
  if (r.idle === null) log(` loop: SKIP — ${fig.skipped?.loop ?? ''}`);
2406
2451
  else log(` ${loopCheckLine(r.idle, fig.loop_max_diff, fig.loop_physics?.length ?? 0)}`);
2407
2452
  if (r.loopPhysics !== null) log(` ${r.loopPhysics}`);
2408
- const beside = besideIdleLine(r.besideIdle, r.figures[LEVEL_LINE] !== undefined);
2453
+ const beside = besideIdleLine(r.besideIdle, fig[LEVEL_LINE] !== undefined, (fig[FOLD_LINE]?.physics_off_skipped?.length ?? 0) > 0);
2409
2454
  if (beside !== null) log(` ${beside}`);
2410
2455
  if (r.seamViewport === null || fig.seam_mean === null) log(` seam: SKIP — ${fig.skipped?.seam ?? ''}`);
2411
2456
  else {
@@ -2468,6 +2513,8 @@ export function checkStage(input: CheckStageInput, rigc: RigcRunner, bin: string
2468
2513
  if (setupPainting !== undefined) for (const line of setupPaintingLines(setupPainting)) log(` ${line}`);
2469
2514
  for (const line of boundaryColourLines(r.boundaryColour)) log(` ${line}`);
2470
2515
  for (const line of behindSeamLines(r.behindSeams)) log(` ${line}`);
2516
+ const sourceExposure = fig[SOURCE_EXPOSURE_LINE];
2517
+ if (sourceExposure !== undefined) for (const line of sourceExposureLines(sourceExposure)) log(` ${line}`);
2471
2518
  if (r.requirements !== null) {
2472
2519
  for (const [name, line] of Object.entries(r.requirements.lines)) log(` ${requirementText(name, line)}`);
2473
2520
  log(` ${summaryText(r.requirements.summary)}`);
package/src/check.ts CHANGED
@@ -10,6 +10,7 @@ import { CUT_MATERIAL_LINE, checkJointMaterial, type MaterialLine } from './cutm
10
10
  import { ART_JOINT_LINE, artJointLine, type ArtJointLine } from './artjoints.ts';
11
11
  import { BOUNDARY_COLOUR_LINE, BOUNDARY_COLOUR_UNMEASURED_CODE, BOUNDARY_COLOUR_UNMEASURED_SUFFIX, measureBoundaryColour, type BoundaryColourMeasured } from './boundarycolour.ts';
12
12
  import { BEHIND_SEAM_LINE, behindTurnAnimations, measureBehindSeams, type BehindSeamsMeasured } from './behindseams.ts';
13
+ import { hasSourceStateMaps, measureSourceExposure, readSourceStateMaps, SOURCE_EXPOSURE_LINE, type SourceExposureMeasured } from './sourceexposure.ts';
13
14
  import { baseAnchorMoves, type AnchorRegion } from './baseanchor.ts';
14
15
  import { PHYSICS_CONTRIBUTES_LINE, measurePhysicsContribution, physicsLine, type PhysicsContributionLine } from './physicscontrib.ts';
15
16
  /**
@@ -1230,10 +1231,11 @@ function withoutSliders(rig: Record<string, unknown>, animations: Record<string,
1230
1231
  * `constraints` entry of `type` `"physics"` and every entry of motion.json's
1231
1232
  * `physics` table are dropped, with what names them only to activate or key
1232
1233
  * them — a skin's `physics` list, and an animation track whose target is a
1233
- * `physics` constraint. Nothing else is touched, and nothing here judges the
1234
- * constraints: the line that names them reports.
1234
+ * `physics` constraint. A named animation beside the idle is dropped if this
1235
+ * removes its last timeline. The idle still has to pass the keyed build's
1236
+ * gate. The line naming what was left out reports it.
1235
1237
  */
1236
- export function withoutPhysics(rig: Record<string, unknown>, motion: Record<string, unknown>): { rig: Record<string, unknown>; motion: Record<string, unknown>; physics: LoopPhysics[] } | null {
1238
+ export function withoutPhysics(rig: Record<string, unknown>, motion: Record<string, unknown>): { rig: Record<string, unknown>; motion: Record<string, unknown>; physics: LoopPhysics[]; droppedAnimations: string[] } | null {
1237
1239
  const physics: LoopPhysics[] = [];
1238
1240
  const constraints = Array.isArray(rig.constraints) ? rig.constraints : null;
1239
1241
  if (constraints !== null) {
@@ -1258,18 +1260,29 @@ export function withoutPhysics(rig: Record<string, unknown>, motion: Record<stri
1258
1260
  }
1259
1261
  const m: Record<string, unknown> = { ...motion };
1260
1262
  delete m.physics;
1263
+ const droppedAnimations: string[] = [];
1261
1264
  if (isRecord(motion.animations)) {
1262
- m.animations = Object.fromEntries(Object.entries(motion.animations).map(([name, a]) => {
1263
- if (!isRecord(a) || !Array.isArray(a.tracks)) return [name, a];
1264
- return [name, { ...a, tracks: a.tracks.filter((t) => !(isRecord(t) && 'physics' in t)) }];
1265
+ m.animations = Object.fromEntries(Object.entries(motion.animations).flatMap(([name, a]): Array<[string, unknown]> => {
1266
+ if (!isRecord(a) || !Array.isArray(a.tracks)) return [[name, a]];
1267
+ const tracks = a.tracks.filter((t) => !(isRecord(t) && 'physics' in t));
1268
+ if (tracks.length === a.tracks.length) return [[name, a]];
1269
+ const hasOtherTimeline = [a.ik, a.transform, a.deform, a.sequence, a.drawOrder, a.events]
1270
+ .some(timeline => Array.isArray(timeline) && timeline.length > 0);
1271
+ if (name !== 'idle' && tracks.length === 0 && !hasOtherTimeline) {
1272
+ droppedAnimations.push(name);
1273
+ return [];
1274
+ }
1275
+ return [[name, { ...a, tracks }]];
1265
1276
  }));
1266
1277
  }
1267
- return { rig: r, motion: m, physics };
1278
+ return { rig: r, motion: m, physics, droppedAnimations };
1268
1279
  }
1269
1280
 
1270
1281
  /** The one line naming what {@link withoutPhysics} left out of the loop's frames: reported, not judged. */
1271
- export function loopPhysicsLine(physics: readonly LoopPhysics[]): string {
1272
- return `loop physics: ${physics.length} physics constraint(s) left out of the loop's frames, reported, not judged — ${physics.map((p) => `"${p.name}" on bone "${p.bone}" (${p.in})`).join(', ')}`;
1282
+ export function loopPhysicsLine(physics: readonly LoopPhysics[], droppedAnimations: readonly string[] = []): string {
1283
+ const dropped = droppedAnimations.length === 0 ? ''
1284
+ : `; physics-only animation(s) omitted from the keyed build: ${droppedAnimations.map(name => JSON.stringify(name)).join(', ')}`;
1285
+ return `loop physics: ${physics.length} physics constraint(s) left out of the loop's frames, reported, not judged — ${physics.map((p) => `"${p.name}" on bone "${p.bone}" (${p.in})`).join(', ')}${dropped}`;
1273
1286
  }
1274
1287
 
1275
1288
  // ---------------------------------------------------------------------------
@@ -2881,6 +2894,7 @@ export interface CheckFigures {
2881
2894
  [BOUNDARY_COLOUR_LINE]?: BoundaryColourMeasured;
2882
2895
  /** Issue #1314: omitted unless behind_seams is declared; undeclared preserves existing check.json bytes. */
2883
2896
  [BEHIND_SEAM_LINE]?: BehindSeamsMeasured;
2897
+ [SOURCE_EXPOSURE_LINE]?: SourceExposureMeasured;
2884
2898
  PASS: boolean;
2885
2899
  }
2886
2900
 
@@ -3340,7 +3354,7 @@ export function checkStatuses(fig: Omit<CheckFigures, 'spec' | 'bar_outcomes' |
3340
3354
  const bar = (id: 'gate' | 'loop' | 'seam', measured: boolean): CheckStatus => (!measured ? 'SKIP' : checkBarStatus(raw, id) === 'FAIL' ? 'FAIL' : 'PASS');
3341
3355
  const out: Record<string, CheckStatus> = { gate: bar('gate', true), loop: bar('loop', fig.loop_max_diff !== null), seam: bar('seam', fig.seam_mean !== null) };
3342
3356
  for (const n of JUDGEMENT_LINES) out[n] = fig[n].status;
3343
- for (const n of [FOLD_LINE, LEVEL_LINE, STRESS_LINE, LIMB_LINE, SWEEP_LINE, MOTION_SEAM_LINE, CLOTH_LINE, PHYSICS_CONTRIBUTES_LINE, ...REPORTED_LINES, 'figure_openings', SOURCE_LINE, WIND_BAND_LINE, ART_JOINT_LINE, CUT_MATERIAL_LINE, SETUP_PAINTING_LINE, BOUNDARY_COLOUR_LINE, BEHIND_SEAM_LINE, COINCIDE_LINE] as const) {
3357
+ for (const n of [FOLD_LINE, LEVEL_LINE, STRESS_LINE, LIMB_LINE, SWEEP_LINE, MOTION_SEAM_LINE, CLOTH_LINE, PHYSICS_CONTRIBUTES_LINE, ...REPORTED_LINES, 'figure_openings', SOURCE_LINE, WIND_BAND_LINE, ART_JOINT_LINE, CUT_MATERIAL_LINE, SETUP_PAINTING_LINE, BOUNDARY_COLOUR_LINE, BEHIND_SEAM_LINE, SOURCE_EXPOSURE_LINE, COINCIDE_LINE] as const) {
3344
3358
  const l = fig[n];
3345
3359
  if (l !== undefined) out[n] = l.status;
3346
3360
  }
@@ -3352,9 +3366,9 @@ export function checkStatuses(fig: Omit<CheckFigures, 'spec' | 'bar_outcomes' |
3352
3366
  * idle (issue #183), or null when it holds none, so a rig of the idle alone
3353
3367
  * prints what it printed before.
3354
3368
  */
3355
- export function besideIdleLine(names: readonly string[], level = false): string | null {
3369
+ export function besideIdleLine(names: readonly string[], level = false, skipsKeyedAnimations = false): string | null {
3356
3370
  if (names.length === 0) return null;
3357
- const readers = level ? `${FOLD_LINE} reads each for folds and ${LEVEL_LINE} for how far the feet turn` : `${FOLD_LINE} reads each for folds`;
3371
+ const readers = level ? `${FOLD_LINE} reads each for folds and ${LEVEL_LINE} for how far the feet turn${skipsKeyedAnimations ? ' in the remaining keyed animations' : ''}` : `${FOLD_LINE} reads each for folds`;
3358
3372
  return `beside the idle: ${names.length} animation(s), ${names.join(', ')} — built and gated by rigc with the rig; ${readers}, every other bar here reads the idle`;
3359
3373
  }
3360
3374
 
@@ -3401,9 +3415,9 @@ export interface FoldRow {
3401
3415
  triangles: number;
3402
3416
  /** The reading with physics on, or null when the mesh folds only with physics off. */
3403
3417
  physics_on: FoldSide | null;
3404
- /** The reading with physics off, or null when the mesh folds only with physics on. */
3418
+ /** The reading with physics off, or null when that side found no fold or skipped this animation. */
3405
3419
  physics_off: FoldSide | null;
3406
- /** When the mesh folds only with physics on (`physics_on !== null && physics_off === null`), the physics constraints on its bones (`<name> on <bone>`); empty otherwise. */
3420
+ /** When physics on found a fold and physics off measured none, the physics constraints on the mesh's bones (`<name> on <bone>`); empty otherwise. */
3407
3421
  physics_constraints: string[];
3408
3422
  /** The `may_fold` entry's why when the requirements file declares this slot and animation; null when nothing does. */
3409
3423
  declared: string | null;
@@ -3414,11 +3428,13 @@ export interface FoldRow {
3414
3428
  /** `check.json`'s `ANIMATIONS_DO_NOT_FOLD`: written whenever the motion holds an animation, the idle included. */
3415
3429
  export interface FoldsLine {
3416
3430
  status: 'PASS' | 'FAIL';
3417
- /** Every animation, the idle included, in motion.json's order: each one read. */
3431
+ /** Every animation read on the original build, the idle included, in motion.json's order. */
3418
3432
  animations: string[];
3419
3433
  fps: number;
3420
3434
  /** How many physics constraints the rig declares ({@link withoutPhysics}) — stepped in `physics_on` and left out in `physics_off`; 0 when the rig has none. */
3421
3435
  physics_left_out: number;
3436
+ /** Animations omitted from the keyed build when stripping physics removed their last timeline. */
3437
+ physics_off_skipped?: string[];
3422
3438
  /** Every mesh that folds in an animation read, in that animation's order and rigc's mesh order. */
3423
3439
  folding: FoldRow[];
3424
3440
  /** The rows no `may_fold` entry takes: the bar's figure. */
@@ -3644,7 +3660,9 @@ export function foldsLine(
3644
3660
  motion: Record<string, unknown> = {},
3645
3661
  context?: WeightStepContext,
3646
3662
  slotParts?: ReadonlyMap<string, string>,
3663
+ physicsOffSkipped: readonly string[] = [],
3647
3664
  ): FoldsLine {
3665
+ const offSkipped = new Set(physicsOffSkipped);
3648
3666
  const toSide = (m: FoldingMesh | undefined): FoldSide | null =>
3649
3667
  m === undefined ? null : { frames: m.frames, worst_frame: m.worstFrame, worst_triangles: m.worstTriangles, line: m.line };
3650
3668
  const folding: FoldRow[] = [];
@@ -3667,7 +3685,7 @@ export function foldsLine(
3667
3685
  const off = offList.find((m) => m.slot === slot && m.attachment === attachment);
3668
3686
  const primary = (on ?? off) as FoldingMesh;
3669
3687
  const entry = mayFold.find((e) => e.slot === slot && e.animation === name);
3670
- const onlyPhysicsOn = on !== undefined && off === undefined;
3688
+ const onlyPhysicsOn = on !== undefined && off === undefined && !offSkipped.has(name);
3671
3689
  const constraints = onlyPhysicsOn ? meshPhysicsConstraints(rig, slot, attachment, physicsList) : [];
3672
3690
  const row: FoldRow = {
3673
3691
  ...checkSlotRow('ANIMATIONS_DO_NOT_FOLD.folding', entry === undefined, slot, slotParts),
@@ -3688,14 +3706,16 @@ export function foldsLine(
3688
3706
  worstOf.set(row, primary.worstTriangleList);
3689
3707
  }
3690
3708
  }
3691
- const physics =
3709
+ const physics = (name: string): string =>
3692
3710
  physicsLeftOut === 0
3693
3711
  ? ''
3694
- : `, with its ${physicsLeftOut} physics constraint(s) on and off`;
3712
+ : `, with its ${physicsLeftOut} physics constraint(s) ${offSkipped.has(name) ? 'on' : 'on and off'}`;
3695
3713
  for (const r of folding) {
3696
3714
  if (r.declared !== null) continue;
3697
3715
  const sideClause =
3698
- r.physics_on !== null && r.physics_off === null && physicsLeftOut > 0
3716
+ offSkipped.has(r.animation)
3717
+ ? ' (physics off: SKIP — removing physics leaves no timeline)'
3718
+ : r.physics_on !== null && r.physics_off === null && physicsLeftOut > 0
3699
3719
  ? ` (physics on: ${r.physics_on.frames} frame(s), worst frame ${r.physics_on.worst_frame} (${r.physics_on.worst_triangles}/${r.triangles} triangle(s)); physics off: 0 frame(s); physics constraint(s) on mesh "${r.attachment}": ${r.physics_constraints.join(', ')})`
3700
3720
  : r.physics_on !== null && r.physics_off !== null && physicsLeftOut > 0
3701
3721
  ? ` (physics on: ${r.physics_on.frames} frame(s), worst frame ${r.physics_on.worst_frame}; physics off: ${r.physics_off.frames} frame(s), worst frame ${r.physics_off.worst_frame})`
@@ -3705,7 +3725,7 @@ export function foldsLine(
3705
3725
  problems.push({
3706
3726
  code: `CHECK_${FOLD_LINE}`,
3707
3727
  object: `animation "${r.animation}", mesh "${r.attachment}" (slot "${r.slot}")`,
3708
- detail: `rigc render --folds at ${fps} fps${physics}${sideClause}: ${r.line}; ${foldBonesText(rig, motion, r.slot, r.attachment, r.worst_frame, worstOf.get(r) ?? [], context)}; no triangle turned over against the setup pose is required — a fold the art means is declared in the --requirements file's may_fold, { "slot": "${r.slot}", "animation": "${r.animation}", "why": … }`,
3728
+ detail: `rigc render --folds at ${fps} fps${physics(r.animation)}${sideClause}: ${r.line}; ${foldBonesText(rig, motion, r.slot, r.attachment, r.worst_frame, worstOf.get(r) ?? [], context)}; no triangle turned over against the setup pose is required — a fold the art means is declared in the --requirements file's may_fold, { "slot": "${r.slot}", "animation": "${r.animation}", "why": … }`,
3709
3729
  });
3710
3730
  }
3711
3731
  const declaredNotFolding = mayFold.filter((e) => !folding.some((r) => r.slot === e.slot && r.animation === e.animation)).map((e) => ({ ...checkSlotRow('ANIMATIONS_DO_NOT_FOLD.declared_not_folding', true, e.slot, slotParts), slot: e.slot, animation: e.animation }));
@@ -3713,7 +3733,7 @@ export function foldsLine(
3713
3733
  problems.push({
3714
3734
  code: `CHECK_${FOLD_LINE}`,
3715
3735
  object: `${requirementsPath ?? 'the requirements file'} may_fold (slot "${e.slot}", animation "${e.animation}")`,
3716
- detail: `declares a fold, and rigc render --folds at ${fps} fps${physics} reads no folded triangle on slot "${e.slot}" in animation "${e.animation}"; an exception that excepts nothing is taken out of the file`,
3736
+ detail: `declares a fold, and rigc render --folds at ${fps} fps${physics(e.animation)} reads no folded triangle on slot "${e.slot}" in animation "${e.animation}"; an exception that excepts nothing is taken out of the file`,
3717
3737
  });
3718
3738
  }
3719
3739
  const undeclared = folding.filter((r) => r.declared === null).length;
@@ -3722,6 +3742,7 @@ export function foldsLine(
3722
3742
  animations: [...named],
3723
3743
  fps,
3724
3744
  physics_left_out: physicsLeftOut,
3745
+ ...(physicsOffSkipped.length === 0 ? {} : { physics_off_skipped: [...physicsOffSkipped] }),
3725
3746
  folding,
3726
3747
  folding_undeclared: undeclared,
3727
3748
  declared_not_folding: declaredNotFolding,
@@ -3911,7 +3932,8 @@ export function levelLine(feet: readonly LevelFoot[], rig: Record<string, unknow
3911
3932
  const names = readings.map((r) => r.animation);
3912
3933
  const line: LevelLine = { status, animations: names, fps, physics_left_out: physicsLeftOut, bar_degrees: LEVEL_BAR_DEGREES, bar: LEVEL_BAR_SOURCE, feet: rows.map(row => ({ ...row, ...checkRow('FEET_STAY_LEVEL.feet', 'part', row.status === 'FAIL', [row.part]) })) };
3913
3934
  if (status === 'SKIP') {
3914
- line.reason = `no frame of ${names.map((n) => `"${n}"`).join(', ')} turns a bone above ${rows.map((r) => `"${r.bone}" (which "${r.part}" rides)`).join(', ')}, so no foot was seen while its leg was posed`;
3935
+ line.reason = names.length === 0 ? 'no animation remains in the physics-off build'
3936
+ : `no frame of ${names.map((n) => `"${n}"`).join(', ')} turns a bone above ${rows.map((r) => `"${r.bone}" (which "${r.part}" rides)`).join(', ')}, so no foot was seen while its leg was posed`;
3915
3937
  }
3916
3938
  return line;
3917
3939
  }
@@ -6877,6 +6899,8 @@ export function runCheck(rigDir: string, outDir: string, rigc: RigcRunner, parts
6877
6899
  if (wb !== null) take(() => resolveWindBand(wb, ready));
6878
6900
  refuseIfAny(refused);
6879
6901
  }
6902
+ // Issue #1473: every source-state map is verified before anything is built; a rig without one reads nothing here.
6903
+ if (hasSourceStateMaps(inp.parts)) readSourceStateMaps(inp.parts as PartsFile, inp.partsDir);
6880
6904
  // Issue #538: a motion with no animation gives check no render a schedule could pose — every frame it reads would be
6881
6905
  // the setup still's — so the flag is refused rather than recorded over readings it did not move.
6882
6906
  if (env !== null && !(isRecord(inp.motion.animations) && Object.keys(inp.motion.animations).length > 0)) {
@@ -6961,7 +6985,7 @@ export function runCheck(rigDir: string, outDir: string, rigc: RigcRunner, parts
6961
6985
  let loopSet: FrameSet | null = null;
6962
6986
  let loopPhysics: LoopPhysics[] | null = null;
6963
6987
  // The keyed build (issues #183, #320): with a physics constraint, the same rig and motion with every one left out,
6964
- // built once the same way, which the loop and the folds of every animation are both read from.
6988
+ // built once the same way for the loop and the physics-off reading of the remaining animations.
6965
6989
  const stripped = withoutPhysics(inp.rig, inp.motion);
6966
6990
  let keyed: string | null = null;
6967
6991
  const keyedBuild = (what: string): string => {
@@ -7116,17 +7140,21 @@ export function runCheck(rigDir: string, outDir: string, rigc: RigcRunner, parts
7116
7140
  const offDir = join(foldDir, 'off');
7117
7141
  const frOn = measured(['render', '--candidate', buildDir, '--folds', '--fps', String(fps), '--max', String(FOLD_RENDER_MAX), '--out', onDir]);
7118
7142
  if (frOn.status !== 0) refuseIfAny(rigcFailed(`render --folds --fps ${fps}`, frOn, frOn.out.split('\n').filter((l) => l.includes('FAIL') || l.includes('rigc:'))));
7119
- // The physics-off half takes no schedule (issue #538): its candidate declares no physics constraint, so no
7120
- // world moves it, and rigc render refuses a schedule on it by name.
7121
- const frOff = rigc(['render', '--candidate', keyedBuild('the animations with their physics constraint(s) left out'), '--folds', ...geometry, '--fps', String(fps), '--max', String(FOLD_RENDER_MAX), '--out', offDir]);
7122
- if (frOff.status !== 0) refuseIfAny(rigcFailed(`render --folds${geometry.map((g) => ` ${g}`).join('')} --fps ${fps} (physics constraint(s) left out)`, frOff, frOff.out.split('\n').filter((l) => l.includes('FAIL') || l.includes('rigc:'))));
7123
7143
  const readingsOn = filterFolds(readFoldSets(onDir, animationNames, fps, frOn.out));
7124
- const readingsOff = filterFolds(readFoldSets(offDir, animationNames, fps, frOff.out));
7125
- folds = foldsLine(animationNames, fps, stripped.physics.length, readingsOn, mayFoldForRun, reqFile === null ? null : reqFile.path, foldProblems, readingsOff, inp.rig, stripped.physics, inp.motion, { config, stage: inp.stage }, checkSlotParts(inp.rig, inp.parts?.parts.map(p => p.name) ?? [], inp.parts?.alternates?.map(set => set.name) ?? []));
7144
+ const keyedNames = isRecord(stripped.motion.animations) ? Object.keys(stripped.motion.animations) : [];
7145
+ let readingsOff = new Map<string, FoldingMesh[]>();
7146
+ if (keyedNames.length > 0) {
7147
+ // The physics-off half takes no schedule (issue #538): its candidate declares no physics constraint, so no
7148
+ // world moves it, and rigc render refuses a schedule on it by name.
7149
+ const frOff = rigc(['render', '--candidate', keyedBuild('the animations with their physics constraint(s) left out'), '--folds', ...geometry, '--fps', String(fps), '--max', String(FOLD_RENDER_MAX), '--out', offDir]);
7150
+ if (frOff.status !== 0) refuseIfAny(rigcFailed(`render --folds${geometry.map((g) => ` ${g}`).join('')} --fps ${fps} (physics constraint(s) left out)`, frOff, frOff.out.split('\n').filter((l) => l.includes('FAIL') || l.includes('rigc:'))));
7151
+ readingsOff = filterFolds(readFoldSets(offDir, keyedNames, fps, frOff.out));
7152
+ }
7153
+ folds = foldsLine(animationNames, fps, stripped.physics.length, readingsOn, mayFoldForRun, reqFile === null ? null : reqFile.path, foldProblems, readingsOff, inp.rig, stripped.physics, inp.motion, { config, stage: inp.stage }, checkSlotParts(inp.rig, inp.parts?.parts.map(p => p.name) ?? [], inp.parts?.alternates?.map(set => set.name) ?? []), stripped.droppedAnimations);
7126
7154
  if (feet.length > 0) {
7127
- const sets = readJson(join(offDir, 'frames.json'), []);
7155
+ const sets = keyedNames.length === 0 ? null : readJson(join(offDir, 'frames.json'), []);
7128
7156
  const listed = sets !== null && Array.isArray(sets.sets) ? sets.sets.filter(isRecord) : [];
7129
- const levelReadings = animationNames.map((name) => {
7157
+ const levelReadings = keyedNames.map((name) => {
7130
7158
  const dir = join(offDir, String((listed.find((x) => x.animation === name) as Record<string, unknown>).dir));
7131
7159
  return { animation: name, set: readFrameSet(dir), geometryPath: join(dir, GEOMETRY_FILE) };
7132
7160
  });
@@ -7715,6 +7743,11 @@ export function runCheck(rigDir: string, outDir: string, rigc: RigcRunner, parts
7715
7743
  }
7716
7744
  }
7717
7745
 
7746
+ // Issue #1473: recorded-hidden and undecided source texels the poses show, where a part carries a map or a limit is declared.
7747
+ const exposureDeclared = reqFile?.source_exposure;
7748
+ const sourceExposure = exposureDeclared === undefined && !hasSourceStateMaps(inp.parts) ? null
7749
+ : measureSourceExposure(officialRenderer(), { build: buildDir, stage: inp.stage, parts: inp.parts, partsDir: inp.partsDir, imagesDir: typeof inp.rig.images === 'string' ? resolve(inp.rigDir, inp.rig.images) : join(inp.rigDir, 'images'), rig: inp.rig, fps: IDLE_FPS }, exposureDeclared, problems);
7750
+
7718
7751
  // 5. the scene's declared requirements (issue #93), only under --requirements
7719
7752
  const reqProblems: Problem[] = [];
7720
7753
  const reqBlock = reqFile === null || reqRecord === null ? null : { file: reqRecord, ...measureRequirements(inp, reqFile, buildDir, out, rigc, reqProblems, seams ?? new Map(), measured) };
@@ -7762,6 +7795,7 @@ export function runCheck(rigDir: string, outDir: string, rigc: RigcRunner, parts
7762
7795
  ...(setupPainting === null ? {} : { [SETUP_PAINTING_LINE]: setupPainting }),
7763
7796
  ...(boundaryColour === null ? {} : { [BOUNDARY_COLOUR_LINE]: boundaryColour }),
7764
7797
  ...(behindSeams === null ? {} : { [BEHIND_SEAM_LINE]: behindSeams }),
7798
+ ...(sourceExposure === null ? {} : { [SOURCE_EXPOSURE_LINE]: sourceExposure }),
7765
7799
  ...(cutMaterial === null ? {} : { [CUT_MATERIAL_LINE]: cutMaterial }),
7766
7800
  ...(reqBlock === null ? {} : { requirements: reqBlock }),
7767
7801
  };
@@ -7839,6 +7873,7 @@ export function runCheck(rigDir: string, outDir: string, rigc: RigcRunner, parts
7839
7873
  if (setupPainting !== null) tally(SETUP_PAINTING_LINE, setupPainting.status === 'SKIP' ? (setupPainting.reason ?? 'no declared limit') : null);
7840
7874
  if (boundaryColour !== null) tally(BOUNDARY_COLOUR_LINE, null);
7841
7875
  if (behindSeams !== null) tally(BEHIND_SEAM_LINE, behindSeams.status === 'SKIP' ? 'HOLE: no complete authored threshold reading; not a pass' : null);
7876
+ if (sourceExposure !== null) tally(SOURCE_EXPOSURE_LINE, sourceExposure.status === 'REPORTED' ? 'no declared limit; a measurement, never a pass' : null);
7842
7877
  // Issue #348: the level bar where it is written; a line whose every foot no frame posed says SKIP and is not measured.
7843
7878
  if (level !== null) tally(LEVEL_LINE, level.status === 'SKIP' ? (level.reason ?? '') : null);
7844
7879
  // Issue #347: the stress bar is counted where it is written — on every rig with a handwear part and an idle.
@@ -7857,7 +7892,7 @@ export function runCheck(rigDir: string, outDir: string, rigc: RigcRunner, parts
7857
7892
  pack,
7858
7893
  packOpaque,
7859
7894
  idle: idle === null || loop === null ? null : { frames: idle.frames.length, fps: idle.fps, duration: idle.duration, lastIndex: idle.frames[idle.frames.length - 1].index, loopAt: { x: loop.x, y: loop.y } },
7860
- loopPhysics: loopPhysics === null ? null : loopPhysicsLine(loopPhysics),
7895
+ loopPhysics: loopPhysics === null ? null : loopPhysicsLine(loopPhysics, stripped?.droppedAnimations),
7861
7896
  seamViewport,
7862
7897
  bars,
7863
7898
  problems,
package/src/checkrow.ts CHANGED
@@ -62,6 +62,8 @@ export const CHECK_ROW_PATHS = {
62
62
  'SEAM_OVER_RANGE.joints[].poses': ['SEAM_OVER_RANGE.joints[].poses'],
63
63
  'SETUP_MATCHES_PAINTING.regions': ['SETUP_MATCHES_PAINTING.regions'],
64
64
  'SETUP_MATCHES_PAINTING.regions[].slots': ['SETUP_MATCHES_PAINTING.regions[].slots'],
65
+ 'SOURCE_EXPOSURE.rows': ['SOURCE_EXPOSURE.rows'],
66
+ 'SOURCE_EXPOSURE.unmeasured': ['SOURCE_EXPOSURE.unmeasured'],
65
67
  'STILL_REGIONS_DARK.*.crossing': ['STILL_REGIONS_DARK.*.crossing'],
66
68
  'STILL_REGIONS_DARK.*.still_slots': ['STILL_REGIONS_DARK.*.still_slots'],
67
69
  'STRESS_OFF_CHAIN.not_read': ['STRESS_OFF_CHAIN.not_read'],
@@ -31,6 +31,7 @@ import { refuseIfAny } from '../errors.ts';
31
31
  import { checkGraph, type Graph } from '../graphs.ts';
32
32
  import {
33
33
  assertPlateOutFree,
34
+ clipClassifiedProps,
34
35
  CORE_DEFAULTS,
35
36
  coreCfg,
36
37
  type CoreParams,
@@ -112,6 +113,10 @@ export async function runBackground(connect: () => ComfyClient, run: BackgroundR
112
113
  }
113
114
  assertPlateOutFree(run.out);
114
115
  const mask = growMask(source, run.growPx);
116
+ const maskClassification = clipClassifiedProps(source, mask);
117
+ for (const { id, clipped_px } of maskClassification?.prop_clips ?? []) {
118
+ say(` classified background prop ${id}: clipped ${clipped_px} grown px`);
119
+ }
115
120
  const prepared = run.graph === 'core' ? prepareCoreGrid(painting.raster, mask) : { painting: painting.raster, mask };
116
121
  const uploadPaintingBytes = prepared.transform === undefined ? painting.bytes : encodePngBytes(prepared.painting);
117
122
  const uploadMaskBytes = encodePngBytes(maskImage(prepared.mask));
@@ -156,6 +161,7 @@ export async function runBackground(connect: () => ComfyClient, run: BackgroundR
156
161
  source: from.source,
157
162
  sourceDir: from.dir,
158
163
  mask,
164
+ maskClassification,
159
165
  plate: pasteInside(painting.raster, inpainted, mask),
160
166
  model: { name: model, checkpoint_sha256: checkpoint, checkpoint_sha256_from: 'declared' },
161
167
  params: { ...(run.graph === 'lama' ? lama : core), ...(occluderMode ? { holes: run.holes === true, mask_alpha_above: OCCLUDER_ALPHA_ABOVE } : { mask_alpha_above: OPAQUE_ALPHA_ABOVE }) },
@@ -29,13 +29,14 @@
29
29
  */
30
30
  import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, rmdirSync, writeFileSync } from 'node:fs';
31
31
  import { basename, dirname, join } from 'node:path';
32
- import { refuseIfAny } from '../errors.ts';
32
+ import { foldName, guidePointer, PartsError, refuseIfAny } from '../errors.ts';
33
33
  import { checkGraph, fillSeeThrough, type SeeThroughParams } from '../graphs.ts';
34
- import { readWrapperLayers } from '../layers.ts';
35
- import type { DepthBinding } from '../depthsheets.ts';
34
+ import { readWrapperLayers, type LayerSet } from '../layers.ts';
35
+ import { bindDepthRun, type DepthBinding } from '../depthsheets.ts';
36
36
  import { sha256 } from '../plate.ts';
37
37
  import { prepareSeeThroughInput } from '../seethrough-transform.ts';
38
38
  import { decodePngBytes, encodePngBytes } from '../raster/png.ts';
39
+ import { writeVisibilityRecord, type VisibilityIdentity } from '../visibility.ts';
39
40
  import { ComfyClient, historyImages, refuse } from './client.ts';
40
41
 
41
42
  export const SEETHROUGH_WORKFLOW = new URL('../../workflows/seethrough.json', import.meta.url);
@@ -78,6 +79,53 @@ function safeName(name: string): boolean {
78
79
  return name !== '' && !name.startsWith('.') && !/[\\/]/.test(name);
79
80
  }
80
81
 
82
+ /** Fetch the writer sheets once for visibility and optional geometry binding.
83
+ * An art-only run can finish when its optional writer sheets are unavailable.
84
+ */
85
+ async function captureVisibility(
86
+ client: ComfyClient, stage: string, set: LayerSet, depth: DepthBinding | undefined,
87
+ identity: VisibilityIdentity,
88
+ ): Promise<string | undefined> {
89
+ const skip = (detail: string): string => {
90
+ const reason = detail.replaceAll(stage + '/', '').replaceAll(client.host, 'the box');
91
+ return `WARN VISIBILITY_SOURCE: visibility.json — ${reason}; the run has no visibility record${guidePointer('VISIBILITY_SOURCE')}`;
92
+ };
93
+ const missing = set.layers.find(layer => layer.depthHint === undefined);
94
+ if (depth === undefined && missing !== undefined) {
95
+ return skip(set.layers.every(layer => layer.depthHint === undefined)
96
+ ? 'the wrapper declared no depth PNGs'
97
+ : `layer "${missing.name}" has no depth_filename`);
98
+ }
99
+ const occupied = new Set([...set.layers, ...set.hidden].map(layer => foldName(`${layer.name}.png`)));
100
+ const fetched: string[] = [];
101
+ try {
102
+ const entries = depth === undefined ? set.layers : [...set.layers, ...set.hidden];
103
+ for (const layer of entries) {
104
+ if (layer.depthHint === undefined) continue;
105
+ const filename = layer.depthHint.filename;
106
+ if (typeof filename !== 'string' || !safeName(filename)) {
107
+ refuse('COMFY_LAYER_NAME', `layer "${layer.name}" depth_filename`, 'requires a plain file name for the writer depth PNG');
108
+ }
109
+ const name = `${layer.name}_depth.png`;
110
+ const local = join(stage, 'parts', name);
111
+ if (occupied.has(foldName(name))) {
112
+ refuse('DEPTH_SHEET_UNAMBIGUOUS', name, 'the writer depth PNG collides with an art or depth PNG in this run; use distinct layer names');
113
+ }
114
+ writeFileSync(local, await client.view(filename), { flag: 'wx' });
115
+ occupied.add(foldName(name));
116
+ fetched.push(local);
117
+ }
118
+ if (missing !== undefined) return skip(`layer "${missing.name}" has no depth_filename`);
119
+ writeVisibilityRecord(stage, identity);
120
+ return undefined;
121
+ } catch (error) {
122
+ if (!(error instanceof PartsError) || depth !== undefined) throw error;
123
+ for (const file of fetched) rmSync(file);
124
+ const [first] = error.problems;
125
+ return skip(first === undefined ? 'the writer depth is unavailable' : `${first.object} — ${first.detail}`);
126
+ }
127
+ }
128
+
81
129
  export async function runSeeThrough(client: ComfyClient, run: SeeThroughRun, say: (line: string) => void): Promise<SeeThroughResult> {
82
130
  const depth = run.depth?.config === undefined ? undefined : run.depth;
83
131
  if (!existsSync(run.image)) refuse('COMFY_IMAGE_PRESENT', run.image, 'no such file; the PNG See-through is to decompose is required');
@@ -148,12 +196,15 @@ export async function runSeeThrough(client: ComfyClient, run: SeeThroughRun, say
148
196
  writeFileSync(join(stage, rel), layerBytes);
149
197
  layerHashes.push({ path: rel, sha256: sha256(layerBytes) });
150
198
  }
151
- 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));
152
199
  writeFileSync(join(stage, 'layers.json'), manifestBytes);
153
- const set = readWrapperLayers(stage, depth);
200
+ const set = readWrapperLayers(stage);
154
201
  if (prepared.transform !== undefined && (set.canvas.w !== run.resolution || set.canvas.h !== run.resolution)) {
155
202
  refuse('COMFY_MANIFEST_NAMED', `output/${infoLog}`, `canvas is ${set.canvas.w}x${set.canvas.h}; the prepared ${run.resolution}x${run.resolution} input grid is required`);
156
203
  }
204
+ const identity = { prompt_id: id, input_sha256: sha256(uploadBytes), graph_sha256: sha256(new TextEncoder().encode(JSON.stringify(graph))) };
205
+ const visibilityWarning = await captureVisibility(client, stage, set, depth, identity);
206
+ if (depth !== undefined) bindDepthRun(set, depth.run, depth.config, depth.base);
207
+ if (visibilityWarning !== undefined) say(` ${visibilityWarning}`);
157
208
  const meta = {
158
209
  prompt_id: id,
159
210
  image: run.image,
@@ -172,6 +223,9 @@ export async function runSeeThrough(client: ComfyClient, run: SeeThroughRun, say
172
223
  layer_names: layers.map((l) => l.name as string),
173
224
  layers: layerHashes,
174
225
  canvas: [set.canvas.w, set.canvas.h],
226
+ ...(visibilityWarning === undefined
227
+ ? { uploaded_image_sha256: identity.input_sha256, graph_sha256: identity.graph_sha256 }
228
+ : { visibility_warning: visibilityWarning }),
175
229
  ...(prepared.transform === undefined ? {} : { input_transform: prepared.transform }),
176
230
  };
177
231
  writeFileSync(join(stage, 'meta.json'), `${JSON.stringify(meta, null, 2)}\n`);