@rig-c/parts 2.32.0 → 2.34.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/config.ts CHANGED
@@ -1482,12 +1482,17 @@ export function configFileReferences(raw: unknown): ConfigFileReference[] {
1482
1482
  const target = parent;
1483
1483
  out.push({ at: field.path.join('.'), value, set: (next) => { target[key] = next; } });
1484
1484
  }
1485
- // Issue #1230: each declared occluder's image, an array field the single-path table above cannot name.
1485
+ // Issue #1230 / #1237: each declared occluder's image and optional plate directory, array fields the single-path table above cannot name.
1486
1486
  const assemble = isPlainObject(raw) ? raw.assemble : undefined;
1487
1487
  const occluders = isPlainObject(assemble) && Array.isArray(assemble.occluders) ? assemble.occluders : [];
1488
1488
  occluders.forEach((entry: unknown, i: number) => {
1489
- if (!isPlainObject(entry) || typeof entry.image !== 'string' || entry.image === '') return;
1490
- out.push({ at: `assemble.occluders[${i}].image`, value: entry.image, set: (next) => { entry.image = next; } });
1489
+ if (!isPlainObject(entry)) return;
1490
+ if (typeof entry.image === 'string' && entry.image !== '') {
1491
+ out.push({ at: `assemble.occluders[${i}].image`, value: entry.image, set: (next) => { entry.image = next; } });
1492
+ }
1493
+ if (typeof entry.plate === 'string' && entry.plate !== '') {
1494
+ out.push({ at: `assemble.occluders[${i}].plate`, value: entry.plate, set: (next) => { entry.plate = next; } });
1495
+ }
1491
1496
  });
1492
1497
  return out;
1493
1498
  }
@@ -1808,7 +1813,7 @@ function parseEarlyConfigFrom(raw: Json, door: EarlyDoor, base: string | null, p
1808
1813
  checkOccluders(c, a, null, base);
1809
1814
  if ('extend_painting' in a) checkPaintingExtensions(c, a.extend_painting);
1810
1815
  if ('edge_splits' in a) checkEdgeSplits(c, a.edge_splits, Array.isArray(a.plan) ? new Set(a.plan.filter((r): r is Json[] => Array.isArray(r) && typeof r[0] === 'string').map(r => r[0] as string)) : null);
1811
- if ('take' in a) checkTakeLayers(c, a.take);
1816
+ if ('take' in a) checkTakeLayers(c, a.take, null, a);
1812
1817
  if ('editor_receipts' in a) checkEditorReceipts(c, a.editor_receipts);
1813
1818
  if ('yield_refused' in a && typeof a.yield_refused !== 'boolean') {
1814
1819
  c.fail('CONFIG_FIELD_TYPE', 'config.assemble.yield_refused', `is ${show(a.yield_refused)}; true or false is required`);
@@ -2567,36 +2572,64 @@ function checkRequiredHiddenExtent(c: Check, a: Record<string, Json>, names: rea
2567
2572
  }
2568
2573
 
2569
2574
  /**
2570
- * Issue #1230: `config.assemble.occluders`, `[{image, sha256, under, rgb_within}]`. Shape at every door; `under`
2571
- * resolved against the plan where the door reads it; the file and its sha256 where the door knows the config's
2572
- * directory (`checkOccluderFiles`).
2575
+ * Issue #1230 / #1241 / #1246: `config.assemble.occluders`, `[{image, sha256, under, over?, rgb_within, plate?, part?}]`.
2576
+ * Shape at every door; `under`, `over` and `part` resolved against the plan where the door reads it; the file and its
2577
+ * sha256 where the door knows the config's directory (`checkOccluderFiles`). Returns the declared `part` names, in order.
2573
2578
  */
2574
- function checkOccluders(c: Check, a: Record<string, Json>, names: readonly string[] | null, base: string | null): void {
2575
- if (!('occluders' in a)) return;
2579
+ function checkOccluders(c: Check, a: Record<string, Json>, names: readonly string[] | null, base: string | null): string[] {
2580
+ if (!('occluders' in a)) return [];
2576
2581
  const at = 'config.assemble.occluders';
2577
- if (!c.array(at, a.occluders, false)) return;
2582
+ if (!c.array(at, a.occluders, false)) return [];
2578
2583
  const declarations: OccluderDeclaration[] = [];
2584
+ const partNames: string[] = [];
2579
2585
  (a.occluders as Json[]).forEach((value, i) => {
2580
2586
  const p = `${at}[${i}]`;
2581
- const row = c.object(p, value, ['image', 'sha256', 'under', 'rgb_within'], []);
2587
+ const row = c.object(p, value, ['image', 'sha256', 'under', 'rgb_within'], ['over', 'plate', 'part']);
2582
2588
  if (row === null) return;
2583
2589
  const imageOk = c.string(`${p}.image`, row.image);
2584
2590
  const shaOk = typeof row.sha256 === 'string' && SHA256_PATTERN.test(row.sha256);
2585
2591
  if (!shaOk) c.fail('CONFIG_FIELD_TYPE', `${p}.sha256`, `is ${show(row.sha256)}; ${SHA256_RULE} is required`);
2586
2592
  let underOk = c.array(`${p}.under`, row.under, true);
2587
2593
  if (underOk) (row.under as Json[]).forEach((name, j) => { if (!c.string(`${p}.under[${j}]`, name)) underOk = false; });
2594
+ let overOk = true;
2595
+ if ('over' in row) {
2596
+ overOk = c.array(`${p}.over`, row.over, true);
2597
+ if (overOk) (row.over as Json[]).forEach((name, j) => { if (!c.string(`${p}.over[${j}]`, name)) overOk = false; });
2598
+ }
2588
2599
  const rgbOk = typeof row.rgb_within === 'number' && Number.isInteger(row.rgb_within) && row.rgb_within >= 0 && row.rgb_within <= 255;
2589
2600
  if (!rgbOk) c.fail('CONFIG_FIELD_TYPE', `${p}.rgb_within`, `is ${show(row.rgb_within)}; an integer from 0 to 255 is required`);
2590
- if (imageOk && shaOk && underOk && rgbOk) declarations.push({ image: row.image as string, sha256: row.sha256 as string, under: row.under as string[], rgb_within: row.rgb_within as number });
2601
+ const plateOk = !('plate' in row) || c.string(`${p}.plate`, row.plate);
2602
+ let partOk = true;
2603
+ let partName: string | undefined;
2604
+ if ('part' in row) {
2605
+ partOk = c.string(`${p}.part`, row.part);
2606
+ if (partOk) {
2607
+ partName = row.part as string;
2608
+ if (!partNameOk(partName)) {
2609
+ c.fail('CONFIG_PART_NAME', `${p}.part`, `names the part ${show(partName)}; a part name is a file name, so it may not be empty, start with "." or hold a slash`);
2610
+ partOk = false;
2611
+ } else {
2612
+ partNames.push(partName);
2613
+ }
2614
+ }
2615
+ }
2616
+ if (imageOk && shaOk && underOk && overOk && rgbOk && plateOk && partOk) {
2617
+ declarations.push({ image: row.image as string, sha256: row.sha256 as string, under: row.under as string[], ...('over' in row ? { over: row.over as string[] } : {}), rgb_within: row.rgb_within as number, ...('plate' in row ? { plate: row.plate as string } : {}), ...(partName !== undefined ? { part: partName } : {}) });
2618
+ }
2591
2619
  });
2592
2620
  c.problems.push(...occluderNameProblems(declarations, names));
2593
2621
  if (base !== null) c.problems.push(...occluderFileProblems(declarations, base));
2622
+ return partNames;
2594
2623
  }
2595
2624
 
2596
2625
  /** The occluder files, at the doors that know the config's directory but read the plan elsewhere. */
2597
2626
  function checkOccluderFiles(c: Check, assemble: Json, base: string | null): void {
2598
2627
  if (base === null || !isPlainObject(assemble) || !Array.isArray(assemble.occluders)) return;
2599
- const declarations = (assemble.occluders as Json[]).filter((d): d is OccluderDeclaration => isPlainObject(d) && typeof d.image === 'string' && d.image !== '' && typeof d.sha256 === 'string' && SHA256_PATTERN.test(d.sha256));
2628
+ const declarations = (assemble.occluders as Json[]).flatMap((d): OccluderDeclaration[] => {
2629
+ if (!isPlainObject(d) || typeof d.image !== 'string' || d.image === '' || typeof d.sha256 !== 'string' || !SHA256_PATTERN.test(d.sha256)) return [];
2630
+ const plate = 'plate' in d && typeof d.plate === 'string' && d.plate !== '' ? { plate: d.plate } : {};
2631
+ return [{ image: d.image, sha256: d.sha256, under: [], rgb_within: 0, ...plate }];
2632
+ });
2600
2633
  c.problems.push(...occluderFileProblems(declarations, base));
2601
2634
  }
2602
2635
 
@@ -2613,16 +2646,19 @@ function checkKeepUnderOccluders(c: Check, a: Record<string, Json>, plan: readon
2613
2646
  });
2614
2647
  }
2615
2648
 
2616
- function checkTakeLayers(c: Check, value: Json, plan: string[] | null = null): void {
2649
+ function checkTakeLayers(c: Check, value: Json, plan: string[] | null = null, assemble?: Record<string, Json>): void {
2617
2650
  const at = 'config.assemble.take';
2618
2651
  if (!c.array(at, value, false)) return;
2619
2652
  const seen = new Set<string>();
2620
2653
  (value as Json[]).forEach((v, i) => {
2621
2654
  const p = `${at}[${i}]`;
2622
- const region = isPlainObject(v) && ('part' in v || 'seed' in v);
2623
- const o = region
2624
- ? c.object(p, v, ['run', 'run_dir', 'st_input', 'part', 'seed'], ['reference', 'crop'])
2625
- : c.object(p, v, ['run', 'run_dir', 'st_input', 'tags'], ['crop']);
2655
+ const split = isPlainObject(v) && ('occluder' in v || ('tag' in v && !('tags' in v)));
2656
+ const region = !split && isPlainObject(v) && ('part' in v || 'seed' in v);
2657
+ const o = split
2658
+ ? c.object(p, v, ['run', 'run_dir', 'st_input', 'part', 'tag', 'occluder'], ['crop'])
2659
+ : region
2660
+ ? c.object(p, v, ['run', 'run_dir', 'st_input', 'part', 'seed'], ['reference', 'crop'])
2661
+ : c.object(p, v, ['run', 'run_dir', 'st_input', 'tags'], ['crop']);
2626
2662
  if (o === null) return;
2627
2663
  if (o.run !== 'full' && o.run !== 'head') c.fail('CONFIG_FIELD_TYPE', p + '.run', '"full" or "head" is required');
2628
2664
  for (const k of ['run_dir', 'st_input']) c.string(`${p}.${k}`, o[k]);
@@ -2634,6 +2670,44 @@ function checkTakeLayers(c: Check, value: Json, plan: string[] | null = null): v
2634
2670
  if (crop.resample !== 'bilinear') c.fail('CONFIG_FIELD_TYPE', `${p}.crop.resample`, '"bilinear" is required explicitly');
2635
2671
  }
2636
2672
  }
2673
+ if (split) {
2674
+ const partName = c.string(`${p}.part`, o.part) ? o.part : null;
2675
+ if (partName !== null && plan !== null && !plan.includes(partName)) {
2676
+ c.fail('CONFIG_NAME_RESOLVES', `${p}.part`, `names "${partName}"; a part named in assemble.plan is required`);
2677
+ }
2678
+ const reading = typeof o.tag === 'string' ? readLayerTag(o.tag) : null;
2679
+ if (reading === null || reading.group === 'author') {
2680
+ c.fail('CONFIG_TAG_KNOWN', `${p}.tag`, 'a See-through tag is required; author layers do not carry a See-through role');
2681
+ } else if (partName !== null && plan !== null && plan.includes(partName) && Array.isArray(assemble?.plan)) {
2682
+ const row = assemble.plan.find((r): r is Json[] => Array.isArray(r) && r[0] === partName);
2683
+ if (row !== undefined && (row[1] !== o.run || row[2] !== o.tag)) {
2684
+ c.fail('CONFIG_NAME_RESOLVES', `${p}.tag`, `is "${String(o.run)}:${String(o.tag)}" for part "${partName}"; assemble.plan declares ["${partName}", "${String(row[1])}", "${String(row[2])}"]`);
2685
+ }
2686
+ }
2687
+ const tagKey = `${String(o.run)}:${String(o.tag)}`;
2688
+ const partKey = `${String(o.run)}:part:${String(o.part)}`;
2689
+ if (seen.has(tagKey) || seen.has(partKey)) {
2690
+ c.fail('CONFIG_TAKE_UNIQUE', `${p}.tag`, `names ${tagKey} again; one donor per target tag is required`);
2691
+ }
2692
+ seen.add(tagKey);
2693
+ seen.add(partKey);
2694
+ const occOk = c.int(`${p}.occluder`, o.occluder, 0);
2695
+ if (occOk && partName !== null && assemble !== undefined) {
2696
+ const occluders = Array.isArray(assemble.occluders) ? assemble.occluders : [];
2697
+ const idx = o.occluder as number;
2698
+ const entry = occluders[idx];
2699
+ const under = isPlainObject(entry) && Array.isArray(entry.under) ? entry.under : null;
2700
+ const over = isPlainObject(entry) && Array.isArray(entry.over) ? entry.over : [];
2701
+ if (!isPlainObject(entry) || under === null) {
2702
+ c.fail('ASSEMBLE_TAKE_SPLIT_OCCLUDER', `${p}.occluder`, `index ${idx} does not exist in config.assemble.occluders (${occluders.length} declared); a valid occluder index is required`);
2703
+ } else if (over.includes(partName)) {
2704
+ c.fail('ASSEMBLE_TAKE_SPLIT_OCCLUDER', `${p}.part`, `names "${partName}", which is in config.assemble.occluders[${idx}].over; a split take is for a part under the occluder, not in its over`);
2705
+ } else if (!under.includes(partName)) {
2706
+ c.fail('ASSEMBLE_TAKE_SPLIT_OCCLUDER', `${p}.part`, `names "${partName}", which is not in config.assemble.occluders[${idx}].under; a part declared under that occluder is required`);
2707
+ }
2708
+ }
2709
+ return;
2710
+ }
2637
2711
  if (region) {
2638
2712
  if (o.reference !== undefined) {
2639
2713
  const r = c.object(`${p}.reference`, o.reference, ['sha256'], ['source', 'painting']);
@@ -2759,10 +2833,10 @@ function checkAssemble(c: Check, v: Json, door: 'assemble' | 'full'): { parts: s
2759
2833
  }
2760
2834
  checkKeepUnderOccluders(c, a, parts);
2761
2835
  checkRequiredHiddenExtent(c, a, parts);
2762
- checkOccluders(c, a, parts, null);
2836
+ const occluderParts = checkOccluders(c, a, parts, null);
2763
2837
  if ('extend_painting' in a) checkPaintingExtensions(c, a.extend_painting);
2764
2838
  if ('edge_splits' in a) checkEdgeSplits(c, a.edge_splits, new Set(parts));
2765
- if ('take' in a) checkTakeLayers(c, a.take, parts);
2839
+ if ('take' in a) checkTakeLayers(c, a.take, parts, a);
2766
2840
  if ('editor_receipts' in a) checkEditorReceipts(c, a.editor_receipts);
2767
2841
  if ('extend_below_crop' in a && c.array(`${p}.extend_below_crop`, a.extend_below_crop, false)) {
2768
2842
  (a.extend_below_crop as Json[]).forEach((entry, i) => {
@@ -2784,7 +2858,7 @@ function checkAssemble(c: Check, v: Json, door: 'assemble' | 'full'): { parts: s
2784
2858
  }
2785
2859
  });
2786
2860
  }
2787
- const patches = 'patches' in a ? checkPatches(c, a.patches, parts) : [];
2861
+ const patches = [...('patches' in a ? checkPatches(c, a.patches, parts, occluderParts) : []), ...occluderParts];
2788
2862
  const cuts = 'cuts' in a ? checkCuts(c, a.cuts, parts, patches) : [];
2789
2863
  return { parts, patches, cuts };
2790
2864
  }
@@ -3112,7 +3186,7 @@ function checkAlternates(
3112
3186
  * (`ASSEMBLE_PATCH_BOX_INSIDE`, `ASSEMBLE_PATCH_OPAQUE`). Returns the patch
3113
3187
  * names, in order.
3114
3188
  */
3115
- function checkPatches(c: Check, v: Json, plan: string[]): string[] {
3189
+ function checkPatches(c: Check, v: Json, plan: string[], occluderParts: readonly string[] = []): string[] {
3116
3190
  const p = 'config.assemble.patches';
3117
3191
  const names: string[] = [];
3118
3192
  if (!c.array(p, v, false)) return names;
@@ -3133,6 +3207,7 @@ function checkPatches(c: Check, v: Json, plan: string[]): string[] {
3133
3207
  const name = e.name;
3134
3208
  if (!partNameOk(name)) c.fail('CONFIG_PART_NAME', `${at}.name`, `names the part ${show(name)}; a part name is a file name, so it may not be empty, start with "." or hold a slash`);
3135
3209
  if (plan.includes(name)) c.fail('CONFIG_PART_UNIQUE', `${at}.name`, `names the part "${name}", which assemble.plan[${plan.indexOf(name)}] already makes; a patch is a part of its own`);
3210
+ else if (occluderParts.includes(name)) c.fail('CONFIG_PART_UNIQUE', `${at}.name`, `names the part "${name}", which assemble.occluders already makes; a patch is a part of its own`);
3136
3211
  else if (seen.has(name)) c.fail('CONFIG_PART_UNIQUE', `${at}.name`, `names the part "${name}" again (first at patches[${seen.get(name)}])`);
3137
3212
  else seen.set(name, i);
3138
3213
  names.push(name);
package/src/occluders.ts CHANGED
@@ -28,43 +28,260 @@ export interface OccluderDeclaration {
28
28
  sha256: string;
29
29
  /** Plan parts the occluder stands in front of. */
30
30
  under: string[];
31
+ /** Plan parts that draw this occluder, in front of `under` (#1241). */
32
+ over?: string[];
31
33
  /** Max absolute channel difference from the painting at which an `under` pixel reads as the occluder's colour. */
32
34
  rgb_within: number;
35
+ /** An optional comfy plate --mode occluder output directory, relative to the config's directory (issue #1237). */
36
+ plate?: string;
37
+ /** An optional part name (`painting:<part>`) emitted from the painting for occluder pixels not held at rest by front parts (issue #1246). */
38
+ part?: string;
33
39
  }
34
40
 
35
41
  export const OCCLUDER_COLOUR_COPIED = 'ASSEMBLE_OCCLUDER_COLOUR_COPIED';
42
+ export const OCCLUDER_DRAW_ORDER = 'ASSEMBLE_OCCLUDER_DRAW_ORDER';
43
+ export const OCCLUDER_DRAW_CYCLE = 'ASSEMBLE_OCCLUDER_DRAW_CYCLE';
44
+ export const OCCLUDER_OVER_TAKEN = 'ASSEMBLE_OCCLUDER_OVER_TAKEN';
45
+ export const OCCLUDER_PLATE_OCCLUDER = 'ASSEMBLE_OCCLUDER_PLATE_OCCLUDER';
46
+ export const OCCLUDER_PLATE_PAINTING = 'ASSEMBLE_OCCLUDER_PLATE_PAINTING';
47
+ export const OCCLUDER_PLATE_BASE_RUN = 'ASSEMBLE_OCCLUDER_PLATE_BASE_RUN';
48
+ export const OCCLUDER_EMPTY = 'ASSEMBLE_OCCLUDER_EMPTY';
49
+ export const OCCLUDER_UNHELD = 'ASSEMBLE_OCCLUDER_UNHELD';
36
50
  /** An `under` layer pixel counts at alpha above this: the half-opaque floor `deriveTakenRegion` reads. */
37
51
  export const COPIED_ALPHA_ABOVE = 128;
38
52
 
39
53
  const AT = 'config.assemble.occluders';
40
54
 
41
- /** Every `under` entry names a plan part (`CONFIG_NAME_RESOLVES`); `names` null skips the check (a door without the plan). */
55
+ /** Contradictory `over` / `under` draw order across occluder entries (`ASSEMBLE_OCCLUDER_DRAW_CYCLE`). */
56
+ export function occluderDrawCycleProblems(declarations: readonly OccluderDeclaration[]): Problem[] {
57
+ const problems: Problem[] = [];
58
+ const edges = new Map<string, Map<string, number>>();
59
+ const vertices: string[] = [];
60
+ const addVertex = (name: string): void => {
61
+ if (!vertices.includes(name)) vertices.push(name);
62
+ };
63
+ declarations.forEach((d, i) => {
64
+ if (d.over === undefined) return;
65
+ for (const u of d.over) {
66
+ for (const v of d.under) {
67
+ if (u === v) {
68
+ problems.push({
69
+ code: OCCLUDER_DRAW_CYCLE,
70
+ object: `${AT}[${i}]`,
71
+ detail: `cycle ${u} -> ${u}: "${u}" is in both over and under of occluders[${i}]; a part cannot draw in front of itself`,
72
+ });
73
+ continue;
74
+ }
75
+ addVertex(u);
76
+ addVertex(v);
77
+ let row = edges.get(u);
78
+ if (row === undefined) {
79
+ row = new Map<string, number>();
80
+ edges.set(u, row);
81
+ }
82
+ if (!row.has(v)) row.set(v, i);
83
+ }
84
+ }
85
+ });
86
+ vertices.forEach((start, startIndex) => {
87
+ const startEdges = edges.get(start);
88
+ if (startEdges === undefined) return;
89
+ const visited = new Set<string>();
90
+ const queue: Array<{ node: string; path: string[]; steps: Array<[string, string, number]> }> = [];
91
+ for (const [next, ei] of startEdges) {
92
+ if (vertices.indexOf(next) > startIndex) {
93
+ visited.add(next);
94
+ queue.push({ node: next, path: [start, next], steps: [[start, next, ei]] });
95
+ }
96
+ }
97
+ while (queue.length > 0) {
98
+ const current = queue.shift()!;
99
+ const nextEdges = edges.get(current.node);
100
+ if (nextEdges === undefined) continue;
101
+ const back = nextEdges.get(start);
102
+ if (back !== undefined) {
103
+ const cycle = [...current.path, start];
104
+ const steps = [...current.steps, [current.node, start, back] as [string, string, number]];
105
+ problems.push({
106
+ code: OCCLUDER_DRAW_CYCLE,
107
+ object: AT,
108
+ detail: `cycle ${cycle.join(' -> ')} (${steps.map(([from, to, idx]) => `"${from}" over "${to}" in occluders[${idx}]`).join(', ')}); declared over/under draw order must be acyclic`,
109
+ });
110
+ break;
111
+ }
112
+ for (const [next, ei] of nextEdges) {
113
+ if (vertices.indexOf(next) > startIndex && !visited.has(next)) {
114
+ visited.add(next);
115
+ queue.push({ node: next, path: [...current.path, next], steps: [...current.steps, [current.node, next, ei]] });
116
+ }
117
+ }
118
+ }
119
+ });
120
+ return problems;
121
+ }
122
+
123
+ export interface DeclaredOccluderPair {
124
+ index: number;
125
+ over: string;
126
+ under: string;
127
+ }
128
+
129
+ /** First occluder entry declaring `(a, b)` or `(b, a)` as an `(over, under)` pair, or null when undeclared. */
130
+ export function declaredOccluderPair(declarations: readonly OccluderDeclaration[], a: string, b: string): DeclaredOccluderPair | null {
131
+ for (let i = 0; i < declarations.length; i++) {
132
+ const d = declarations[i];
133
+ if (d.over === undefined) continue;
134
+ if (d.over.includes(a) && d.under.includes(b)) return { index: i, over: a, under: b };
135
+ if (d.over.includes(b) && d.under.includes(a)) return { index: i, over: b, under: a };
136
+ }
137
+ return null;
138
+ }
139
+
140
+ /**
141
+ * Every declared `(over, under)` pair in `config.assemble.occluders` must draw `over` after `under`
142
+ * in the combined `config.assemble.plan` (back to front, `ASSEMBLE_OCCLUDER_DRAW_ORDER`).
143
+ */
144
+ export function occluderDrawOrderProblems(
145
+ declarations: readonly OccluderDeclaration[],
146
+ plan: ReadonlyArray<readonly [string, string, string]>,
147
+ ): Problem[] {
148
+ const problems: Problem[] = [];
149
+ for (let i = 0; i < plan.length; i++) {
150
+ for (let j = i + 1; j < plan.length; j++) {
151
+ const [partA, runA] = plan[i];
152
+ const [partB, runB] = plan[j];
153
+ const declared = declaredOccluderPair(declarations, partA, partB);
154
+ if (declared !== null && declared.over === partA) {
155
+ problems.push({
156
+ code: OCCLUDER_DRAW_ORDER,
157
+ object: runA === runB ? `${runA} plan parts "${partA}" / "${partB}"` : `plan parts "${partA}" (${runA}) / "${partB}" (${runB})`,
158
+ detail: `${AT}[${declared.index}] declares "${partA}" in over and "${partB}" in under, but config.assemble.plan draws "${partA}" behind "${partB}"; put "${partA}" after "${partB}" in config.assemble.plan (back to front)`,
159
+ });
160
+ }
161
+ }
162
+ }
163
+ return problems;
164
+ }
165
+
166
+ /** Every `over` part's plan layer (`run:tag`) must be taken by a whole-layer `assemble.take` declaration (`ASSEMBLE_OCCLUDER_OVER_TAKEN`). */
167
+ export function occluderOverTakenProblems(
168
+ declarations: readonly OccluderDeclaration[],
169
+ plan: ReadonlyArray<readonly [string, string, string]>,
170
+ taken: ReadonlyArray<{ run: string; tags: readonly string[] }>,
171
+ ): Problem[] {
172
+ const problems: Problem[] = [];
173
+ declarations.forEach((d, i) => {
174
+ d.over?.forEach((name, j) => {
175
+ const row = plan.find(([part]) => part === name);
176
+ if (row === undefined) return;
177
+ const [, run, tag] = row;
178
+ if (!taken.some((t) => t.run === run && t.tags.includes(tag))) {
179
+ problems.push({
180
+ code: OCCLUDER_OVER_TAKEN,
181
+ object: `${AT}[${i}].over[${j}]`,
182
+ detail: `part "${name}" (${run}:${tag}) is not taken by config.assemble.take; declare a whole-layer take for ${run}:${tag} or omit "${name}" from over`,
183
+ });
184
+ }
185
+ });
186
+ });
187
+ return problems;
188
+ }
189
+
190
+ /** Every `under` and `over` entry names a plan part (`CONFIG_NAME_RESOLVES`, with `over` entries distinct per occluder, `CONFIG_PART_UNIQUE`), and any declared `part` is distinct from plan parts and other occluder parts (`CONFIG_PART_UNIQUE`); `names` null skips the plan-membership check (a door without the plan). */
42
191
  export function occluderNameProblems(declarations: readonly OccluderDeclaration[], names: readonly string[] | null): Problem[] {
43
- if (names === null) return [];
44
192
  const problems: Problem[] = [];
45
- declarations.forEach((d, i) => d.under.forEach((name, j) => {
46
- if (!names.includes(name)) problems.push({ code: 'CONFIG_NAME_RESOLVES', object: `${AT}[${i}].under[${j}]`, detail: `names "${name}"; a part in config.assemble.plan is required` });
47
- }));
193
+ const seenParts = new Map<string, number>();
194
+ declarations.forEach((d, i) => {
195
+ if (d.over !== undefined) {
196
+ const seen = new Set<string>();
197
+ d.over.forEach((name, j) => {
198
+ if (seen.has(name)) problems.push({ code: 'CONFIG_PART_UNIQUE', object: `${AT}[${i}].over[${j}]`, detail: `names "${name}" again; each part is named once` });
199
+ seen.add(name);
200
+ });
201
+ }
202
+ if (d.part !== undefined && d.part !== '') {
203
+ if (names !== null && names.includes(d.part)) {
204
+ problems.push({ code: 'CONFIG_PART_UNIQUE', object: `${AT}[${i}].part`, detail: `names the part "${d.part}", which assemble.plan[${names.indexOf(d.part)}] already makes; an occluder part is a part of its own` });
205
+ } else if (names === null && (d.under.includes(d.part) || (d.over?.includes(d.part) ?? false))) {
206
+ problems.push({ code: 'CONFIG_PART_UNIQUE', object: `${AT}[${i}].part`, detail: `names the part "${d.part}", which occluders[${i}] also names in under/over; an occluder part is a part of its own` });
207
+ } else if (seenParts.has(d.part)) {
208
+ problems.push({ code: 'CONFIG_PART_UNIQUE', object: `${AT}[${i}].part`, detail: `names the part "${d.part}" again (first at occluders[${seenParts.get(d.part)}].part)` });
209
+ } else {
210
+ seenParts.set(d.part, i);
211
+ }
212
+ }
213
+ if (names === null) return;
214
+ d.under.forEach((name, j) => {
215
+ if (!names.includes(name)) problems.push({ code: 'CONFIG_NAME_RESOLVES', object: `${AT}[${i}].under[${j}]`, detail: `names "${name}"; a part in config.assemble.plan is required` });
216
+ });
217
+ d.over?.forEach((name, j) => {
218
+ if (!names.includes(name)) problems.push({ code: 'CONFIG_NAME_RESOLVES', object: `${AT}[${i}].over[${j}]`, detail: `names "${name}"; a part in config.assemble.plan is required` });
219
+ });
220
+ });
221
+ problems.push(...occluderDrawCycleProblems(declarations));
48
222
  return problems;
49
223
  }
50
224
 
51
- /** The image is a file beside the config (`CONFIG_FILE_PRESENT`) whose bytes hash to `sha256` (`CONFIG_OCCLUDER_SHA256`). */
225
+ /** The image is a file beside the config (`CONFIG_FILE_PRESENT`) whose bytes hash to `sha256` (`CONFIG_OCCLUDER_SHA256`), and an optional `plate` names a plate output directory holding `receipt.json`. */
52
226
  export function occluderFileProblems(declarations: readonly OccluderDeclaration[], base: string): Problem[] {
53
227
  const problems: Problem[] = [];
54
228
  declarations.forEach((d, i) => {
55
229
  const path = resolve(base, d.image);
56
230
  if (!existsSync(path) || !statSync(path).isFile()) {
57
231
  problems.push({ code: 'CONFIG_FILE_PRESENT', object: `${AT}[${i}].image`, detail: `names ${d.image}, which is no such file; an RGBA PNG of the occluder on the painting's grid, relative to the config's directory, is required` });
58
- return;
232
+ } else {
233
+ const found = fileSha256(path);
234
+ if (SHA256_PATTERN.test(d.sha256) && found !== d.sha256) {
235
+ problems.push({ code: 'CONFIG_OCCLUDER_SHA256', object: `${AT}[${i}].sha256`, detail: `is ${d.sha256}; ${d.image} has sha256 ${found} — declare the bytes the occluder image holds` });
236
+ }
59
237
  }
60
- const found = fileSha256(path);
61
- if (SHA256_PATTERN.test(d.sha256) && found !== d.sha256) {
62
- problems.push({ code: 'CONFIG_OCCLUDER_SHA256', object: `${AT}[${i}].sha256`, detail: `is ${d.sha256}; ${d.image} has sha256 ${found} — declare the bytes the occluder image holds` });
238
+ if (d.plate !== undefined) {
239
+ const plateDir = resolve(base, d.plate);
240
+ const receiptPath = resolve(plateDir, 'receipt.json');
241
+ if (!existsSync(plateDir) || !statSync(plateDir).isDirectory() || !existsSync(receiptPath) || !statSync(receiptPath).isFile()) {
242
+ problems.push({ code: 'CONFIG_FILE_PRESENT', object: `${AT}[${i}].plate`, detail: `names ${d.plate} (${plateDir}), which holds no receipt.json; a comfy plate --mode occluder output directory relative to the config's directory is required` });
243
+ }
63
244
  }
64
245
  });
65
246
  return problems;
66
247
  }
67
248
 
249
+ /**
250
+ * Reorder a draft `assemble.plan` in place so each declared `occluders[i].over`
251
+ * part sits after every `under` part of the same entry across `full` and `head`
252
+ * rows, keeping every other row's relative order unchanged (issue #1247).
253
+ */
254
+ export function orderPlanForOccluders<T extends readonly [string, ...unknown[]]>(
255
+ plan: T[],
256
+ declarations: readonly OccluderDeclaration[] | undefined,
257
+ ): void {
258
+ if (declarations === undefined || declarations.length === 0) return;
259
+ for (let pass = 0; pass <= plan.length; pass++) {
260
+ let moved = false;
261
+ for (const d of declarations) {
262
+ if (d.over === undefined || d.over.length === 0) continue;
263
+ const underSet = new Set(d.under);
264
+ let lastUnder = -1;
265
+ for (let i = 0; i < plan.length; i++) {
266
+ if (underSet.has(plan[i][0])) lastUnder = i;
267
+ }
268
+ if (lastUnder < 0) continue;
269
+ const overSet = new Set(d.over);
270
+ const beforeOver: T[] = [];
271
+ const keptBefore: T[] = [];
272
+ for (let i = 0; i < lastUnder; i++) {
273
+ if (overSet.has(plan[i][0])) beforeOver.push(plan[i]);
274
+ else keptBefore.push(plan[i]);
275
+ }
276
+ if (beforeOver.length === 0) continue;
277
+ const after = plan.slice(lastUnder + 1);
278
+ plan.splice(0, plan.length, ...keptBefore, plan[lastUnder], ...beforeOver, ...after);
279
+ moved = true;
280
+ }
281
+ if (!moved) break;
282
+ }
283
+ }
284
+
68
285
  export interface OccluderCopy {
69
286
  part: string;
70
287
  px: number;
@@ -100,3 +317,7 @@ export function occluderColourCopies(parts: ReadonlyArray<{ name: string; image:
100
317
  export function occluderColourWarning(index: number, copy: OccluderCopy, rgbWithin: number): string {
101
318
  return `WARN ${OCCLUDER_COLOUR_COPIED}: ${AT}[${index}] part "${copy.part}" — ${copy.px} rig px of its selected layer at alpha > ${COPIED_ALPHA_ABOVE} under the occluder (alpha > 0) lie within ${rgbWithin} of the painting (max channel); first at ${copy.first[0]},${copy.first[1]}; the layer holds the occluder's own colour — take this part from a See-through run on the painting with the occluder removed (comfy plate --mode occluder)`;
102
319
  }
320
+
321
+ export function occluderUnheldWarning(index: number, image: string, under: readonly string[], px: number, first: readonly [number, number]): string {
322
+ return `WARN ${OCCLUDER_UNHELD}: ${AT}[${index}] — ${px} rig px of occluder "${image}" (alpha > 8, first at ${first[0]},${first[1]}) are not held at alpha >= 250 by any part drawn in front of under [${under.map((u) => `"${u}"`).join(', ')}]; declare ${AT}[${index}].part to fill the unheld occluder pixels`;
323
+ }
@@ -1,19 +1,30 @@
1
1
  /**
2
- * The assemble stage's reading of `config.assemble.occluders` (issue #1230):
2
+ * The assemble stage's reading of `config.assemble.occluders` (issues #1230, #1237):
3
3
  * each declaration's image read and held to its sha256 and to the painting's
4
4
  * size, each `under` part's selected source layer placed on the rig grid the
5
5
  * way the hidden-extent reading places it (after any take, before projection
6
- * or cleanup), and every copied-colour pixel counted ({@link occluderColourCopies}).
7
- * It returns WARN lines and changes no output byte.
6
+ * or cleanup), every copied-colour pixel counted ({@link occluderColourCopies}),
7
+ * and each declared `plate` receipt verified and bound to the occluder, the
8
+ * `--source` painting and the base (`--full`) See-through run's input image.
8
9
  */
9
10
  import { createHash } from 'node:crypto';
10
- import { readFileSync } from 'node:fs';
11
- import { dirname, resolve } from 'node:path';
11
+ import { existsSync, readFileSync, statSync } from 'node:fs';
12
+ import { dirname, join, resolve } from 'node:path';
12
13
  import { checkGeometry, layerToRig, padSingleRun, placeLayer, sourceInRig } from './assemble.ts';
13
14
  import type { PlanEntry } from './config.ts';
15
+ import { SHA256_PATTERN } from './editreceipt.ts';
14
16
  import { PartsError } from './errors.ts';
15
17
  import type { LayerSet } from './layers.ts';
16
- import { type OccluderDeclaration, occluderColourCopies, occluderColourWarning } from './occluders.ts';
18
+ import {
19
+ type OccluderDeclaration,
20
+ OCCLUDER_PLATE_BASE_RUN,
21
+ OCCLUDER_PLATE_OCCLUDER,
22
+ OCCLUDER_PLATE_PAINTING,
23
+ occluderColourCopies,
24
+ occluderColourWarning,
25
+ } from './occluders.ts';
26
+ import type { OccluderPlateRecord } from './parts.ts';
27
+ import { PLATE_RECEIPT_FILE, type PlateReceipt, sha256, verifyPlateReceipt } from './plate.ts';
17
28
  import { decodePngBytes } from './raster/png.ts';
18
29
  import type { Raster } from './raster/types.ts';
19
30
 
@@ -32,15 +43,22 @@ export interface OccluderStageInput {
32
43
  rigScale: number;
33
44
  }
34
45
 
35
- export function occluderStageWarnings(input: OccluderStageInput): string[] {
36
- const { source, runs } = input;
37
- const frame = checkGeometry({ sourceW: source.width, sourceH: source.height, resolution: input.resolution, headBox: input.headBox, rigScale: input.rigScale, ...(runs.single ? { single: true } : {}) }, { full: runs.full, head: runs.head });
38
- const full = runs.single ? padSingleRun(runs.full, frame, input.resolution) : runs.full;
39
- const painting = sourceInRig(source, frame.W, frame.H);
40
- const lines: string[] = [];
41
- input.occluders.forEach((d, i) => {
46
+ export interface OccluderPlateBindInput {
47
+ occluders: readonly OccluderDeclaration[];
48
+ configPath: string;
49
+ sourcePath: string;
50
+ fullPath: string;
51
+ }
52
+
53
+ export interface OccluderInput {
54
+ declaration: OccluderDeclaration;
55
+ image: Raster;
56
+ }
57
+
58
+ export function readOccluderInputs(occluders: readonly OccluderDeclaration[], configPath: string, source: Raster): OccluderInput[] {
59
+ return occluders.map((d, i) => {
42
60
  const at = `config.assemble.occluders[${i}]`;
43
- const path = resolve(dirname(resolve(input.configPath)), d.image);
61
+ const path = resolve(dirname(resolve(configPath)), d.image);
44
62
  const bytes = new Uint8Array(readFileSync(path));
45
63
  const found = createHash('sha256').update(bytes).digest('hex');
46
64
  if (found !== d.sha256) refuse('CONFIG_OCCLUDER_SHA256', `${at}.sha256`, `is ${d.sha256}; ${d.image} has sha256 ${found} — declare the bytes the occluder image holds`);
@@ -48,6 +66,17 @@ export function occluderStageWarnings(input: OccluderStageInput): string[] {
48
66
  if (image.width !== source.width || image.height !== source.height) {
49
67
  refuse('ASSEMBLE_OCCLUDER_GRID', `${at}.image`, `is ${image.width}x${image.height}; the painting's ${source.width}x${source.height} is required — the occluder is read on the painting's grid and never fitted`);
50
68
  }
69
+ return { declaration: d, image };
70
+ });
71
+ }
72
+
73
+ export function occluderStageWarnings(input: OccluderStageInput): string[] {
74
+ const { source, runs } = input;
75
+ const frame = checkGeometry({ sourceW: source.width, sourceH: source.height, resolution: input.resolution, headBox: input.headBox, rigScale: input.rigScale, ...(runs.single ? { single: true } : {}) }, { full: runs.full, head: runs.head });
76
+ const full = runs.single ? padSingleRun(runs.full, frame, input.resolution) : runs.full;
77
+ const painting = sourceInRig(source, frame.W, frame.H);
78
+ const lines: string[] = [];
79
+ readOccluderInputs(input.occluders, input.configPath, source).forEach(({ declaration: d, image }, i) => {
51
80
  // A rig pixel reads the occluder at the source pixel its centre falls in.
52
81
  const sx = (x: number): number => Math.min(source.width - 1, Math.floor((x + 0.5) * source.width / frame.W));
53
82
  const sy = (y: number): number => Math.min(source.height - 1, Math.floor((y + 0.5) * source.height / frame.H));
@@ -62,3 +91,64 @@ export function occluderStageWarnings(input: OccluderStageInput): string[] {
62
91
  });
63
92
  return lines;
64
93
  }
94
+
95
+ /**
96
+ * Verify and bind each declared `config.assemble.occluders[i].plate` (issue #1237):
97
+ * 1. `verifyPlateReceipt` holds the receipt's own schema and sibling files (`plate.png`, `mask.png`).
98
+ * 2. `receipt.occluder.sha256` must equal `config.assemble.occluders[i].sha256` (`ASSEMBLE_OCCLUDER_PLATE_OCCLUDER`).
99
+ * 3. `receipt.painting.sha256` must equal the `--source` painting's sha256 (`ASSEMBLE_OCCLUDER_PLATE_PAINTING`).
100
+ * 4. `receipt.output.sha256` must equal the base (`--full`) See-through run's `meta.json` `image_sha256` (`ASSEMBLE_OCCLUDER_PLATE_BASE_RUN`).
101
+ */
102
+ export function bindOccluderPlates(input: OccluderPlateBindInput): OccluderPlateRecord[] {
103
+ const withPlates = input.occluders.map((d, i) => ({ d, i })).filter((x) => x.d.plate !== undefined);
104
+ if (withPlates.length === 0) return [];
105
+ const configDir = dirname(resolve(input.configPath));
106
+ const paintingSha = sha256(new Uint8Array(readFileSync(resolve(input.sourcePath))));
107
+ const fullDir = resolve(input.fullPath);
108
+ const metaPath = existsSync(fullDir) && statSync(fullDir).isDirectory() ? join(fullDir, 'meta.json') : join(dirname(fullDir), 'meta.json');
109
+ const out: OccluderPlateRecord[] = [];
110
+ for (const { d, i } of withPlates) {
111
+ const at = `config.assemble.occluders[${i}].plate`;
112
+ const plateRel = d.plate as string;
113
+ const plateDir = resolve(configDir, plateRel);
114
+ const receiptFile = join(plateDir, PLATE_RECEIPT_FILE);
115
+ if (!existsSync(plateDir) || !statSync(plateDir).isDirectory() || !existsSync(receiptFile) || !statSync(receiptFile).isFile()) {
116
+ refuse('CONFIG_FILE_PRESENT', at, `names ${plateRel} (${plateDir}), which holds no ${PLATE_RECEIPT_FILE}; a comfy plate --mode occluder output directory relative to the config's directory is required`);
117
+ }
118
+ const problems = verifyPlateReceipt(receiptFile);
119
+ if (problems.length > 0) throw new PartsError(problems);
120
+ const receiptBytes = new Uint8Array(readFileSync(receiptFile));
121
+ const receiptSha = sha256(receiptBytes);
122
+ const receipt = JSON.parse(Buffer.from(receiptBytes).toString('utf8')) as PlateReceipt;
123
+ if (receipt.mode !== 'occluder' || receipt.occluder === undefined) {
124
+ refuse('PLATE_RECEIPT_KEYS', at, `names ${receiptFile} with mode ${JSON.stringify(receipt.mode)}; an occluder plate receipt (mode "occluder") is required`);
125
+ }
126
+ if (receipt.occluder.sha256 !== d.sha256) {
127
+ refuse(OCCLUDER_PLATE_OCCLUDER, at, `receipt ${receiptFile} binds occluder.sha256 ${receipt.occluder.sha256}; config.assemble.occluders[${i}].sha256 is ${d.sha256}`);
128
+ }
129
+ if (receipt.painting.sha256 !== paintingSha) {
130
+ refuse(OCCLUDER_PLATE_PAINTING, at, `receipt ${receiptFile} binds painting.sha256 ${receipt.painting.sha256}; --source ${input.sourcePath} has sha256 ${paintingSha}`);
131
+ }
132
+ if (!existsSync(metaPath) || !statSync(metaPath).isFile()) {
133
+ refuse(OCCLUDER_PLATE_BASE_RUN, at, `receipt ${receiptFile} binds output.sha256 ${receipt.output.sha256}, but base run ${input.fullPath} has no meta.json (${metaPath}) to bind image_sha256`);
134
+ }
135
+ let baseRunSha: unknown;
136
+ try {
137
+ baseRunSha = (JSON.parse(readFileSync(metaPath, 'utf8')) as { image_sha256?: unknown }).image_sha256;
138
+ } catch (err) {
139
+ refuse(OCCLUDER_PLATE_BASE_RUN, at, `base run meta.json (${metaPath}) does not parse as JSON: ${(err as Error).message}`);
140
+ }
141
+ if (typeof baseRunSha !== 'string' || !SHA256_PATTERN.test(baseRunSha) || receipt.output.sha256 !== baseRunSha) {
142
+ refuse(OCCLUDER_PLATE_BASE_RUN, at, `receipt ${receiptFile} binds output.sha256 ${receipt.output.sha256}; base (--full) See-through run ${metaPath} image_sha256 is ${typeof baseRunSha === 'string' ? baseRunSha : JSON.stringify(baseRunSha)}`);
143
+ }
144
+ out.push({
145
+ receipt: `${plateRel.replace(/\\/g, '/').replace(/\/+$/, '')}/${PLATE_RECEIPT_FILE}`,
146
+ receipt_sha256: receiptSha,
147
+ occluder_sha256: receipt.occluder.sha256,
148
+ painting_sha256: receipt.painting.sha256,
149
+ output_sha256: receipt.output.sha256,
150
+ mask_sha256: receipt.mask.sha256,
151
+ });
152
+ }
153
+ return out;
154
+ }