rig-parts 2.69.0 → 2.71.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
@@ -6,7 +6,7 @@ import { withoutCheckRows } from './checkrow.ts';
6
6
  import { readSetupFigureMask } from './setupfiguremask.ts';
7
7
  import { EDGE_RESIDUAL_FILE, edgeResidualLines } from './edgeresidual.ts';
8
8
  import { SUPPORT_DOMAINS_FILE, writeSupportDomains } from './supportdomains.ts';
9
- import { COINCIDE_LINE, supportLines } from './coincide.ts';
9
+ import { COINCIDE_LINE, SETUP_SEAM_TRANSMISSION_LINE, setupSeamTransmissionLine, supportLines } from './coincide.ts';
10
10
  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';
@@ -112,7 +112,7 @@ import { CONTROL_SUFFIX, withAnimations } from './motion.ts';
112
112
  import type { PaletteError } from './palette.ts';
113
113
  import { PartVisibility } from './partvisibility.ts';
114
114
  import { readRunVisibility } from './visibility.ts';
115
- import { type LayerSet, readLayers } from './layers.ts';
115
+ import { type LayerSet, readLayers, type WrapperReadings } from './layers.ts';
116
116
  import { placeBoneEntriesForSkeleton, poseBoneEntriesForDrawn, REGISTER_OFFSET_BAR, REGISTER_SCALE_BAR, registeredWithinBar, registerSkeleton, SKELETON_LIMB_BONES, skeletonDrawnLength, skeletonLimbJoints } from './limbs.ts';
117
117
  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';
118
118
  import { encodePngBytes, readPng, writePng } from './raster/png.ts';
@@ -149,26 +149,33 @@ export function readSource(path: string): Raster {
149
149
  }
150
150
  }
151
151
 
152
+ export type AssembleWrapperReadings = Record<'full' | 'head', WrapperReadings>;
153
+
152
154
  /**
153
155
  * Read both runs, collecting the refusals of both before throwing. With no
154
156
  * head run (`head` null, issue #359) the full run is read once and stands for
155
157
  * both, and `single` says so: the stage then holds it to `checkSingleRun`.
156
158
  */
157
- export function readRuns(full: string, head: string | null, recordVisibility = false): {
159
+ export function readRuns(full: string, head: string | null, recordVisibility = false, wrapperReadings?: AssembleWrapperReadings): {
158
160
  full: LayerSet; head: LayerSet; single: boolean; visibility?: PartVisibility;
159
161
  } {
160
162
  const problems: Problem[] = [];
161
163
  let recorded: ReturnType<typeof readRunVisibility>;
162
- const one = (path: string, verify = false): LayerSet | null => {
164
+ const one = (path: string, verify: boolean, readings?: WrapperReadings): LayerSet | null => {
163
165
  try {
164
166
  if (verify && !/\.psd$/i.test(path) && existsSync(path)) {
165
- const wrapperDir = statSync(path).isDirectory() ? path : basename(path) === 'layers.json' ? dirname(path) : undefined;
167
+ const isDirectory = statSync(path).isDirectory();
168
+ const wrapperDir = isDirectory ? path : basename(path) === 'layers.json' ? dirname(path) : undefined;
166
169
  if (wrapperDir !== undefined) {
167
- recorded = readRunVisibility(wrapperDir);
168
- if (recorded !== undefined) return recorded.set;
170
+ recorded = readRunVisibility(wrapperDir, readings);
171
+ if (recorded !== undefined) {
172
+ // Visibility takes the wrapper directory even when the CLI names its manifest.
173
+ if (readings?.manifest !== undefined) readings.manifest.givenAsDirectory = isDirectory;
174
+ return recorded.set;
175
+ }
169
176
  }
170
177
  }
171
- return readLayers(path);
178
+ return readLayers(path, undefined, readings);
172
179
  } catch (err) {
173
180
  if (err instanceof PartsError) {
174
181
  problems.push(...err.problems);
@@ -177,8 +184,8 @@ export function readRuns(full: string, head: string | null, recordVisibility = f
177
184
  throw err;
178
185
  }
179
186
  };
180
- const f = one(full, recordVisibility);
181
- const h = head === null ? f : one(head);
187
+ const f = one(full, recordVisibility, wrapperReadings?.full);
188
+ const h = head === null ? f : one(head, false, wrapperReadings?.head);
182
189
  if (problems.length > 0) throw new PartsError(problems);
183
190
  const runs = { full: f as LayerSet, head: h as LayerSet, single: head === null };
184
191
  if (recorded === undefined) return runs;
@@ -538,12 +545,12 @@ export function frontOrdered<T extends { record: { name: string } }>(items: read
538
545
 
539
546
  /** Bind the pure owner reading to the exact stage inputs. */
540
547
  function sourceCoverSet(result: AssembleResult, set: string | null, painting: string,
541
- runs: ReturnType<typeof readRuns>): SourceCoverSet {
548
+ runs: ReturnType<typeof readRuns>, wrapperReadings?: AssembleWrapperReadings): SourceCoverSet {
542
549
  const inputs: SourceCoverSet['inputs'] = [];
543
550
  for (const run of (runs.single ? ['full'] : ['full', 'head']) as Array<'full' | 'head'>) {
544
551
  const layers = runs[run];
545
552
  inputs.push({ run, file: basename(layers.source),
546
- sha256: createHash('sha256').update(readFileSync(layers.source)).digest('hex'),
553
+ sha256: wrapperReadings?.[run].manifest?.sha256 ?? createHash('sha256').update(readFileSync(layers.source)).digest('hex'),
547
554
  layers: layers.layers.map(layer => ({ layer: layer.name,
548
555
  image: layer.file === null ? null : relative(dirname(layers.source), layer.file).split(sep).join('/') })) });
549
556
  }
@@ -554,7 +561,9 @@ function sourceCoverSet(result: AssembleResult, set: string | null, painting: st
554
561
  }
555
562
 
556
563
  /** Read, assemble, and write only after every refusal has had its chance. Throws a PartsError on a refusal, having written nothing. */
557
- export function assembleStage(input: AssembleStageInput, outs: AssembleOutputs, log: Log): AssembleResult {
564
+ export function assembleStage(input: AssembleStageInput, outs: AssembleOutputs, log: Log,
565
+ onWrapperReadings?: (readings: AssembleWrapperReadings) => void,
566
+ ): AssembleResult {
558
567
  // A --requirements file that reaches assembly must be the one config.requirements
559
568
  // names (#1418), so the assembly reading sees what assemble read.
560
569
  const requirementsFile = input.requirements === undefined ? null : readRequirements(input.requirements);
@@ -570,7 +579,8 @@ export function assembleStage(input: AssembleStageInput, outs: AssembleOutputs,
570
579
  const { seam, project } = effectiveAssemblyRules(cfg.assemble, input);
571
580
  const { requirements, effectiveSetup } = resolveAssemblyRequirements(input, cfg, project, requirementsFile);
572
581
  const src = readSource(input.source);
573
- const read = readRuns(input.full, input.head, true);
582
+ const wrapperReadings = onWrapperReadings === undefined ? undefined : { full: { pngs: [] }, head: { pngs: [] } };
583
+ const read = readRuns(input.full, input.head, true, wrapperReadings);
574
584
  // Issue #946: every declared receipt is held to its file, and under `required` every edited image needs one, before anything is assembled.
575
585
  const receipts = readEditorReceipts(cfg.assemble.editor_receipts, input.config);
576
586
  const editedParts = readEditedParts(cfg.assemble.edited_parts, input.config, cfg.assemble.plan ?? []);
@@ -603,7 +613,7 @@ export function assembleStage(input: AssembleStageInput, outs: AssembleOutputs,
603
613
  if (boundPlates.length > 0) result.parts.occluder_plates = boundPlates;
604
614
  }
605
615
 
606
- const sourceCoverSets = [sourceCoverSet(result, null, input.source, read)];
616
+ const sourceCoverSets = [sourceCoverSet(result, null, input.source, read, wrapperReadings)];
607
617
 
608
618
  // Issue #454: alternate painting sets, assembled before any file is written.
609
619
  const configDir = dirname(resolve(input.config));
@@ -1170,6 +1180,7 @@ export function assembleStage(input: AssembleStageInput, outs: AssembleOutputs,
1170
1180
  }
1171
1181
  }
1172
1182
 
1183
+ if (wrapperReadings !== undefined) onWrapperReadings?.(wrapperReadings);
1173
1184
  // Emit only after green: every refusal above has already thrown.
1174
1185
  if (input.resetBuildOutput === true) resetBuildOutput(dirname(outs.partsJson));
1175
1186
  makeOutDir(outs.partsDir);
@@ -2560,6 +2571,8 @@ export function checkStage(input: CheckStageInput, rigc: RigcRunner, bin: string
2560
2571
  if (artJoints !== undefined) for (const line of artJointLines(artJoints)) log(` ${line}`);
2561
2572
  const partSupport = fig[COINCIDE_LINE];
2562
2573
  if (partSupport !== undefined) for (const line of supportLines(partSupport)) log(` ${line}`);
2574
+ const seamTransmission = fig[SETUP_SEAM_TRANSMISSION_LINE];
2575
+ if (seamTransmission !== undefined) log(setupSeamTransmissionLine(seamTransmission));
2563
2576
  const setupPainting = fig[SETUP_PAINTING_LINE];
2564
2577
  if (setupPainting !== undefined) for (const line of setupPaintingLines(setupPainting)) log(` ${line}`);
2565
2578
  for (const line of boundaryColourLines(r.boundaryColour)) log(` ${line}`);
package/src/check.ts CHANGED
@@ -2,8 +2,8 @@ import { refuseStaleAssembly, type AssemblyRules } from './assembly-reading.ts';
2
2
  import { checkRow, checkSlotRow, checkSlotParts, serializeCheckRows, type CheckRowLabels } from './checkrow.ts';
3
3
  import { readSetupFigureMask } from './setupfiguremask.ts';
4
4
  import { readSetupBackdrop } from './setupbackdrop.ts';
5
- import { COINCIDE_LINE, type SupportReport } from './coincide.ts';
6
- import { observeSupport } from './coincideio.ts';
5
+ import { COINCIDE_LINE, SETUP_SEAM_TRANSMISSION_LINE, type SetupSeamTransmissionReport, type SupportReport } from './coincide.ts';
6
+ import { observeSetupSeamTransmission, observeSupport } from './coincideio.ts';
7
7
  import { SETUP_PAINTING_LINE, SETUP_PAINTING_UNCOVERED_WARNING, UNDECLARED_SETUP_PAINTING_REASON, setupPaintingBounds, setupPaintingLine, setupPaintingWarningCount, type SetupPainting, type SetupPaintingLine, type SetupPaintingObservation } from './setuppainting.ts';
8
8
  import { readMaterialSources } from './cutmaterialio.ts';
9
9
  import { CUT_MATERIAL_LINE, checkJointMaterial, type MaterialLine } from './cutmaterial.ts';
@@ -3002,6 +3002,8 @@ export interface CheckFigures {
3002
3002
  /** Written only when it reads a part under physics (issue #1320): {@link PhysicsContributionLine}, a warning, never a bar. */
3003
3003
  [PHYSICS_CONTRIBUTES_LINE]?: PhysicsContributionLine;
3004
3004
  [COINCIDE_LINE]?: SupportReport;
3005
+ /** Written only when a painting is registered on the setup grid (issue #1634): {@link SetupSeamTransmissionReport}, REPORTED. */
3006
+ [SETUP_SEAM_TRANSMISSION_LINE]?: SetupSeamTransmissionReport;
3005
3007
  RECOMPOSITE_HOLES: ReportedLine;
3006
3008
  /** Issue #933: openings inside the figure over motion across undeclared setup-overlapping layer pairs; omitted when SKIP. */
3007
3009
  figure_openings?: FigureOpeningReading;
@@ -3510,7 +3512,7 @@ export function checkStatuses(fig: Omit<CheckFigures, 'spec' | 'bar_outcomes' |
3510
3512
  const raw = fig as unknown as Record<string, unknown>;
3511
3513
  const out: Record<string, CheckStatus> = { gate: checkBarStatus(raw, 'gate'), loop: checkBarStatus(raw, 'loop'), seam: checkBarStatus(raw, 'seam') };
3512
3514
  for (const n of JUDGEMENT_LINES) out[n] = fig[n].status;
3513
- 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) {
3515
+ 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, COINCIDE_LINE, SETUP_SEAM_TRANSMISSION_LINE, ART_JOINT_LINE, SETUP_PAINTING_LINE, BOUNDARY_COLOUR_LINE, BEHIND_SEAM_LINE, SOURCE_EXPOSURE_LINE, CUT_MATERIAL_LINE] as const) {
3514
3516
  const l = fig[n];
3515
3517
  if (l !== undefined) out[n] = l.status;
3516
3518
  }
@@ -7939,6 +7941,9 @@ export function runCheck(rigDir: string, outDir: string, rigc: RigcRunner, parts
7939
7941
  const sourceExposure = exposureDeclared === undefined && !hasSourceStateMaps(inp.parts) ? null
7940
7942
  : 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);
7941
7943
 
7944
+ // Issue #1634: setup seam transmission over shared normal-blend pair edges, only when a painting is registered on the setup grid.
7945
+ const seamTransmission = observeSetupSeamTransmission(buildDir, inp, reqFile?.setup_painting !== undefined);
7946
+
7942
7947
  // 5. the scene's declared requirements (issue #93), only under --requirements
7943
7948
  const reqProblems: Problem[] = [];
7944
7949
  const reqBlock = reqFile === null || reqRecord === null ? null : { file: reqRecord, ...measureRequirements(inp, reqFile, buildDir, out, rigc, reqProblems, seams ?? new Map(), measured) };
@@ -7987,6 +7992,7 @@ export function runCheck(rigDir: string, outDir: string, rigc: RigcRunner, parts
7987
7992
  ...(Object.keys(skipped).length === 0 ? {} : { skipped }),
7988
7993
  ...(Object.keys(setsFigures).length === 0 ? {} : { sets: setsFigures }),
7989
7994
  ...(partSupport === null ? {} : { [COINCIDE_LINE]: partSupport }),
7995
+ ...(seamTransmission === null ? {} : { [SETUP_SEAM_TRANSMISSION_LINE]: seamTransmission }),
7990
7996
  ...(config === undefined ? {} : { config }),
7991
7997
  ...(artJoints === null ? {} : { [ART_JOINT_LINE]: artJoints }),
7992
7998
  ...(setupPainting === null ? {} : { [SETUP_PAINTING_LINE]: setupPainting }),
package/src/checkrow.ts CHANGED
@@ -62,6 +62,7 @@ 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
+ 'SETUP_SEAM_TRANSMISSION.rows': ['SETUP_SEAM_TRANSMISSION.rows'],
65
66
  'SOURCE_EXPOSURE.rows': ['SOURCE_EXPOSURE.rows'],
66
67
  'SOURCE_EXPOSURE.unmeasured': ['SOURCE_EXPOSURE.unmeasured'],
67
68
  'STILL_REGIONS_DARK.*.crossing': ['STILL_REGIONS_DARK.*.crossing'],
package/src/coincide.ts CHANGED
@@ -1,10 +1,12 @@
1
- import { checkRow } from './checkrow.ts';
2
- /** Report-only missing support observations on the native setup grid (#998). */
1
+ import { checkRow, type CheckRowLabels } from './checkrow.ts';
2
+ import { cropToSpineY } from './coords.ts';
3
+ /** Report-only missing support and setup seam transmission observations on the native setup grid (#998, #1634). */
3
4
  import { refuseIfAny } from './errors.ts';
4
5
  import { connectedComponents } from './raster/components.ts';
5
6
  import { assertBinary, type Mask } from './raster/types.ts';
6
7
 
7
8
  export const COINCIDE_LINE = 'PART_SUPPORT_REPORT';
9
+ export const SETUP_SEAM_TRANSMISSION_LINE = 'SETUP_SEAM_TRANSMISSION';
8
10
  export const SUPPORT_GRID_CODE = 'CHECK_SUPPORT_GRID';
9
11
  export type SupportBox = [number, number, number, number];
10
12
  /** Independent stage-grid witness, supplied by the producer. Never derive it
@@ -57,6 +59,52 @@ export interface SupportReport {
57
59
  reason?: string;
58
60
  }
59
61
 
62
+ export interface MaskBounds {
63
+ left: number;
64
+ top: number;
65
+ right: number;
66
+ bottom: number;
67
+ }
68
+
69
+ export function maskBounds(width: number, height: number, mask: Mask): MaskBounds {
70
+ let left = width, top = height, right = 0, bottom = 0;
71
+ for (let y = 0; y < height; y++) for (let x = 0; x < width; x++) {
72
+ if (mask.data[y * width + x] === 0) continue;
73
+ left = Math.min(left, x); top = Math.min(top, y);
74
+ right = Math.max(right, x + 1); bottom = Math.max(bottom, y + 1);
75
+ }
76
+ return { left, top, right, bottom };
77
+ }
78
+
79
+ /**
80
+ * Shared 4-neighbour unit pixel-cell edge geometry: calls `onSharedEdge(x, y, dx, dy)`
81
+ * for each unit lattice segment from `(x, y)` to `(x + dx, y + dy)` where one
82
+ * orthogonally adjacent cell is inside `over` only and the other is inside `under`
83
+ * only, and `onOverlap?.(x, y)` for each cell inside both.
84
+ */
85
+ export function walkSharedPairGeometry(
86
+ width: number, height: number, under: Mask, underBounds: MaskBounds, over: Mask, overBounds: MaskBounds,
87
+ onSharedEdge: (x: number, y: number, dx: number, dy: number) => void,
88
+ onOverlap?: (x: number, y: number) => void,
89
+ ): void {
90
+ if (underBounds.right === 0 || overBounds.right === 0) return;
91
+ const rawEdge = (a: number, b: number, x: number, y: number, dx: number, dy: number): void => {
92
+ if (under.data[a] !== 0 && under.data[b] === 0 && over.data[a] === 0 && over.data[b] !== 0) {
93
+ onSharedEdge(x, y, dx, dy);
94
+ }
95
+ };
96
+ // Intersect occupied boxes before visiting pixels. The one-cell halo
97
+ // includes touching boxes and both directions of each shared edge.
98
+ const left = Math.max(0, underBounds.left - 1, overBounds.left - 1), top = Math.max(0, underBounds.top - 1, overBounds.top - 1);
99
+ const right = Math.min(width, underBounds.right + 1, overBounds.right + 1), bottom = Math.min(height, underBounds.bottom + 1, overBounds.bottom + 1);
100
+ for (let y = top; y < bottom; y++) for (let x = left; x < right; x++) {
101
+ const p = y * width + x;
102
+ if (onOverlap !== undefined && under.data[p] !== 0 && over.data[p] !== 0) onOverlap(x, y);
103
+ if (x + 1 < width) { rawEdge(p, p + 1, x + 1, y, 0, 1); rawEdge(p + 1, p, x + 1, y, 0, 1); }
104
+ if (y + 1 < height) { rawEdge(p, p + width, x, y + 1, 1, 0); rawEdge(p + width, p, x, y + 1, 1, 0); }
105
+ }
106
+ }
107
+
60
108
  /** Parts are ordered back to front. A boundary segment is counted only when
61
109
  * the adjacent F cell is missing from B AND belongs to B's independent domain.
62
110
  * No dilation, inferred continuation, limit or gate is applied. */
@@ -73,40 +121,19 @@ export function supportReport(
73
121
  for (const domain of domains) if ('mask' in domain) check(domain.mask);
74
122
  if (paintedFigure !== null) check(paintedFigure);
75
123
  if (new Set(parts.map(p => p.name)).size !== parts.length || new Set(domains.map(d => d.part)).size !== domains.length) throw new Error('support report requires unique part and domain names');
76
- const bounds = parts.map(part => {
77
- let left = width, top = height, right = 0, bottom = 0;
78
- for (let y = 0; y < height; y++) for (let x = 0; x < width; x++) {
79
- if (part.mask.data[y * width + x] === 0) continue;
80
- left = Math.min(left, x); top = Math.min(top, y);
81
- right = Math.max(right, x + 1); bottom = Math.max(bottom, y + 1);
82
- }
83
- return { left, top, right, bottom };
84
- });
124
+ const bounds = parts.map(part => maskBounds(width, height, part.mask));
85
125
  const raw_pairs: RawSupportPair[] = [];
86
126
  const pairs: SupportPair[] = [];
87
127
  for (let back = 0; back < parts.length; back++) for (let front = back + 1; front < parts.length; front++) {
88
128
  const B = parts[back], F = parts[front], domain = domains.find(d => d.part === B.name);
89
- const bb = bounds[back], fb = bounds[front];
90
129
  let rawLength = 0, overlap = 0, rx0 = width, ry0 = height, rx1 = 0, ry1 = 0;
91
130
  const include = (x: number, y: number, dx: number, dy: number): void => {
92
131
  rx0 = Math.min(rx0, x); ry0 = Math.min(ry0, y);
93
132
  rx1 = Math.max(rx1, x + dx); ry1 = Math.max(ry1, y + dy);
94
133
  };
95
- const rawEdge = (a: number, b: number, x: number, y: number, dx: number, dy: number): void => {
96
- if (B.mask.data[a] !== 0 && B.mask.data[b] === 0 && F.mask.data[a] === 0 && F.mask.data[b] !== 0) {
97
- rawLength++; include(x, y, dx, dy);
98
- }
99
- };
100
- // Intersect occupied boxes before visiting pixels. The one-cell halo
101
- // includes touching boxes and both directions of each shared edge.
102
- const left = Math.max(0, bb.left - 1, fb.left - 1), top = Math.max(0, bb.top - 1, fb.top - 1);
103
- const right = Math.min(width, bb.right + 1, fb.right + 1), bottom = Math.min(height, bb.bottom + 1, fb.bottom + 1);
104
- for (let y = top; y < bottom; y++) for (let x = left; x < right; x++) {
105
- const p = y * width + x;
106
- if (B.mask.data[p] !== 0 && F.mask.data[p] !== 0) { overlap++; include(x, y, 1, 1); }
107
- if (x + 1 < width) { rawEdge(p, p + 1, x + 1, y, 0, 1); rawEdge(p + 1, p, x + 1, y, 0, 1); }
108
- if (y + 1 < height) { rawEdge(p, p + width, x, y + 1, 1, 0); rawEdge(p + width, p, x, y + 1, 1, 0); }
109
- }
134
+ walkSharedPairGeometry(width, height, B.mask, bounds[back], F.mask, bounds[front],
135
+ (x, y, dx, dy) => { rawLength++; include(x, y, dx, dy); },
136
+ (x, y) => { overlap++; include(x, y, 1, 1); });
110
137
  if (rawLength > 0 || overlap > 0) raw_pairs.push({ ...checkRow('PART_SUPPORT_REPORT.raw_pairs', 'pair', false, [F.name, B.name]), front: F.name, back: B.name,
111
138
  boundary_length_px: rawLength, box: [rx0, ry0, rx1 - rx0, ry1 - ry0], overlap_area_px: overlap,
112
139
  classification: 'ownership unknown, unclassified' });
@@ -156,3 +183,286 @@ export function supportLines(report: SupportReport): string[] {
156
183
  `${COINCIDE_LINE}: unowned ${report.unowned.status} — ${report.unowned.status === 'unavailable' ? report.unowned.reason : `${report.unowned.area_px} px, ${report.unowned.regions.length} regions`}`,
157
184
  ...report.unowned.regions.map(r => `${COINCIDE_LINE}: unowned box ${JSON.stringify(r.box)}, area ${r.area_px} px`)];
158
185
  }
186
+
187
+ export interface SetupSeamPiece {
188
+ slot: string;
189
+ /** Sampled alpha bytes (0..255) on the native setup grid, width * height row-major. */
190
+ alpha: Uint8Array;
191
+ }
192
+
193
+ export interface SetupSeamTransmissionRow extends CheckRowLabels {
194
+ under: string;
195
+ over: string;
196
+ longest_lighter_run_px: number;
197
+ lighter_px: number;
198
+ world_box: [number, number, number, number];
199
+ edge_length_px: number;
200
+ sampled_px: number;
201
+ painting_eligible_px: number;
202
+ darker_px: number;
203
+ worst_transmission: number;
204
+ }
205
+
206
+ export interface SetupSeamTransmissionReport {
207
+ status: 'REPORTED';
208
+ rows: SetupSeamTransmissionRow[];
209
+ }
210
+
211
+ interface LatticeSegment {
212
+ x0: number;
213
+ y0: number;
214
+ x1: number;
215
+ y1: number;
216
+ mx2: number;
217
+ my2: number;
218
+ }
219
+
220
+ function sharesEndpoint(a: LatticeSegment, b: LatticeSegment): boolean {
221
+ return (
222
+ (a.x0 === b.x0 && a.y0 === b.y0) ||
223
+ (a.x0 === b.x1 && a.y0 === b.y1) ||
224
+ (a.x1 === b.x0 && a.y1 === b.y0) ||
225
+ (a.x1 === b.x1 && a.y1 === b.y1)
226
+ );
227
+ }
228
+
229
+ function longestLighterRunPx(
230
+ width: number, height: number, segments: readonly LatticeSegment[],
231
+ lighterSamples: readonly number[], sampleSeg: Int32Array,
232
+ ): number {
233
+ if (lighterSamples.length === 0) return 0;
234
+ const occupied = new Uint8Array(segments.length);
235
+ for (const p of lighterSamples) {
236
+ const px = p % width, py = Math.floor(p / width);
237
+ const cx2 = 2 * px + 1, cy2 = 2 * py + 1;
238
+ let bestSeg = 0, bestD2 = Infinity;
239
+ for (let s = 0; s < segments.length; s++) {
240
+ const dx2 = cx2 - segments[s].mx2, dy2 = cy2 - segments[s].my2;
241
+ const d2 = dx2 * dx2 + dy2 * dy2;
242
+ if (d2 < bestD2) { bestD2 = d2; bestSeg = s; }
243
+ }
244
+ sampleSeg[p] = bestSeg;
245
+ occupied[bestSeg] = 1;
246
+ }
247
+ const adj: number[][] = Array.from({ length: segments.length }, () => []);
248
+ for (const p of lighterSamples) {
249
+ const px = p % width, py = Math.floor(p / width);
250
+ const sa = sampleSeg[p];
251
+ const y0 = Math.max(0, py - 1), y1 = Math.min(height - 1, py + 1);
252
+ const x0 = Math.max(0, px - 1), x1 = Math.min(width - 1, px + 1);
253
+ for (let ny = y0; ny <= y1; ny++) for (let nx = x0; nx <= x1; nx++) {
254
+ if (nx === px && ny === py) continue;
255
+ const sb = sampleSeg[ny * width + nx];
256
+ if (sb < 0 || sa === sb || !sharesEndpoint(segments[sa], segments[sb])) continue;
257
+ if (!adj[sa].includes(sb)) adj[sa].push(sb);
258
+ if (!adj[sb].includes(sa)) adj[sb].push(sa);
259
+ }
260
+ }
261
+ for (const p of lighterSamples) sampleSeg[p] = -1;
262
+ let best = 1;
263
+ const compSeen = new Uint8Array(segments.length);
264
+ const visited = new Uint8Array(segments.length);
265
+ const inReach = new Uint8Array(segments.length);
266
+ for (let root = 0; root < segments.length; root++) {
267
+ if (occupied[root] === 0 || compSeen[root] !== 0) continue;
268
+ const comp: number[] = [root];
269
+ compSeen[root] = 1;
270
+ for (let head = 0; head < comp.length; head++) {
271
+ for (const nb of adj[comp[head]]) {
272
+ if (compSeen[nb] === 0) { compSeen[nb] = 1; comp.push(nb); }
273
+ }
274
+ }
275
+ if (comp.length <= best) continue;
276
+ if (comp.every(v => adj[v].length <= 2)) { best = comp.length; continue; }
277
+ const dfs = (u: number, runLen: number): void => {
278
+ if (runLen > best) best = runLen;
279
+ if (best === comp.length) return;
280
+ const next = adj[u].filter(w => visited[w] === 0);
281
+ if (next.length === 0) return;
282
+ if (next.length === 1) {
283
+ const w = next[0];
284
+ visited[w] = 1;
285
+ dfs(w, runLen + 1);
286
+ visited[w] = 0;
287
+ return;
288
+ }
289
+ const reach: number[] = [];
290
+ for (const w of next) { inReach[w] = 1; reach.push(w); }
291
+ for (let head = 0; head < reach.length; head++) {
292
+ for (const nb of adj[reach[head]]) {
293
+ if (visited[nb] === 0 && inReach[nb] === 0) { inReach[nb] = 1; reach.push(nb); }
294
+ }
295
+ }
296
+ let deadEnds = 0;
297
+ for (const r of reach) {
298
+ let deg = 0;
299
+ for (const nb of adj[r]) if (nb === u || inReach[nb] === 1) deg++;
300
+ if (deg <= 1) deadEnds++;
301
+ }
302
+ for (const r of reach) inReach[r] = 0;
303
+ if (runLen + reach.length - Math.max(0, deadEnds - 1) <= best) return;
304
+ for (const w of next) {
305
+ visited[w] = 1;
306
+ dfs(w, runLen + 1);
307
+ visited[w] = 0;
308
+ if (best === comp.length) return;
309
+ }
310
+ };
311
+ for (const start of comp) {
312
+ if (best === comp.length) break;
313
+ visited[start] = 1;
314
+ dfs(start, 1);
315
+ visited[start] = 0;
316
+ }
317
+ }
318
+ return best;
319
+ }
320
+
321
+ /**
322
+ * Setup seam transmission reading (#1634): for every ordered (under, over) pair
323
+ * of normal-blend drawn pieces, measures shared alpha>=128 unit lattice edges,
324
+ * the <=2 px Euclidean band around their midpoints, raw pair transmission,
325
+ * lighter/darker samples against local painting luminance variation, and the
326
+ * longest non-repeating lighter segment run.
327
+ */
328
+ export function setupSeamTransmission(
329
+ stage: { x: number; y: number; width: number; height: number },
330
+ pieces: readonly SetupSeamPiece[],
331
+ composite: { width: number; height: number; data: ArrayLike<number> },
332
+ painting: { width: number; height: number; data: ArrayLike<number> },
333
+ ): SetupSeamTransmissionReport {
334
+ const W = stage.width, H = stage.height, n = W * H;
335
+ if (!Number.isSafeInteger(W) || !Number.isSafeInteger(H) || W <= 0 || H <= 0 ||
336
+ composite.width !== W || composite.height !== H || composite.data.length !== n * 4 ||
337
+ painting.width !== W || painting.height !== H || painting.data.length !== n * 4 ||
338
+ pieces.some(piece => piece.alpha.length !== n)) {
339
+ throw new Error(`setup seam transmission requires ${W}x${H} composite, painting and piece alpha grids`);
340
+ }
341
+ const compLum = new Float64Array(n);
342
+ const paintLum = new Float64Array(n);
343
+ const paintOpaque = new Uint8Array(n);
344
+ for (let p = 0; p < n; p++) {
345
+ const q = p * 4;
346
+ compLum[p] = 0.2126 * composite.data[q] + 0.7152 * composite.data[q + 1] + 0.0722 * composite.data[q + 2];
347
+ paintLum[p] = 0.2126 * painting.data[q] + 0.7152 * painting.data[q + 1] + 0.0722 * painting.data[q + 2];
348
+ if (painting.data[q + 3] === 255) paintOpaque[p] = 1;
349
+ }
350
+ const eligible = new Uint8Array(n);
351
+ const pixelState = new Int8Array(n);
352
+ for (let y = 0; y < H; y++) {
353
+ const y0 = Math.max(0, y - 1), y1 = Math.min(H - 1, y + 1);
354
+ for (let x = 0; x < W; x++) {
355
+ const p = y * W + x;
356
+ if (paintOpaque[p] === 0) continue;
357
+ const x0 = Math.max(0, x - 1), x1 = Math.min(W - 1, x + 1);
358
+ let hasOpaqueNeighbour = false, variation = 0;
359
+ const lum = paintLum[p];
360
+ for (let ny = y0; ny <= y1; ny++) for (let nx = x0; nx <= x1; nx++) {
361
+ if (nx === x && ny === y) continue;
362
+ const np = ny * W + nx;
363
+ if (paintOpaque[np] === 0) continue;
364
+ hasOpaqueNeighbour = true;
365
+ const d = Math.abs(lum - paintLum[np]);
366
+ if (d > variation) variation = d;
367
+ }
368
+ if (!hasOpaqueNeighbour) continue;
369
+ eligible[p] = 1;
370
+ const delta = compLum[p] - lum;
371
+ if (delta > variation) pixelState[p] = 1;
372
+ else if (delta < -variation) pixelState[p] = -1;
373
+ }
374
+ }
375
+ const masks: Mask[] = pieces.map(piece => {
376
+ const data = new Uint8Array(n);
377
+ for (let p = 0; p < n; p++) if (piece.alpha[p] >= 128) data[p] = 1;
378
+ return { width: W, height: H, data };
379
+ });
380
+ const bounds = masks.map(mask => maskBounds(W, H, mask));
381
+ const stamp = new Int32Array(n);
382
+ const sampleSeg = new Int32Array(n).fill(-1);
383
+ let pairStamp = 0;
384
+ const zero = (v: number): number => (v === 0 ? 0 : v);
385
+ const rows: SetupSeamTransmissionRow[] = [];
386
+ for (let u = 0; u < pieces.length; u++) for (let o = u + 1; o < pieces.length; o++) {
387
+ const segments: LatticeSegment[] = [];
388
+ walkSharedPairGeometry(W, H, masks[u], bounds[u], masks[o], bounds[o], (x, y, dx, dy) => {
389
+ segments.push({ x0: x, y0: y, x1: x + dx, y1: y + dy, mx2: 2 * x + dx, my2: 2 * y + dy });
390
+ });
391
+ if (segments.length === 0) continue;
392
+ segments.sort((a, b) => a.y0 - b.y0 || a.x0 - b.x0 || a.y1 - b.y1 || a.x1 - b.x1);
393
+ pairStamp++;
394
+ const band: number[] = [];
395
+ for (let s = 0; s < segments.length; s++) {
396
+ const seg = segments[s];
397
+ const pxMin = Math.max(0, Math.floor(seg.mx2 / 2 - 2)), pxMax = Math.min(W - 1, Math.ceil(seg.mx2 / 2 + 2));
398
+ const pyMin = Math.max(0, Math.floor(seg.my2 / 2 - 2)), pyMax = Math.min(H - 1, Math.ceil(seg.my2 / 2 + 2));
399
+ for (let py = pyMin; py <= pyMax; py++) {
400
+ const dy2 = 2 * py + 1 - seg.my2;
401
+ const dySq = dy2 * dy2;
402
+ if (dySq > 16) continue;
403
+ for (let px = pxMin; px <= pxMax; px++) {
404
+ const dx2 = 2 * px + 1 - seg.mx2;
405
+ if (dx2 * dx2 + dySq > 16) continue;
406
+ const p = py * W + px;
407
+ if (stamp[p] !== pairStamp) { stamp[p] = pairStamp; band.push(p); }
408
+ }
409
+ }
410
+ }
411
+ let minCellX = W, maxCellX = 0, minCellY = H, maxCellY = 0;
412
+ let painting_eligible_px = 0, lighter_px = 0, darker_px = 0, worstTrans = 0;
413
+ const lighterSamples: number[] = [];
414
+ const underAlpha = pieces[u].alpha, overAlpha = pieces[o].alpha;
415
+ for (let i = 0; i < band.length; i++) {
416
+ const p = band[i];
417
+ const px = p % W, py = Math.floor(p / W);
418
+ if (px < minCellX) minCellX = px;
419
+ if (px + 1 > maxCellX) maxCellX = px + 1;
420
+ if (py < minCellY) minCellY = py;
421
+ if (py + 1 > maxCellY) maxCellY = py + 1;
422
+ const trans = (1 - overAlpha[p] / 255) * (1 - underAlpha[p] / 255);
423
+ if (trans > worstTrans) worstTrans = trans;
424
+ if (eligible[p] === 1) {
425
+ painting_eligible_px++;
426
+ const st = pixelState[p];
427
+ if (st === 1) { lighter_px++; lighterSamples.push(p); }
428
+ else if (st === -1) darker_px++;
429
+ }
430
+ }
431
+ if (lighterSamples.length === 0) continue;
432
+ const longest_lighter_run_px = longestLighterRunPx(W, H, segments, lighterSamples, sampleSeg);
433
+ if (longest_lighter_run_px < 1) continue;
434
+ const under = pieces[u].slot, over = pieces[o].slot;
435
+ const world_box: [number, number, number, number] = [
436
+ zero(stage.x + minCellX),
437
+ zero(stage.y + cropToSpineY(maxCellY, H)),
438
+ zero(stage.x + maxCellX),
439
+ zero(stage.y + cropToSpineY(minCellY, H)),
440
+ ];
441
+ const worstRound = Number(worstTrans.toFixed(6));
442
+ rows.push({
443
+ under,
444
+ over,
445
+ longest_lighter_run_px,
446
+ lighter_px,
447
+ world_box,
448
+ edge_length_px: segments.length,
449
+ sampled_px: band.length,
450
+ painting_eligible_px,
451
+ darker_px,
452
+ worst_transmission: worstRound === 0 ? 0 : worstRound,
453
+ ...checkRow('SETUP_SEAM_TRANSMISSION.rows', 'pair', false, [under, over]),
454
+ });
455
+ }
456
+ rows.sort((a, b) =>
457
+ b.longest_lighter_run_px - a.longest_lighter_run_px ||
458
+ (a.under < b.under ? -1 : a.under > b.under ? 1 : 0) ||
459
+ (a.over < b.over ? -1 : a.over > b.over ? 1 : 0));
460
+ return { status: 'REPORTED', rows };
461
+ }
462
+
463
+ export function setupSeamTransmissionLine(report: SetupSeamTransmissionReport): string {
464
+ if (report.rows.length === 0) return ` REPORTED ${SETUP_SEAM_TRANSMISSION_LINE}: no shared edge has a lighter run`;
465
+ const top = report.rows[0];
466
+ const [x0, y0, x1, y1] = top.world_box;
467
+ return ` REPORTED ${SETUP_SEAM_TRANSMISSION_LINE}: under "${top.under}", over "${top.over}" — longest lighter run ${top.longest_lighter_run_px} px, ${top.lighter_px} lighter px, world box [${x0}, ${y0}, ${x1}, ${y1}]; ${top.edge_length_px} shared edge px, ${top.sampled_px} sampled px, worst pair transmission ${top.worst_transmission.toFixed(6)}; ${report.rows.length} pair(s) have a lighter run`;
468
+ }
package/src/coincideio.ts CHANGED
@@ -1,12 +1,14 @@
1
- /** Pre-rig pair domains and actual textured setup observations (#998). */
2
- import { readFileSync } from 'node:fs';
3
- import { basename, join } from 'node:path';
1
+ /** Pre-rig pair domains and actual textured setup observations (#998, #1634). */
2
+ import { existsSync, readFileSync } from 'node:fs';
3
+ import { basename, dirname, join } from 'node:path';
4
+ import { readModel } from '@rig-c/core/core';
4
5
  import { sourceSupportFigure as supportFigure } from './assemble.ts';
5
6
  import { officialRenderer, sourceSizeProblem, type CheckInputs } from './check.ts';
6
- import { supportReport, unownedSupport, SUPPORT_GRID_CODE, type SupportPart, type SupportReport } from './coincide.ts';
7
+ import { setupSeamTransmission, supportReport, unownedSupport, SUPPORT_GRID_CODE, type SetupSeamPiece, type SetupSeamTransmissionReport, type SupportPart, type SupportReport } from './coincide.ts';
7
8
  import { refuseIfAny } from './errors.ts';
8
9
  import { partImageReference } from './parts.ts';
9
10
  import { readPng } from './raster/png.ts';
11
+ import { resize } from './raster/resize.ts';
10
12
  import { assertBinary, type Mask } from './raster/types.ts';
11
13
  import { readSupportDomains } from './supportdomains.ts';
12
14
 
@@ -60,4 +62,55 @@ export function observeSupport(build: string, input: CheckInputs, supportSource?
60
62
  return report;
61
63
  }
62
64
 
65
+ /**
66
+ * Observe setup seam transmission (#1634) on the accepted gated build when a
67
+ * painting is registered on the setup grid (a hash-bound `painting_in_rig` or a
68
+ * declared `setup_painting` source); returns `null` when no painting is registered.
69
+ */
70
+ export function observeSetupSeamTransmission(
71
+ build: string, input: CheckInputs, declaredSetupPainting: boolean,
72
+ ): SetupSeamTransmissionReport | null {
73
+ const W = input.stage.width, H = input.stage.height;
74
+ let painting = null;
75
+ if (input.parts?.painting_in_rig !== undefined) {
76
+ painting = readPng(join(dirname(input.partsPath), input.parts.painting_in_rig.path));
77
+ } else if (declaredSetupPainting && input.source !== null) {
78
+ painting = resize(input.source.painting, W, H, 'lanczos3');
79
+ }
80
+ if (painting === null) return null;
81
+ const modelPath = join(build, 'skeleton.model.json');
82
+ const skeleton = join(build, 'skeleton.json'), atlas = join(build, 'skeleton.atlas');
83
+ const skeletonText = readFileSync(skeleton, 'utf8');
84
+ const isNormalBlend = (blend: unknown): boolean => blend === undefined || (typeof blend === 'string' && blend.toLowerCase() === 'normal');
85
+ let normalSlots: Set<string>;
86
+ if (existsSync(modelPath)) {
87
+ const model = readModel(readFileSync(modelPath, 'utf8'));
88
+ normalSlots = new Set(model.slots.filter(s => isNormalBlend(s.blend)).map(s => s.name));
89
+ } else {
90
+ const raw = JSON.parse(skeletonText) as { slots?: Array<{ name?: unknown; blend?: unknown }> };
91
+ normalSlots = new Set((raw.slots ?? []).filter(s => typeof s.name === 'string' && isNormalBlend(s.blend)).map(s => String(s.name)));
92
+ }
93
+ const api = officialRenderer();
94
+ const candidate = api.loadCandidate({
95
+ skeletonText,
96
+ atlasText: existsSync(atlas) ? readFileSync(atlas, 'utf8') : null,
97
+ atlasDir: build,
98
+ label: 'setup seam transmission',
99
+ }, { skeleton, atlas }, undefined);
100
+ const pose = api.throughPoser(candidate.choice, p => api.sampleSetupPose(p)).value[0];
101
+ if (pose === undefined) return setupSeamTransmission(input.stage, [], { width: W, height: H, data: new Uint8Array(W * H * 4) }, painting);
102
+ const vp = { minX: input.stage.x, minY: input.stage.y, maxX: input.stage.x + W, maxY: input.stage.y + H, scale: 1, width: W, height: H };
103
+ const composite = api.renderFrame(pose, candidate.pages, vp, [232, 232, 232, 255]);
104
+ const n = W * H;
105
+ const pieces: SetupSeamPiece[] = [];
106
+ for (const piece of pose.pieces) {
107
+ if (!normalSlots.has(piece.slot)) continue;
108
+ const isolated = api.renderFrame({ ...pose, pieces: [piece] }, candidate.pages, vp, [0, 0, 0, 0]);
109
+ const alpha = new Uint8Array(n);
110
+ for (let p = 0; p < n; p++) alpha[p] = isolated.data[p * 4 + 3];
111
+ pieces.push({ slot: piece.slot, alpha });
112
+ }
113
+ return setupSeamTransmission(input.stage, pieces, composite, painting);
114
+ }
115
+
63
116
  export { sourceSupportFigure as supportFigure } from './assemble.ts';