@rig-c/parts 2.8.1 → 2.9.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.
@@ -0,0 +1,208 @@
1
+ /** Exhaustive whole-figure error inventory; existing recomposite output is unchanged. */
2
+ import { createHash } from 'node:crypto';
3
+ import { readFileSync, writeFileSync } from 'node:fs';
4
+ import { dirname, join } from 'node:path';
5
+ import { COVERED_ALPHA, ERROR_LIMIT, coveredMask, errorMask, holeBorders, type PlacedPart } from './assemble.ts';
6
+ import { PartsError, type Problem } from './errors.ts';
7
+ import { readParts } from './parts.ts';
8
+ import { connectedComponents } from './raster/components.ts';
9
+ import { decodePngBytes } from './raster/png.ts';
10
+ import { newMask, type Raster } from './raster/types.ts';
11
+
12
+ export const DIFF_COMPONENTS_SPEC = 'rig-parts-diff-components/1';
13
+ export interface DiffBytes { path: string; bytes: Uint8Array }
14
+ export interface DiffInputs {
15
+ stack: DiffBytes;
16
+ painting: DiffBytes;
17
+ parts: PlacedPart[];
18
+ /** Same binary figure domain measureRecomposite reads; null means the whole canvas. */
19
+ inside: Uint8Array | null;
20
+ }
21
+ export interface DiffComponent {
22
+ id: string;
23
+ px: number;
24
+ box: { x: number; y: number; w: number; h: number };
25
+ coverage: 'covered' | 'uncovered' | 'mixed';
26
+ uncovered_px: number;
27
+ borders: { part: string; px: number }[];
28
+ }
29
+ export interface DiffComponentsReport {
30
+ spec: typeof DIFF_COMPONENTS_SPEC;
31
+ stack: { path: string; sha256: string };
32
+ painting: { path: string; sha256: string };
33
+ definition: {
34
+ metric: 'max-absolute-rgb-channel'; threshold: number; comparison: '>'; connectivity: 8;
35
+ floor_px: number; coordinates: 'native'; y: 'down'; origin: 'top-left'; resampling: 'none';
36
+ covered_alpha_above: number; width: number; height: number; inside_sha256: string | null;
37
+ };
38
+ error_px: number;
39
+ uncovered_error_px: number;
40
+ components: DiffComponent[];
41
+ below_floor: { count: number; px: number; uncovered_px: number };
42
+ }
43
+ const sha = (bytes: Uint8Array): string => createHash('sha256').update(bytes).digest('hex');
44
+ function inputFailure(object: string, detail: string): never {
45
+ throw new PartsError([{ code: 'DIFF_COMPONENTS_INPUT', object, detail }]);
46
+ }
47
+ function reportFailure(detail: string): never {
48
+ throw new PartsError([{ code: 'DIFF_COMPONENTS_REPORT', object: 'diff components report', detail }]);
49
+ }
50
+
51
+ /** Shared by measurement and both command modes; report every invalid numeric field. */
52
+ function diffDefinition(floor: number, threshold: number): void {
53
+ const problems: Problem[] = [];
54
+ if (!Number.isSafeInteger(floor) || floor < 1) problems.push({ code: 'DIFF_COMPONENTS_INPUT', object: 'floor_px', detail: `is ${floor}; a positive safe integer is required` });
55
+ if (!Number.isFinite(threshold) || threshold < 0 || threshold > 255) problems.push({ code: 'DIFF_COMPONENTS_INPUT', object: 'threshold', detail: `is ${threshold}; a finite channel threshold in [0,255] is required` });
56
+ if (problems.length > 0) throw new PartsError(problems);
57
+ }
58
+
59
+ /** The codec's failure remains a named input refusal at this command boundary. */
60
+ function diffPng(bytes: Uint8Array, label: string): Raster {
61
+ try { return decodePngBytes(bytes, label); }
62
+ catch (err) { return inputFailure(label, `cannot decode PNG: ${JSON.stringify(err instanceof Error ? err.message : err)}; valid PNG bytes are required`); }
63
+ }
64
+
65
+ /** Hash and decode each source from the same buffer. No alignment or resampling. */
66
+ export function measureDiffComponents(input: DiffInputs, floor: number, threshold = ERROR_LIMIT): DiffComponentsReport {
67
+ diffDefinition(floor, threshold);
68
+ const stack = diffPng(input.stack.bytes, input.stack.path);
69
+ const painting = diffPng(input.painting.bytes, input.painting.path);
70
+ const W = painting.width, H = painting.height;
71
+ if (stack.width !== W || stack.height !== H) inputFailure('stack', `is ${stack.width}x${stack.height}; painting ${W}x${H} is required, with no resampling`);
72
+ if (input.inside !== null) {
73
+ const bad = input.inside.findIndex(v => v !== 0 && v !== 1);
74
+ if (input.inside.length !== W * H || bad >= 0) inputFailure('inside', `has ${input.inside.length} pixels, first nonbinary value ${bad < 0 ? 'none' : `${input.inside[bad]} at index ${bad}`}; ${W * H} binary 0/1 pixels in the painting's native frame are required`);
75
+ }
76
+ const names = new Set<string>();
77
+ for (const { record: p, image } of input.parts) {
78
+ if (!p.name || names.has(p.name) || ![p.x, p.y, p.w, p.h].every(Number.isSafeInteger) || p.x < 0 || p.y < 0 || p.w < 1 || p.h < 1 || p.x + p.w > W || p.y + p.h > H || image.width !== p.w || image.height !== p.h || image.data.length < p.w * p.h * 4) inputFailure(`part "${p.name}"`, `box ${p.x},${p.y} ${p.w}x${p.h}, image ${image.width}x${image.height} with ${image.data.length} RGBA bytes, duplicate name ${names.has(p.name)}; a unique nonempty name and an integer in-canvas matching box with four RGBA bytes per pixel are required on ${W}x${H}`);
79
+ names.add(p.name);
80
+ }
81
+ const covered = coveredMask(input.parts, W, H);
82
+ const err = errorMask(stack, painting, input.inside, threshold);
83
+ const mask = newMask(W, H); mask.data.set(err);
84
+ const cc = connectedComponents(mask, 8);
85
+ const first = new Float64Array(cc.stats.length).fill(-1);
86
+ const uncovered = new Float64Array(cc.stats.length);
87
+ let errorPx = 0, uncoveredPx = 0;
88
+ for (let p = 0; p < err.length; p++) if (err[p]) {
89
+ const label = cc.labels[p];
90
+ if (first[label] === -1) first[label] = p;
91
+ errorPx++;
92
+ if (!covered[p]) { uncovered[label]++; uncoveredPx++; }
93
+ }
94
+ const components: DiffComponent[] = [];
95
+ const below = { count: 0, px: 0, uncovered_px: 0 };
96
+ for (const s of cc.stats.slice(1).filter(s => s.area > 0).sort((a,b) => first[a.label] - first[b.label])) {
97
+ const u = uncovered[s.label];
98
+ if (s.area < floor) { below.count++; below.px += s.area; below.uncovered_px += u; continue; }
99
+ components.push({ id: `p${first[s.label]}-n${s.area}`, px: s.area,
100
+ box: { x: s.left, y: s.top, w: s.width, h: s.height },
101
+ coverage: u === 0 ? 'covered' : u === s.area ? 'uncovered' : 'mixed', uncovered_px: u,
102
+ borders: holeBorders(input.parts, cc, s, W, H, COVERED_ALPHA) });
103
+ }
104
+ return { spec: DIFF_COMPONENTS_SPEC,
105
+ stack: { path: input.stack.path, sha256: sha(input.stack.bytes) },
106
+ painting: { path: input.painting.path, sha256: sha(input.painting.bytes) },
107
+ definition: { metric: 'max-absolute-rgb-channel', threshold, comparison: '>', connectivity: 8, floor_px: floor,
108
+ coordinates: 'native', y: 'down', origin: 'top-left', resampling: 'none', covered_alpha_above: COVERED_ALPHA,
109
+ width: W, height: H, inside_sha256: input.inside === null ? null : sha(input.inside) },
110
+ error_px: errorPx, uncovered_error_px: uncoveredPx, components, below_floor: below };
111
+ }
112
+ export function serializeDiffComponents(report: DiffComponentsReport): string { return JSON.stringify(report, null, 2) + '\n'; }
113
+ export function writeDiffComponents(path: string, input: DiffInputs, floor: number, threshold = ERROR_LIMIT): DiffComponentsReport {
114
+ const report = measureDiffComponents(input, floor, threshold);
115
+ try { writeFileSync(path, serializeDiffComponents(report)); }
116
+ catch (err) { inputFailure(path, `cannot write report: ${JSON.stringify(err instanceof Error ? err.message : err)}; a writable output file path is required`); }
117
+ return report;
118
+ }
119
+ const object = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null && !Array.isArray(v);
120
+ const shown = (v: unknown): string => v === undefined ? 'missing' : Array.isArray(v) ? `array with ${v.length} entries` : typeof v === 'number' && !Number.isFinite(v) ? String(v) : JSON.stringify(v);
121
+ /** Recompute the inventory against the supplied bytes and coverage/domain. A capped or edited report is refused. */
122
+ export function readDiffComponents(text: string, input: DiffInputs): DiffComponentsReport {
123
+ let raw: unknown;
124
+ try { raw = JSON.parse(text); } catch (err) { return reportFailure(`cannot parse JSON: ${JSON.stringify(err instanceof Error ? err.message : err)}; valid JSON is required`); }
125
+ if (!object(raw)) return reportFailure(`found ${shown(raw)}; a ${DIFF_COMPONENTS_SPEC} report object is required`);
126
+ if (raw.spec !== DIFF_COMPONENTS_SPEC) return reportFailure(`spec is ${shown(raw.spec)}; ${DIFF_COMPONENTS_SPEC} is required`);
127
+ if (!object(raw.stack) || !object(raw.painting) || !object(raw.definition)) return reportFailure(`stack=${shown(raw.stack)}, painting=${shown(raw.painting)}, definition=${shown(raw.definition)}; all three objects are required`);
128
+ const bindings: Problem[] = [];
129
+ for (const key of ['stack', 'painting'] as const) {
130
+ const binding = raw[key] as Record<string, unknown>;
131
+ const required = sha(input[key].bytes);
132
+ if (binding.sha256 !== required) bindings.push({ code: 'DIFF_COMPONENTS_BINDING', object: key,
133
+ detail: `sha256 is ${shown(binding.sha256)}; ${required} is required for the bytes actually measured` });
134
+ }
135
+ if (bindings.length > 0) throw new PartsError(bindings);
136
+ const floor = raw.definition.floor_px, threshold = raw.definition.threshold;
137
+ if (typeof floor !== 'number' || typeof threshold !== 'number') return reportFailure(`definition floor_px=${shown(floor)}, threshold=${shown(threshold)}; both must be numbers`);
138
+ const expected = measureDiffComponents(input, floor, threshold);
139
+ const differences: Problem[] = [];
140
+ const fail = (path: string, found: unknown, required: unknown): void => {
141
+ differences.push({ code: 'DIFF_COMPONENTS_REPORT', object: path,
142
+ detail: `found ${shown(found)}; required ${shown(required)} from the exhaustive measurement; regenerate the report` });
143
+ };
144
+ const compare = (found: unknown, required: unknown, path: string): void => {
145
+ if (Array.isArray(required)) {
146
+ if (!Array.isArray(found)) { fail(path, found, required); return; }
147
+ if (found.length !== required.length) fail(`${path}.length`, found.length, required.length);
148
+ for (let i = 0; i < Math.max(found.length, required.length); i++) compare(found[i], required[i], `${path}[${i}]`);
149
+ } else if (object(required)) {
150
+ if (!object(found)) { fail(path, found, required); return; }
151
+ for (const key of Object.keys(required)) compare(found[key], required[key], `${path}.${key}`);
152
+ for (const key of Object.keys(found).sort()) if (!Object.hasOwn(required, key)) {
153
+ const field = /^[A-Za-z_$][\w$]*$/.test(key) ? `${path}.${key}` : `${path}[${JSON.stringify(key)}]`;
154
+ fail(field, found[key], undefined);
155
+ }
156
+ } else if (found !== required) fail(path, found, required);
157
+ };
158
+ compare(raw, expected, 'report');
159
+ if (differences.length > 0) throw new PartsError(differences);
160
+ return expected;
161
+ }
162
+
163
+ /** CLI adapter: explicit native PNGs, plus assembled parts for coverage; optional figure mask is never inferred. */
164
+ export function diffComponentsCommand(args: string[]): void {
165
+ const allowed = ['--stack', '--painting', '--parts', '--figure', '--floor', '--threshold', '--out', '--verify'];
166
+ const flags = new Map<string,string>();
167
+ for (let i = 0; i < args.length; i += 2) {
168
+ const key = args[i], value = args[i + 1];
169
+ if (!allowed.includes(key) || flags.has(key) || value === undefined || value.startsWith('--')) inputFailure('arguments', `requires unique ${allowed.join(', ')} flags with values; found ${key}`);
170
+ if (value.length === 0) inputFailure(key, 'is ""; a nonempty value is required');
171
+ flags.set(key, value);
172
+ }
173
+ for (const key of ['--stack', '--painting', '--parts', '--floor']) if (!flags.has(key)) inputFailure(key, 'is missing; an explicit value is required');
174
+ if (flags.has('--out') === flags.has('--verify')) inputFailure('arguments', `has --out=${flags.has('--out')} and --verify=${flags.has('--verify')}; exactly one is required`);
175
+ const numericFlag = (key: string): number => {
176
+ const value = flags.get(key)!;
177
+ if (value.trim().length === 0) inputFailure(key, `is ${JSON.stringify(value)}; an explicit number is required`);
178
+ return Number(value);
179
+ };
180
+ const floor = numericFlag('--floor'), threshold = flags.has('--threshold') ? numericFlag('--threshold') : ERROR_LIMIT;
181
+ diffDefinition(floor, threshold);
182
+ const bytes = (path: string): DiffBytes => {
183
+ try { return { path, bytes: readFileSync(path) }; } catch (err) { return inputFailure(path, `cannot read file: ${JSON.stringify(err instanceof Error ? err.message : err)}; readable input bytes are required`); }
184
+ };
185
+ const partsPath = flags.get('--parts')!;
186
+ const parts = readParts(partsPath);
187
+ const placed = parts.parts.map(record => ({ record, image: diffPng(bytes(join(dirname(partsPath), 'parts', `${record.name}.png`)).bytes, record.name) }));
188
+ const stack = bytes(flags.get('--stack')!), painting = bytes(flags.get('--painting')!);
189
+ const reference = diffPng(painting.bytes, painting.path);
190
+ if (parts.rig_size[0] !== reference.width || parts.rig_size[1] !== reference.height) inputFailure('parts.rig_size', `is ${parts.rig_size[0]}x${parts.rig_size[1]}; painting ${reference.width}x${reference.height} is required, with no resampling`);
191
+ let inside: Uint8Array | null = null;
192
+ if (flags.has('--figure')) {
193
+ const image = diffPng(bytes(flags.get('--figure')!).bytes, '--figure');
194
+ if (image.width !== reference.width || image.height !== reference.height) inputFailure('--figure', `is ${image.width}x${image.height}; painting ${reference.width}x${reference.height} is required, with no resampling`);
195
+ inside = new Uint8Array(image.width * image.height);
196
+ for (let p = 0; p < inside.length; p++) {
197
+ const s = p * 4, v = image.data[s];
198
+ if ((v !== 0 && v !== 255) || image.data[s+1] !== v || image.data[s+2] !== v || image.data[s+3] !== 255) inputFailure('--figure', `pixel ${p % image.width},${Math.floor(p / image.width)} is RGBA [${Array.from(image.data.slice(s,s+4)).join(',')}]; opaque black [0,0,0,255] or white [255,255,255,255] is required`);
199
+ inside[p] = v === 255 ? 1 : 0;
200
+ }
201
+ }
202
+ const input = { stack, painting, parts: placed, inside };
203
+ if (flags.has('--verify')) {
204
+ const path = flags.get('--verify')!;
205
+ const report = readDiffComponents(new TextDecoder().decode(bytes(path).bytes), input);
206
+ if (report.definition.floor_px !== floor || report.definition.threshold !== threshold) inputFailure('definition', `report floor_px=${report.definition.floor_px}, threshold=${report.definition.threshold}; caller floor_px=${floor}, threshold=${threshold} are required`);
207
+ } else writeDiffComponents(flags.get('--out')!, input, floor, threshold);
208
+ }
@@ -0,0 +1,191 @@
1
+ /** Report-only visible-back residual candidates after edge composition (#999). */
2
+ import { EDGE_OWNER_ALPHA } from './paintingedges.ts';
3
+ import { type Raster, RasterError } from './raster/types.ts';
4
+
5
+ export const EDGE_PAIR_RESIDUAL = 'EDGE_PAIR_RESIDUAL';
6
+ export const EDGE_RESIDUAL_FILE = 'edge_residuals.json';
7
+ export interface ResidualPart {
8
+ name: string;
9
+ x: number;
10
+ y: number;
11
+ image: Raster;
12
+ }
13
+ export interface ResidualPair {
14
+ front: string;
15
+ back: string;
16
+ status: 'measured' | 'skip' | 'unavailable';
17
+ residual_px: number | null;
18
+ /** Rig pixels, [left, top, width, height]. */
19
+ box: [number, number, number, number] | null;
20
+ /** Coordinates reference the existing back part PNG at its parts.json placement.
21
+ * Spans are [y, left, right-exclusive], sorted by y then left. */
22
+ back_pixels: { count: number; spans: Array<[number, number, number]> };
23
+ skipped: string[];
24
+ unavailable: string[];
25
+ unavailable_px: number;
26
+ }
27
+ export interface EdgeResidualReport {
28
+ spec: 'rig-parts-edge-residuals/1';
29
+ observation: 'visible-back RGB-error components touching one overlapping front boundary; candidates, painting ownership unproven';
30
+ stage: 'final assembled parts after paintingEdges and seam correction';
31
+ grid: [number, number];
32
+ rgb_tolerance: number;
33
+ owner_alpha_above: number;
34
+ connectivity: 8;
35
+ pairs: ResidualPair[];
36
+ summary: { pairs: number; measured: number; skipped: number; unavailable: number; residual_px: number; unassigned_error_px: number };
37
+ }
38
+
39
+ function offset(part: ResidualPart, x: number, y: number): number | null {
40
+ const lx = x - part.x, ly = y - part.y;
41
+ if (lx < 0 || ly < 0 || lx >= part.image.width || ly >= part.image.height) return null;
42
+ return (ly * part.image.width + lx) * 4;
43
+ }
44
+ function alpha(part: ResidualPart, x: number, y: number): number {
45
+ const at = offset(part, x, y);
46
+ return at === null ? 0 : part.image.data[at + 3];
47
+ }
48
+ function overlap(a: ResidualPart, b: ResidualPart): boolean {
49
+ const right = Math.min(a.x + a.image.width, b.x + b.image.width);
50
+ const bottom = Math.min(a.y + a.image.height, b.y + b.image.height);
51
+ for (let y = Math.max(a.y, b.y); y < bottom; y++) {
52
+ for (let x = Math.max(a.x, b.x); x < right; x++) {
53
+ if (alpha(a, x, y) > EDGE_OWNER_ALPHA && alpha(b, x, y) > EDGE_OWNER_ALPHA) return true;
54
+ }
55
+ }
56
+ return false;
57
+ }
58
+ function spans(pixels: number[], width: number): Array<[number, number, number]> {
59
+ const out: Array<[number, number, number]> = [];
60
+ for (const p of pixels.sort((a, b) => a - b)) {
61
+ const x = p % width, y = Math.floor(p / width), previous = out.at(-1);
62
+ if (previous !== undefined && previous[0] === y && previous[2] === x) previous[2]++;
63
+ else out.push([y, x, x + 1]);
64
+ }
65
+ return out;
66
+ }
67
+
68
+ /** Read existing limits, never set a new bar or a reach cap. Components are
69
+ * observations of residual colour error. Semantic painting ownership cannot
70
+ * be established from colour and draw order and is explicitly unproven. */
71
+ export function edgePairResiduals(parts: readonly ResidualPart[], painting: Raster, composite: Raster, tolerance: number): EdgeResidualReport {
72
+ const W = painting.width, H = painting.height, size = W * H;
73
+ if (composite.width !== W || composite.height !== H) throw new RasterError('edgePairResiduals: composite and painting require the same native rig grid');
74
+ const n = parts.length;
75
+ const owner = new Int32Array(size).fill(-1);
76
+ const pure = new Uint8Array(size);
77
+ const visible = new Uint32Array(n);
78
+ const errors = new Uint8Array(size);
79
+ for (let y = 0; y < H; y++) {
80
+ for (let x = 0; x < W; x++) {
81
+ const p = y * W + x;
82
+ for (let i = n - 1; i >= 0; i--) {
83
+ if (alpha(parts[i], x, y) > EDGE_OWNER_ALPHA) { owner[p] = i; visible[i]++; break; }
84
+ }
85
+ const back = owner[p];
86
+ if (back >= 0) {
87
+ let opaque = alpha(parts[back], x, y) === 255;
88
+ for (let i = back + 1; i < n && opaque; i++) if (alpha(parts[i], x, y) > 0) opaque = false;
89
+ pure[p] = opaque ? 1 : 0;
90
+ }
91
+ let delta = 0;
92
+ for (let c = 0; c < 3; c++) delta = Math.max(delta, Math.abs(composite.data[p * 4 + c] - painting.data[p * 4 + c]));
93
+ errors[p] = delta > tolerance ? 1 : 0;
94
+ }
95
+ }
96
+ const neighbours = (p: number, visit: (q: number) => void): void => {
97
+ const x = p % W, y = Math.floor(p / W);
98
+ for (let dy = -1; dy <= 1; dy++) {
99
+ for (let dx = -1; dx <= 1; dx++) {
100
+ if ((dx === 0 && dy === 0) || x + dx < 0 || x + dx >= W || y + dy < 0 || y + dy >= H) continue;
101
+ visit((y + dy) * W + x + dx);
102
+ }
103
+ }
104
+ };
105
+ const adjacency = new Uint8Array(n * n);
106
+ for (let p = 0; p < size; p++) {
107
+ if (owner[p] < 0) continue;
108
+ neighbours(p, q => {
109
+ if (owner[q] > owner[p]) adjacency[owner[q] * n + owner[p]] = 1;
110
+ });
111
+ }
112
+ const rows = new Map<number, ResidualPair>();
113
+ const selected = new Map<number, number[]>();
114
+ for (let front = 1; front < n; front++) {
115
+ for (let back = 0; back < front; back++) {
116
+ const row: ResidualPair = { front: parts[front].name, back: parts[back].name, status: 'measured', residual_px: 0, box: null, back_pixels: { count: 0, spans: [] }, skipped: [], unavailable: [], unavailable_px: 0 };
117
+ if (!overlap(parts[front], parts[back])) { row.status = 'skip'; row.skipped.push('no alpha overlap above the existing owner floor'); }
118
+ else if (visible[front] === 0 || visible[back] === 0) {
119
+ row.status = 'unavailable';
120
+ row.unavailable.push(visible[front] === 0 ? 'front has no visible boundary observation' : 'back has no visible pixel observation');
121
+ row.residual_px = null;
122
+ } else if (adjacency[front * n + back] === 0) { row.status = 'skip'; row.skipped.push('no exposed front/back boundary'); }
123
+ rows.set(front * n + back, row);
124
+ }
125
+ }
126
+ const visited = new Uint8Array(size);
127
+ let unassigned = 0;
128
+ for (let start = 0; start < size; start++) {
129
+ if (errors[start] === 0 || visited[start] === 1) continue;
130
+ const back = owner[start];
131
+ if (back < 0) { visited[start] = 1; unassigned++; continue; }
132
+ const queue = [start], fronts = new Set<number>();
133
+ let mixed = false;
134
+ visited[start] = 1;
135
+ for (let cursor = 0; cursor < queue.length; cursor++) {
136
+ const p = queue[cursor];
137
+ if (pure[p] === 0) mixed = true;
138
+ neighbours(p, q => {
139
+ const front = owner[q];
140
+ if (front > back && rows.get(front * n + back)?.status === 'measured') fronts.add(front);
141
+ if (errors[q] === 1 && owner[q] === back && visited[q] === 0) { visited[q] = 1; queue.push(q); }
142
+ });
143
+ }
144
+ if (fronts.size !== 1 || mixed) {
145
+ unassigned += queue.length;
146
+ for (const front of fronts) {
147
+ const row = rows.get(front * n + back)!;
148
+ row.unavailable_px += queue.length;
149
+ const reason = mixed ? 'residual component includes partial-alpha or additional foreground contribution' : 'residual component touches multiple overlapping fronts';
150
+ if (!row.unavailable.includes(reason)) row.unavailable.push(reason);
151
+ }
152
+ continue;
153
+ }
154
+ const front = [...fronts][0], key = front * n + back;
155
+ const pixels = selected.get(key) ?? [];
156
+ for (const pixel of queue) pixels.push(pixel);
157
+ selected.set(key, pixels);
158
+ }
159
+ for (const [key, row] of rows) {
160
+ const pixels = selected.get(key) ?? [];
161
+ row.back_pixels = { count: pixels.length, spans: spans(pixels, W) };
162
+ if (pixels.length > 0) {
163
+ let left = W, top = H, right = 0, bottom = 0;
164
+ for (const p of pixels) { const x = p % W, y = Math.floor(p / W); left = Math.min(left, x); top = Math.min(top, y); right = Math.max(right, x + 1); bottom = Math.max(bottom, y + 1); }
165
+ row.box = [left, top, right - left, bottom - top];
166
+ }
167
+ if (row.unavailable.length > 0) {
168
+ row.status = 'unavailable';
169
+ row.residual_px = null;
170
+ // Retained candidates still count when this pair's attribution is unavailable.
171
+ unassigned += pixels.length;
172
+ }
173
+ else if (row.status === 'measured') row.residual_px = pixels.length;
174
+ }
175
+ const pairs = [...rows.values()];
176
+ return {
177
+ spec: 'rig-parts-edge-residuals/1',
178
+ observation: 'visible-back RGB-error components touching one overlapping front boundary; candidates, painting ownership unproven',
179
+ stage: 'final assembled parts after paintingEdges and seam correction',
180
+ grid: [W, H], rgb_tolerance: tolerance, owner_alpha_above: EDGE_OWNER_ALPHA, connectivity: 8, pairs,
181
+ summary: { pairs: pairs.length, measured: pairs.filter(p => p.status === 'measured').length, skipped: pairs.filter(p => p.status === 'skip').length, unavailable: pairs.filter(p => p.status === 'unavailable').length, residual_px: pairs.reduce((sum, p) => sum + (p.residual_px ?? 0), 0), unassigned_error_px: unassigned },
182
+ };
183
+ }
184
+
185
+ export function edgeResidualLines(report: EdgeResidualReport): string[] {
186
+ const s = report.summary;
187
+ return [
188
+ `${EDGE_PAIR_RESIDUAL}: ${s.measured} of ${s.pairs} pairs measured, ${s.skipped} skipped, ${s.unavailable} unavailable; ${s.residual_px} candidate px, ${s.unassigned_error_px} unassigned error px; painting ownership unproven; report only`,
189
+ ...report.pairs.map(p => `${EDGE_PAIR_RESIDUAL}: front "${p.front}", back "${p.back}" ${p.status}; residual px ${p.residual_px ?? 'unavailable'}, box ${p.box === null ? 'none' : `[${p.box.join(', ')}]`}, back pixels ${p.back_pixels.count}${p.skipped.length === 0 ? '' : `; skipped ${p.skipped.join(', ')}`}${p.unavailable.length === 0 ? '' : `; unavailable ${p.unavailable.join(', ')}`}`),
190
+ ];
191
+ }
package/src/mesh.ts CHANGED
@@ -44,8 +44,9 @@
44
44
  * against.
45
45
  */
46
46
  import { type Problem } from './errors.ts';
47
- import { connectedComponents, fillHoles, fillPoly, type Mask, newMask } from './raster/index.ts';
48
- import { rint } from './round.ts';
47
+ import { alphaAbove, connectedComponents, fillHoles, fillPoly, type Mask, newMask } from './raster/index.ts';
48
+ import type { Raster } from './raster/types.ts';
49
+ import { pyRound, rint } from './round.ts';
49
50
 
50
51
  /** A pixel counts as art when its alpha is above this — the reference's `im[..., 3] > 8`. */
51
52
  export const ART_ALPHA = 8;
@@ -440,3 +441,29 @@ export function latticeStray(art: Mask, stray: number): LatticeStray {
440
441
  for (let i = 0; i < data.length; i++) if (out[comp.labels[i]] === 1) data[i] = 0;
441
442
  return { art: { width: art.width, height: art.height, data }, islands, pixels, artPixels, largest };
442
443
  }
444
+
445
+ /** A part's art islands, largest first, and what the dust rule makes of them. */
446
+ export type DustReading = { stray: number | undefined; islands: number[]; dust: number[] } | { keep: string; islands: number[] };
447
+
448
+ /**
449
+ * The dust rule on a part image (its alpha, unpadded or padded alike: the pad adds no art): the 4-connected islands
450
+ * of alpha above `ART_ALPHA` — the contour mode's own island rule — and whether every island past the largest is
451
+ * dust ({@link DUST_MAX_PX}, {@link DUST_MAX_SHARE}). A tie for the largest is no single largest island, which the
452
+ * contour mode refuses, so it keeps the lattice too.
453
+ */
454
+ export function dustOf(image: Raster): DustReading {
455
+ const comp = connectedComponents(alphaAbove(image, ART_ALPHA), 4);
456
+ const islands = comp.stats.slice(1).map((s) => s.area).sort((a, b) => b - a);
457
+ const art = islands.reduce((a, b) => a + b, 0);
458
+ if (islands.length === 0) return { keep: `its image has no pixel with alpha above ${ART_ALPHA}`, islands };
459
+ if (islands.length > 1 && islands[0] === islands[1]) return { keep: `its art is ${islands.length} islands (${islands.join(', ')} px) of which two share the largest count, so no one island is the largest`, islands };
460
+ const extra = islands.slice(1);
461
+ const pieces = extra.filter((n) => !isDust(n, art));
462
+ if (pieces.length > 0) {
463
+ return {
464
+ keep: `its art is ${islands.length} islands (${islands.join(', ')} px); ${pieces.length} beside the largest ${pieces.length === 1 ? 'is a real piece' : 'are real pieces'}, not dust (at most ${DUST_MAX_PX} px and at most ${pyRound(DUST_MAX_SHARE * 100, 6)} % of the part's ${art} art px), and the contour mode meshes one island`,
465
+ islands,
466
+ };
467
+ }
468
+ return { stray: extra.length === 0 ? undefined : extra[0], islands, dust: extra };
469
+ }
package/src/meshdraft.ts CHANGED
@@ -71,9 +71,8 @@ import { type CharacterConfig, configFileReferences, type ConfigFileReference, t
71
71
  import { PartsError, type Problem, problemLine } from './errors.ts';
72
72
  import { IDLE_FPS } from './motion.ts';
73
73
  import { type ContourBridges, FAINT_ALPHA } from './contour.ts';
74
- import { ART_ALPHA, DUST_MAX_PX, DUST_MAX_SHARE, isDust } from './mesh.ts';
74
+ import { ART_ALPHA, DUST_MAX_PX, DUST_MAX_SHARE, isDust, dustOf, type DustReading } from './mesh.ts';
75
75
  import { type PartsFile, readParts } from './parts.ts';
76
- import { alphaAbove, connectedComponents } from './raster/index.ts';
77
76
  import { readPng } from './raster/png.ts';
78
77
  import type { Raster } from './raster/types.ts';
79
78
  import { buildRig, type IdleKeys, type MeshAttachment, rigJsonText, type RigSpec } from './rig.ts';
@@ -196,31 +195,7 @@ export function figureRules(parts: Pick<PartsFile, 'parts'>): FigureRules | Prob
196
195
  // the candidate
197
196
  // ---------------------------------------------------------------------------
198
197
 
199
- /** A part's art islands, largest first, and what the dust rule makes of them. */
200
- export type DustReading = { stray: number | undefined; islands: number[]; dust: number[] } | { keep: string; islands: number[] };
201
-
202
- /**
203
- * The dust rule on a part image (its alpha, unpadded or padded alike: the pad adds no art): the 4-connected islands
204
- * of alpha above `ART_ALPHA` — the contour mode's own island rule — and whether every island past the largest is
205
- * dust ({@link DUST_MAX_PX}, {@link DUST_MAX_SHARE}). A tie for the largest is no single largest island, which the
206
- * contour mode refuses, so it keeps the lattice too.
207
- */
208
- export function dustOf(image: Raster): DustReading {
209
- const comp = connectedComponents(alphaAbove(image, ART_ALPHA), 4);
210
- const islands = comp.stats.slice(1).map((s) => s.area).sort((a, b) => b - a);
211
- const art = islands.reduce((a, b) => a + b, 0);
212
- if (islands.length === 0) return { keep: `its image has no pixel with alpha above ${ART_ALPHA}`, islands };
213
- if (islands.length > 1 && islands[0] === islands[1]) return { keep: `its art is ${islands.length} islands (${islands.join(', ')} px) of which two share the largest count, so no one island is the largest`, islands };
214
- const extra = islands.slice(1);
215
- const pieces = extra.filter((n) => !isDust(n, art));
216
- if (pieces.length > 0) {
217
- return {
218
- keep: `its art is ${islands.length} islands (${islands.join(', ')} px); ${pieces.length} beside the largest ${pieces.length === 1 ? 'is a real piece' : 'are real pieces'}, not dust (at most ${DUST_MAX_PX} px and at most ${pyRound(DUST_MAX_SHARE * 100, 6)} % of the part's ${art} art px), and the contour mode meshes one island`,
219
- islands,
220
- };
221
- }
222
- return { stray: extra.length === 0 ? undefined : extra[0], islands, dust: extra };
223
- }
198
+ export { dustOf, type DustReading } from './mesh.ts';
224
199
 
225
200
  /**
226
201
  * The candidate for one lattice entry: the outline mesh at the figure's numbers, its weights' fields as the lattice