@rig-c/parts 2.8.0 → 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.
- package/README.md +1 -1
- package/cli.ts +42 -5
- package/docs/AUTHORING.md +204 -12
- package/docs/MIGRATION.md +20 -1
- package/docs/STABILITY.md +7 -1
- package/package.json +1 -1
- package/skills/rig-parts/SKILL.md +1 -1
- package/src/assemble.ts +32 -11
- package/src/build.ts +29 -7
- package/src/check.ts +201 -30
- package/src/coincide.ts +157 -0
- package/src/coincideio.ts +79 -0
- package/src/config.ts +41 -4
- package/src/diffcomponents.ts +208 -0
- package/src/edgeresidual.ts +191 -0
- package/src/mesh.ts +29 -2
- package/src/meshdraft.ts +8 -49
- package/src/propose.ts +150 -5
- package/src/supportdomains.ts +76 -0
- package/tools/build-process.ts +31 -9
package/src/coincide.ts
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
/** Report-only missing support observations on the native setup grid (#998). */
|
|
2
|
+
import { refuseIfAny } from './errors.ts';
|
|
3
|
+
import { connectedComponents } from './raster/components.ts';
|
|
4
|
+
import { assertBinary, type Mask } from './raster/types.ts';
|
|
5
|
+
|
|
6
|
+
export const COINCIDE_LINE = 'PART_SUPPORT_REPORT';
|
|
7
|
+
export const SUPPORT_GRID_CODE = 'CHECK_SUPPORT_GRID';
|
|
8
|
+
export type SupportBox = [number, number, number, number];
|
|
9
|
+
/** Independent stage-grid witness, supplied by the producer. Never derive it
|
|
10
|
+
* from the final alpha or from the part's cropped PNG rectangle. */
|
|
11
|
+
export interface SupportDomain {
|
|
12
|
+
part: string;
|
|
13
|
+
mask: Mask;
|
|
14
|
+
provenance: { kind: 'cut-polygon' | 'limb-capsule'; entry: string };
|
|
15
|
+
}
|
|
16
|
+
export interface UnavailableSupportDomain { part: string; reason: string }
|
|
17
|
+
export type SupportDomainReading = SupportDomain | UnavailableSupportDomain;
|
|
18
|
+
export interface SupportPart { name: string; mask: Mask }
|
|
19
|
+
export interface SupportPair {
|
|
20
|
+
front: string;
|
|
21
|
+
back: string;
|
|
22
|
+
status: 'measured' | 'unavailable';
|
|
23
|
+
reason?: string;
|
|
24
|
+
boundary_length_px: number | null;
|
|
25
|
+
/** Bounds of the shared unit segments, exclusive far edge. */
|
|
26
|
+
box: SupportBox | null;
|
|
27
|
+
/** Missing cells in B's domain under F, a candidate bound, not inferred art. */
|
|
28
|
+
continuation_candidate_area_px: number | null;
|
|
29
|
+
}
|
|
30
|
+
export interface RawSupportPair {
|
|
31
|
+
front: string;
|
|
32
|
+
back: string;
|
|
33
|
+
boundary_length_px: number;
|
|
34
|
+
/** Bounds of shared unit segments and overlapping cells. */
|
|
35
|
+
box: SupportBox;
|
|
36
|
+
overlap_area_px: number;
|
|
37
|
+
classification: 'ownership unknown, unclassified';
|
|
38
|
+
}
|
|
39
|
+
export interface UnownedReading {
|
|
40
|
+
status: 'measured' | 'unavailable';
|
|
41
|
+
reason?: string;
|
|
42
|
+
area_px: number | null;
|
|
43
|
+
regions: Array<{ box: SupportBox; area_px: number }>;
|
|
44
|
+
}
|
|
45
|
+
export interface SupportReport {
|
|
46
|
+
status: 'REPORTED' | 'WARN' | 'UNCLASSIFIED';
|
|
47
|
+
grid: [number, number];
|
|
48
|
+
alpha: 'alpha >= 128';
|
|
49
|
+
pair_registration: string;
|
|
50
|
+
unowned_registration: string;
|
|
51
|
+
boundary: '4-neighbour unit pixel-cell edges, exact coincidence';
|
|
52
|
+
pairs: SupportPair[];
|
|
53
|
+
raw_pairs: RawSupportPair[];
|
|
54
|
+
coverage: { measured: number; total: number };
|
|
55
|
+
unowned: UnownedReading;
|
|
56
|
+
reason?: string;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Parts are ordered back to front. A boundary segment is counted only when
|
|
60
|
+
* the adjacent F cell is missing from B AND belongs to B's independent domain.
|
|
61
|
+
* No dilation, inferred continuation, limit or gate is applied. */
|
|
62
|
+
export function supportReport(
|
|
63
|
+
width: number, height: number, parts: readonly SupportPart[],
|
|
64
|
+
domains: readonly SupportDomainReading[], paintedFigure: Mask | null,
|
|
65
|
+
unavailableReason = 'independent support domain is unavailable',
|
|
66
|
+
): SupportReport {
|
|
67
|
+
const check = (mask: Mask): void => {
|
|
68
|
+
assertBinary('support report', mask);
|
|
69
|
+
if (mask.data.length !== width * height || mask.width !== width || mask.height !== height) refuseIfAny([{ code: SUPPORT_GRID_CODE, object: 'support report mask', detail: `is ${mask.width}x${mask.height} with ${mask.data.length} cells; requires ${width}x${height} and ${width * height} cells on the native grid` }]);
|
|
70
|
+
};
|
|
71
|
+
for (const part of parts) check(part.mask);
|
|
72
|
+
for (const domain of domains) if ('mask' in domain) check(domain.mask);
|
|
73
|
+
if (paintedFigure !== null) check(paintedFigure);
|
|
74
|
+
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');
|
|
75
|
+
const bounds = parts.map(part => {
|
|
76
|
+
let left = width, top = height, right = 0, bottom = 0;
|
|
77
|
+
for (let y = 0; y < height; y++) for (let x = 0; x < width; x++) {
|
|
78
|
+
if (part.mask.data[y * width + x] === 0) continue;
|
|
79
|
+
left = Math.min(left, x); top = Math.min(top, y);
|
|
80
|
+
right = Math.max(right, x + 1); bottom = Math.max(bottom, y + 1);
|
|
81
|
+
}
|
|
82
|
+
return { left, top, right, bottom };
|
|
83
|
+
});
|
|
84
|
+
const raw_pairs: RawSupportPair[] = [];
|
|
85
|
+
const pairs: SupportPair[] = [];
|
|
86
|
+
for (let back = 0; back < parts.length; back++) for (let front = back + 1; front < parts.length; front++) {
|
|
87
|
+
const B = parts[back], F = parts[front], domain = domains.find(d => d.part === B.name);
|
|
88
|
+
const bb = bounds[back], fb = bounds[front];
|
|
89
|
+
let rawLength = 0, overlap = 0, rx0 = width, ry0 = height, rx1 = 0, ry1 = 0;
|
|
90
|
+
const include = (x: number, y: number, dx: number, dy: number): void => {
|
|
91
|
+
rx0 = Math.min(rx0, x); ry0 = Math.min(ry0, y);
|
|
92
|
+
rx1 = Math.max(rx1, x + dx); ry1 = Math.max(ry1, y + dy);
|
|
93
|
+
};
|
|
94
|
+
const rawEdge = (a: number, b: number, x: number, y: number, dx: number, dy: number): void => {
|
|
95
|
+
if (B.mask.data[a] !== 0 && B.mask.data[b] === 0 && F.mask.data[a] === 0 && F.mask.data[b] !== 0) {
|
|
96
|
+
rawLength++; include(x, y, dx, dy);
|
|
97
|
+
}
|
|
98
|
+
};
|
|
99
|
+
// Intersect occupied boxes before visiting pixels. The one-cell halo
|
|
100
|
+
// includes touching boxes and both directions of each shared edge.
|
|
101
|
+
const left = Math.max(0, bb.left - 1, fb.left - 1), top = Math.max(0, bb.top - 1, fb.top - 1);
|
|
102
|
+
const right = Math.min(width, bb.right + 1, fb.right + 1), bottom = Math.min(height, bb.bottom + 1, fb.bottom + 1);
|
|
103
|
+
for (let y = top; y < bottom; y++) for (let x = left; x < right; x++) {
|
|
104
|
+
const p = y * width + x;
|
|
105
|
+
if (B.mask.data[p] !== 0 && F.mask.data[p] !== 0) { overlap++; include(x, y, 1, 1); }
|
|
106
|
+
if (x + 1 < width) { rawEdge(p, p + 1, x + 1, y, 0, 1); rawEdge(p + 1, p, x + 1, y, 0, 1); }
|
|
107
|
+
if (y + 1 < height) { rawEdge(p, p + width, x, y + 1, 1, 0); rawEdge(p + width, p, x, y + 1, 1, 0); }
|
|
108
|
+
}
|
|
109
|
+
if (rawLength > 0 || overlap > 0) raw_pairs.push({ front: F.name, back: B.name,
|
|
110
|
+
boundary_length_px: rawLength, box: [rx0, ry0, rx1 - rx0, ry1 - ry0], overlap_area_px: overlap,
|
|
111
|
+
classification: 'ownership unknown, unclassified' });
|
|
112
|
+
if (domain === undefined || !('mask' in domain)) {
|
|
113
|
+
pairs.push({ front: F.name, back: B.name, status: 'unavailable', reason: `${B.name}: ${domain === undefined ? unavailableReason : domain.reason}`, boundary_length_px: null, box: null, continuation_candidate_area_px: null });
|
|
114
|
+
continue;
|
|
115
|
+
}
|
|
116
|
+
let length = 0, area = 0, x0 = width, y0 = height, x1 = 0, y1 = 0;
|
|
117
|
+
const edge = (a: number, b: number, x: number, y: number, dx: number, dy: number): void => {
|
|
118
|
+
if (B.mask.data[a] === 0 || B.mask.data[b] !== 0 || F.mask.data[a] !== 0 || F.mask.data[b] === 0 || domain.mask.data[a] === 0 || domain.mask.data[b] === 0) return;
|
|
119
|
+
length++;
|
|
120
|
+
x0 = Math.min(x0, x); y0 = Math.min(y0, y);
|
|
121
|
+
x1 = Math.max(x1, x + dx); y1 = Math.max(y1, y + dy);
|
|
122
|
+
};
|
|
123
|
+
for (let y = 0; y < height; y++) for (let x = 0; x < width; x++) {
|
|
124
|
+
const p = y * width + x;
|
|
125
|
+
if (domain.mask.data[p] !== 0 && F.mask.data[p] !== 0 && B.mask.data[p] === 0) area++;
|
|
126
|
+
if (x + 1 < width) { edge(p, p + 1, x + 1, y, 0, 1); edge(p + 1, p, x + 1, y, 0, 1); }
|
|
127
|
+
if (y + 1 < height) { edge(p, p + width, x, y + 1, 1, 0); edge(p + width, p, x, y + 1, 1, 0); }
|
|
128
|
+
}
|
|
129
|
+
pairs.push({ front: F.name, back: B.name, status: 'measured', boundary_length_px: length,
|
|
130
|
+
box: length === 0 ? null : [x0, y0, x1 - x0, y1 - y0], continuation_candidate_area_px: area });
|
|
131
|
+
}
|
|
132
|
+
const unowned = unownedSupport(width, height, parts, paintedFigure);
|
|
133
|
+
return { status: pairs.some(p => (p.boundary_length_px ?? 0) > 0) || (unowned.area_px ?? 0) > 0 ? 'WARN' : pairs.some(p => p.status === 'measured') ? 'REPORTED' : 'UNCLASSIFIED',
|
|
134
|
+
grid: [width, height], alpha: 'alpha >= 128', pair_registration: 'caller-supplied native masks', unowned_registration: 'caller-supplied native masks', boundary: '4-neighbour unit pixel-cell edges, exact coincidence',
|
|
135
|
+
pairs, raw_pairs, coverage: { measured: pairs.filter(p => p.status === 'measured').length, total: pairs.length }, unowned };
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** Painted cells outside the supplied actual setup union, including open edges. */
|
|
139
|
+
export function unownedSupport(width: number, height: number, parts: readonly SupportPart[], paintedFigure: Mask | null): UnownedReading {
|
|
140
|
+
let unowned: UnownedReading = { status: 'unavailable', reason: 'source painting and its painted silhouette are unavailable; supply --source', area_px: null, regions: [] };
|
|
141
|
+
if (paintedFigure !== null) {
|
|
142
|
+
const missing = paintedFigure.data.slice();
|
|
143
|
+
for (const part of parts) for (let p = 0; p < missing.length; p++) if (part.mask.data[p] !== 0) missing[p] = 0;
|
|
144
|
+
const regions = connectedComponents({ width, height, data: missing }, 4).stats.slice(1).map(s => ({ box: [s.left, s.top, s.width, s.height] as SupportBox, area_px: s.area }));
|
|
145
|
+
unowned = { status: 'measured', area_px: regions.reduce((sum, r) => sum + r.area_px, 0), regions };
|
|
146
|
+
}
|
|
147
|
+
return unowned;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
export function supportLines(report: SupportReport): string[] {
|
|
151
|
+
const classified = report.raw_pairs.filter(raw => report.pairs.some(pair => pair.back === raw.back && pair.front === raw.front && pair.status === 'measured')).length;
|
|
152
|
+
return [`${COINCIDE_LINE}: ${report.status} — ${report.raw_pairs.length} pairs adjacent, ${classified} classified${report.coverage.measured === 0 ? ' (no extent witness)' : ''}; ${report.coverage.measured} of ${report.coverage.total} pairs measured; pairs on ${report.pair_registration}; unowned on ${report.unowned_registration}${report.reason === undefined ? '' : `; ${report.reason}`}`,
|
|
153
|
+
...report.raw_pairs.map(p => `${COINCIDE_LINE}: back "${p.back}" front "${p.front}" shared boundary ${p.boundary_length_px} px, box ${JSON.stringify(p.box)}, overlap ${p.overlap_area_px} px — ${p.classification}`),
|
|
154
|
+
...report.pairs.map(p => `${COINCIDE_LINE}: back "${p.back}" front "${p.front}" ${p.status} — ${p.status === 'unavailable' ? p.reason : `boundary ${p.boundary_length_px} px, box ${JSON.stringify(p.box)}, continuation candidate ${p.continuation_candidate_area_px} px`}`),
|
|
155
|
+
`${COINCIDE_LINE}: unowned ${report.unowned.status} — ${report.unowned.status === 'unavailable' ? report.unowned.reason : `${report.unowned.area_px} px, ${report.unowned.regions.length} regions`}`,
|
|
156
|
+
...report.unowned.regions.map(r => `${COINCIDE_LINE}: unowned box ${JSON.stringify(r.box)}, area ${r.area_px} px`)];
|
|
157
|
+
}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
/** Pre-rig pair domains and actual textured setup observations (#998). */
|
|
2
|
+
import { readFileSync } from 'node:fs';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { figureSilhouette, paintedFigure, sourceInRig } from './assemble.ts';
|
|
5
|
+
import { officialRenderer, sourceSizeProblem, type CheckInputs } from './check.ts';
|
|
6
|
+
import { supportReport, unownedSupport, SUPPORT_GRID_CODE, type SupportPart, type SupportReport } from './coincide.ts';
|
|
7
|
+
import { refuseIfAny } from './errors.ts';
|
|
8
|
+
import { readPng } from './raster/png.ts';
|
|
9
|
+
import { assertBinary, newRaster, type Mask, type Raster } from './raster/types.ts';
|
|
10
|
+
import { readSupportDomains } from './supportdomains.ts';
|
|
11
|
+
|
|
12
|
+
/** The setup candidate is already built by check. Only alpha callbacks are
|
|
13
|
+
* sampled here; no additional rigc build/render or renderFrame is run. */
|
|
14
|
+
export function observeSupport(build: string, input: CheckInputs, supportSource?: string, nativeFigure?: Mask): SupportReport {
|
|
15
|
+
const width = input.stage.width, height = input.stage.height;
|
|
16
|
+
if (!Number.isSafeInteger(width) || !Number.isSafeInteger(height) || width <= 0 || height <= 0 ||
|
|
17
|
+
(input.parts !== null && (input.parts.rig_size[0] !== width || input.parts.rig_size[1] !== height))) refuseIfAny([{ code: SUPPORT_GRID_CODE, object: 'support native canvas', detail: `stage ${width}x${height} must match the positive integer parts.json grid ${JSON.stringify(input.parts?.rig_size)}` }]);
|
|
18
|
+
const ordered = input.parts === null ? [] : [...input.parts.parts];
|
|
19
|
+
const slots = new Map((Array.isArray(input.rig.slots) ? input.rig.slots : []).flatMap((s, i) =>
|
|
20
|
+
typeof s === 'object' && s !== null && 'name' in s && typeof s.name === 'string' ? [[s.name, i] as const] : []));
|
|
21
|
+
for (const part of ordered) if (!slots.has(part.name)) refuseIfAny([{ code: 'CHECK_PART_SLOT_PRESENT', object: `part "${part.name}"`, detail: 'support report requires the named setup slot; no draw order is guessed' }]);
|
|
22
|
+
ordered.sort((a, b) => slots.get(a.name)! - slots.get(b.name)!);
|
|
23
|
+
const art = ordered.map<SupportPart>(part => {
|
|
24
|
+
const image = readPng(join(input.partsDir, `${part.name}.png`));
|
|
25
|
+
if (image.width !== part.w || image.height !== part.h) refuseIfAny([{ code: SUPPORT_GRID_CODE, object: `part "${part.name}"`, detail: `PNG is ${image.width}x${image.height}; parts.json requires ${part.w}x${part.h}` }]);
|
|
26
|
+
const mask: Mask = { width, height, data: new Uint8Array(width * height) };
|
|
27
|
+
for (let y = 0; y < image.height; y++) for (let x = 0; x < image.width; x++) {
|
|
28
|
+
const u = part.x + x, v = part.y + y;
|
|
29
|
+
if (u >= 0 && v >= 0 && u < width && v < height && image.data[(y * image.width + x) * 4 + 3] >= 128) mask.data[v * width + u] = 1;
|
|
30
|
+
}
|
|
31
|
+
return { name: part.name, mask };
|
|
32
|
+
});
|
|
33
|
+
const domains = input.parts === null ? [] : readSupportDomains(input.partsPath, input.partsDir, input.parts);
|
|
34
|
+
const report = supportReport(width, height, art, domains, null);
|
|
35
|
+
report.pair_registration = 'pre-rig parts.json placements, setup slot order';
|
|
36
|
+
report.unowned_registration = 'official renderer setup, native stage grid';
|
|
37
|
+
const api = officialRenderer(), skeleton = join(build, 'skeleton.json'), atlas = join(build, 'skeleton.atlas');
|
|
38
|
+
const candidate = api.loadCandidate({ skeletonText: readFileSync(skeleton, 'utf8'), atlasText: readFileSync(atlas, 'utf8'), atlasDir: build, label: 'part support report' }, { skeleton, atlas }, undefined);
|
|
39
|
+
const pose = api.throughPoser(candidate.choice, p => api.sampleSetupPose(p, { geometry: true, texture: true })).value[0];
|
|
40
|
+
if (pose === undefined || pose.pieces.some(p => 'source' in p)) {
|
|
41
|
+
report.unowned.reason = 'actual setup textured pieces are unavailable or clipped';
|
|
42
|
+
return report;
|
|
43
|
+
}
|
|
44
|
+
const viewport = { minX: input.stage.x, minY: input.stage.y, maxX: input.stage.x + width, maxY: input.stage.y + height, scale: 1, width, height };
|
|
45
|
+
const project = api.projector(viewport), union: Mask = { width, height, data: new Uint8Array(width * height) };
|
|
46
|
+
for (const piece of pose.pieces) api.rasterisePiece(api.pageFor(candidate.pages, piece), piece, project, viewport,
|
|
47
|
+
(x, y, _r, _g, _b, a) => { if (a >= 128) union.data[y * width + x] = 1; });
|
|
48
|
+
if (nativeFigure !== undefined && (nativeFigure.width !== width || nativeFigure.height !== height || nativeFigure.data.length !== width * height)) refuseIfAny([{ code: SUPPORT_GRID_CODE, object: 'transient support figure', detail: `requires ${width}x${height} native cells` }]);
|
|
49
|
+
if (nativeFigure !== undefined) assertBinary('transient support figure', nativeFigure);
|
|
50
|
+
const source = nativeFigure !== undefined ? null : input.source?.painting ?? (supportSource === undefined ? null : readPng(supportSource));
|
|
51
|
+
let figure: Mask | null = nativeFigure ?? null;
|
|
52
|
+
if (source !== null) {
|
|
53
|
+
const mismatch = sourceSizeProblem(source.width, source.height, input.stage, input.parts?.scale_rig_per_source ?? null);
|
|
54
|
+
if (mismatch !== null) refuseIfAny([{ code: SUPPORT_GRID_CODE, object: 'support painting', detail: mismatch }]);
|
|
55
|
+
figure = supportFigure(source, width, height);
|
|
56
|
+
}
|
|
57
|
+
report.unowned = unownedSupport(width, height, [{ name: 'setup union', mask: union }], figure);
|
|
58
|
+
report.status = report.pairs.some(p => (p.boundary_length_px ?? 0) > 0) || (report.unowned.area_px ?? 0) > 0 ? 'WARN' : report.coverage.measured > 0 ? 'REPORTED' : 'UNCLASSIFIED';
|
|
59
|
+
return report;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Reuse assembly's rig-sized painting only when its alpha is fully opaque.
|
|
63
|
+
* Transparent inputs retain source-over-white before the Lanczos resize. */
|
|
64
|
+
export function supportFigure(source: Raster, width: number, height: number, opaquePainting?: Raster): Mask {
|
|
65
|
+
let painting = opaquePainting;
|
|
66
|
+
for (let p = 3; painting !== undefined && p < source.data.length; p += 4) if (source.data[p] !== 255) painting = undefined;
|
|
67
|
+
if (painting === undefined) {
|
|
68
|
+
const white = newRaster(source.width, source.height);
|
|
69
|
+
for (let p = 0; p < source.width * source.height; p++) {
|
|
70
|
+
const alpha = source.data[p * 4 + 3] / 255;
|
|
71
|
+
for (let c = 0; c < 3; c++) white.data[p * 4 + c] = Math.round(source.data[p * 4 + c] * alpha + 255 * (1 - alpha));
|
|
72
|
+
white.data[p * 4 + 3] = 255;
|
|
73
|
+
}
|
|
74
|
+
painting = sourceInRig(white, width, height);
|
|
75
|
+
}
|
|
76
|
+
const painted = paintedFigure(painting), figure = figureSilhouette(painting, painted);
|
|
77
|
+
for (let p = 0; p < painted.length; p++) figure.data[p] &= painted[p];
|
|
78
|
+
return figure;
|
|
79
|
+
}
|
package/src/config.ts
CHANGED
|
@@ -1434,6 +1434,41 @@ const DOORS = 'a project\'s own record goes under a key beginning "x-" (any JSON
|
|
|
1434
1434
|
|
|
1435
1435
|
type Json = unknown;
|
|
1436
1436
|
|
|
1437
|
+
/** The loader's config-relative file fields, also used when relocating a config. */
|
|
1438
|
+
const CONFIG_FILE_FIELDS = {
|
|
1439
|
+
requirements: { path: ['requirements'], isFile: (_value: string) => true },
|
|
1440
|
+
animations: { path: ['motion', 'animations_from'], isFile: (_value: string) => true },
|
|
1441
|
+
skeleton: { path: ['generation', 'control', 'skeleton'], isFile: (value: string) => !isSkeletonName(value) },
|
|
1442
|
+
} as const;
|
|
1443
|
+
|
|
1444
|
+
function configFilePath(field: keyof typeof CONFIG_FILE_FIELDS, base: string, value: string): string | null {
|
|
1445
|
+
return CONFIG_FILE_FIELDS[field].isFile(value) ? resolve(base, value) : null;
|
|
1446
|
+
}
|
|
1447
|
+
|
|
1448
|
+
/** A file reference in a parsed config and its setter, excluding built-in names. */
|
|
1449
|
+
export interface ConfigFileReference {
|
|
1450
|
+
at: string;
|
|
1451
|
+
value: string;
|
|
1452
|
+
set: (value: string) => void;
|
|
1453
|
+
}
|
|
1454
|
+
|
|
1455
|
+
/** Enumerate the same file fields that the loader resolves, preserving invalid fields for its diagnostics. */
|
|
1456
|
+
export function configFileReferences(raw: unknown): ConfigFileReference[] {
|
|
1457
|
+
const out: ConfigFileReference[] = [];
|
|
1458
|
+
for (const field of Object.values(CONFIG_FILE_FIELDS)) {
|
|
1459
|
+
let parent = raw;
|
|
1460
|
+
for (const key of field.path.slice(0, -1)) parent = isPlainObject(parent) ? parent[key] : undefined;
|
|
1461
|
+
const key = field.path[field.path.length - 1];
|
|
1462
|
+
if (!isPlainObject(parent)) continue;
|
|
1463
|
+
const value = parent[key];
|
|
1464
|
+
if (typeof value !== 'string' || value === '' || !field.isFile(value)) continue;
|
|
1465
|
+
const target = parent;
|
|
1466
|
+
out.push({ at: field.path.join('.'), value, set: (next) => { target[key] = next; } });
|
|
1467
|
+
}
|
|
1468
|
+
return out;
|
|
1469
|
+
}
|
|
1470
|
+
|
|
1471
|
+
|
|
1437
1472
|
class Check {
|
|
1438
1473
|
readonly problems: Problem[] = [];
|
|
1439
1474
|
|
|
@@ -1836,10 +1871,12 @@ export function cloneConfig<T extends object>(cfg: T): T {
|
|
|
1836
1871
|
function poseBeside(c: Check, gen: Json, base: string): ControlPose | null {
|
|
1837
1872
|
if (!isPlainObject(gen) || !isPlainObject(gen.control)) return null;
|
|
1838
1873
|
const skel = gen.control.skeleton;
|
|
1839
|
-
if (typeof skel !== 'string' || skel === ''
|
|
1874
|
+
if (typeof skel !== 'string' || skel === '') return null;
|
|
1875
|
+
const file = configFilePath('skeleton', base, skel);
|
|
1876
|
+
if (file === null) return null;
|
|
1840
1877
|
const l = gen.latent;
|
|
1841
1878
|
const latent = Array.isArray(l) && l.length === 2 && l.every((n) => typeof n === 'number' && Number.isInteger(n) && n > 0) ? ([l[0], l[1]] as [number, number]) : null;
|
|
1842
|
-
return readControlPose(c,
|
|
1879
|
+
return readControlPose(c, file, latent);
|
|
1843
1880
|
}
|
|
1844
1881
|
|
|
1845
1882
|
/**
|
|
@@ -1992,7 +2029,7 @@ function parseConfigFrom(raw: Json, base: string | null): { config: CharacterCon
|
|
|
1992
2029
|
if ('turn' in t) checkTurn(c, t.turn, attached, names.bones, hasAltFace, parts, declaredSliders, meshParts, t.meshes, names.chains, names.parents);
|
|
1993
2030
|
if ('scene' in t) checkScene(c, t.scene);
|
|
1994
2031
|
if ('cloth' in t) checkCloth(c, t.cloth);
|
|
1995
|
-
if ('requirements' in t && c.string('config.requirements', t.requirements) && base !== null) checkRequirementsFile(c,
|
|
2032
|
+
if ('requirements' in t && c.string('config.requirements', t.requirements) && base !== null) checkRequirementsFile(c, configFilePath('requirements', base, t.requirements) as string);
|
|
1996
2033
|
const from = isPlainObject(t.motion) ? t.motion.animations_from : undefined;
|
|
1997
2034
|
const animations = base !== null && typeof from === 'string' && from !== '' ? readAnimationsFrom(c, base, from) : null;
|
|
1998
2035
|
if (animations !== null) {
|
|
@@ -2074,7 +2111,7 @@ function checkRequirementsFile(c: Check, file: string): void {
|
|
|
2074
2111
|
*/
|
|
2075
2112
|
function readAnimationsFrom(c: Check, base: string, from: string): AnimationsFrom | null {
|
|
2076
2113
|
const field = 'config.motion.animations_from';
|
|
2077
|
-
const file =
|
|
2114
|
+
const file = configFilePath('animations', base, from) as string;
|
|
2078
2115
|
const form = `{"spec": "${ANIMATIONS_FROM_SPEC}", "animations": {"<name>": {"duration": …, "tracks": [...]}}}`;
|
|
2079
2116
|
const shape = `a file in rig-c's motion-spec shape, ${form}, its path relative to the config's directory`;
|
|
2080
2117
|
const where = `names ${JSON.stringify(from)}, resolved against the config's directory ${base} (not the working directory) to ${file}`;
|
|
@@ -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
|
+
}
|