@rig-c/parts 2.37.0 → 2.38.1
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/docs/AUTHORING.md +126 -8
- package/docs/STABILITY.md +139 -4
- package/package.json +1 -1
- package/src/assemble.ts +33 -6
- package/src/build.ts +29 -12
- package/src/config.ts +92 -12
- package/src/depthworkflow.ts +4 -7
- package/src/editedparts.ts +168 -0
- package/src/meshdraft.ts +8 -4
- package/src/painting-reference.ts +210 -0
- package/src/parts.ts +35 -5
- package/src/provenance.ts +5 -0
package/src/config.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { EditedParts } from './editedparts.ts';
|
|
1
2
|
import { hiddenExtentNameProblems, type HiddenExtentDeclaration } from './hiddenextent.ts';
|
|
2
3
|
import { occluderFileProblems, occluderNameProblems, type OccluderDeclaration } from './occluders.ts';
|
|
3
4
|
import { SEAM_RULES, type SeamRule } from './seamrule.ts';
|
|
@@ -94,7 +95,7 @@ import type { DepthConfig } from './depthsheets.ts';
|
|
|
94
95
|
* the field is a non-empty string.
|
|
95
96
|
*/
|
|
96
97
|
import { existsSync, readFileSync, statSync } from 'node:fs';
|
|
97
|
-
import { dirname, relative, resolve } from 'node:path';
|
|
98
|
+
import { dirname, isAbsolute, posix, relative, resolve } from 'node:path';
|
|
98
99
|
import { RIG_BONE_INHERIT, RIG_SKIN_CONSTRAINT_KEYS, type RigBoneInherit, type RigConstraint, type RigSkinConstraintKey, type RigStop } from '@rig-c/core/rig';
|
|
99
100
|
import { pyRound } from './round.ts';
|
|
100
101
|
import { motionSeamProblems, type MotionSeamDeclaration } from './motionseams.ts';
|
|
@@ -331,6 +332,8 @@ export interface Assemble {
|
|
|
331
332
|
take?: TakeDeclaration[];
|
|
332
333
|
/** Issue #946: receipts for images edited in an image editor; absent, no file is read and no byte moves. */
|
|
333
334
|
editor_receipts?: EditorReceipts;
|
|
335
|
+
/** Whole-file rig-space edits; config-relative directory, directory-relative files. */
|
|
336
|
+
edited_parts?: EditedParts;
|
|
334
337
|
/** Rig pixels per source pixel. */
|
|
335
338
|
rig_scale: number;
|
|
336
339
|
plan: PlanEntry[];
|
|
@@ -1478,7 +1481,30 @@ export interface ConfigFileReference {
|
|
|
1478
1481
|
set: (value: string) => void;
|
|
1479
1482
|
}
|
|
1480
1483
|
|
|
1481
|
-
/**
|
|
1484
|
+
/** Normalized POSIX segments; neither operand is resolved against the cwd. */
|
|
1485
|
+
function editedPathSegments(path: string): string[] {
|
|
1486
|
+
return posix.normalize(path).split('/').filter(p => p !== '' && p !== '.');
|
|
1487
|
+
}
|
|
1488
|
+
|
|
1489
|
+
function editedPathPrefix(from: readonly string[], to: readonly string[]): number {
|
|
1490
|
+
let common = 0;
|
|
1491
|
+
while (common < from.length && common < to.length && from[common] === to[common]) common++;
|
|
1492
|
+
return common;
|
|
1493
|
+
}
|
|
1494
|
+
|
|
1495
|
+
/** Same absolute forms the relative-only loader refuses, including Windows forms. */
|
|
1496
|
+
function editedPathAbsolute(path: string): boolean {
|
|
1497
|
+
return isAbsolute(path) || /^(?:[\\/]|[A-Za-z]:[\\/])/.test(path);
|
|
1498
|
+
}
|
|
1499
|
+
|
|
1500
|
+
/** Relative segments for a target representable under dir, including rebased siblings. */
|
|
1501
|
+
function relativeEditedFile(dir: string, next: string): string {
|
|
1502
|
+
const from = editedPathSegments(dir), to = editedPathSegments(next);
|
|
1503
|
+
const common = editedPathPrefix(from, to);
|
|
1504
|
+
return [...from.slice(common).map(() => '..'), ...to.slice(common)].join('/');
|
|
1505
|
+
}
|
|
1506
|
+
|
|
1507
|
+
/** Enumerate loader and assemble file references, preserving invalid fields for their diagnostics. */
|
|
1482
1508
|
export function configFileReferences(raw: unknown): ConfigFileReference[] {
|
|
1483
1509
|
const out: ConfigFileReference[] = [];
|
|
1484
1510
|
for (const field of Object.values(CONFIG_FILE_FIELDS)) {
|
|
@@ -1503,6 +1529,36 @@ export function configFileReferences(raw: unknown): ConfigFileReference[] {
|
|
|
1503
1529
|
out.push({ at: `assemble.occluders[${i}].plate`, value: entry.plate, set: (next) => { entry.plate = next; } });
|
|
1504
1530
|
}
|
|
1505
1531
|
});
|
|
1532
|
+
// Issue #1281: receipt files cover this directory without declaring a directory input.
|
|
1533
|
+
const edited = isPlainObject(assemble) ? assemble.edited_parts : undefined;
|
|
1534
|
+
if (isPlainObject(edited) && typeof edited.dir === 'string' && edited.dir !== '' && Array.isArray(edited.receipts)) {
|
|
1535
|
+
const enumerationDir = edited.dir, receipts = edited.receipts;
|
|
1536
|
+
receipts.forEach((entry: unknown, i: number) => {
|
|
1537
|
+
if (!isPlainObject(entry) || typeof entry.file !== 'string' || entry.file === '') return;
|
|
1538
|
+
out.push({ at: `assemble.edited_parts.receipts[${i}].file`, value: posix.join(enumerationDir, entry.file), set: (next) => {
|
|
1539
|
+
// Preserve invalid absolute targets for the existing relative-only loader refusal.
|
|
1540
|
+
if (editedPathAbsolute(next)) { entry.file = next; return; }
|
|
1541
|
+
// A previous setter from this enumeration may have rebased the shared dir.
|
|
1542
|
+
const liveDir = edited.dir;
|
|
1543
|
+
if (typeof liveDir !== 'string' || liveDir.trim() === '' || editedPathAbsolute(liveDir)) {
|
|
1544
|
+
entry.file = next;
|
|
1545
|
+
return; // Do not repair invalid dirs or hide their existing loader diagnostics.
|
|
1546
|
+
}
|
|
1547
|
+
let dir: string = liveDir;
|
|
1548
|
+
const from = editedPathSegments(dir), to = editedPathSegments(next);
|
|
1549
|
+
if (from.filter(p => p === '..').length > to.filter(p => p === '..').length) {
|
|
1550
|
+
const rebased = from.slice(0, editedPathPrefix(from, to)).join('/') || '.';
|
|
1551
|
+
for (const sibling of receipts) {
|
|
1552
|
+
if (!isPlainObject(sibling) || typeof sibling.file !== 'string' || sibling.file.trim() === '' || editedPathAbsolute(sibling.file)) continue;
|
|
1553
|
+
sibling.file = relativeEditedFile(rebased, posix.join(dir, sibling.file));
|
|
1554
|
+
}
|
|
1555
|
+
edited.dir = rebased;
|
|
1556
|
+
dir = rebased;
|
|
1557
|
+
}
|
|
1558
|
+
entry.file = relativeEditedFile(dir, next);
|
|
1559
|
+
} });
|
|
1560
|
+
});
|
|
1561
|
+
}
|
|
1506
1562
|
return out;
|
|
1507
1563
|
}
|
|
1508
1564
|
|
|
@@ -1729,7 +1785,7 @@ export interface EarlyConfig {
|
|
|
1729
1785
|
depth?: DepthConfig;
|
|
1730
1786
|
key: string;
|
|
1731
1787
|
seethrough: SeeThrough;
|
|
1732
|
-
assemble: { rig_scale: number; seam?: SeamRule; project?: ProjectRule; ground?: Ground; take?: TakeDeclaration[]; editor_receipts?: EditorReceipts; head_face_underfill?: boolean; yield_refused?: boolean; stage_map?: boolean; keep_under_occluders?: string[]; require_hidden_extent?: HiddenExtentDeclaration[]; extend_painting?: PaintingExtension[]; occluders?: OccluderDeclaration[]; edge_splits?: EdgeSplit[] };
|
|
1788
|
+
assemble: { rig_scale: number; seam?: SeamRule; project?: ProjectRule; ground?: Ground; take?: TakeDeclaration[]; editor_receipts?: EditorReceipts; edited_parts?: EditedParts; head_face_underfill?: boolean; yield_refused?: boolean; stage_map?: boolean; keep_under_occluders?: string[]; require_hidden_extent?: HiddenExtentDeclaration[]; extend_painting?: PaintingExtension[]; occluders?: OccluderDeclaration[]; edge_splits?: EdgeSplit[] };
|
|
1733
1789
|
}
|
|
1734
1790
|
|
|
1735
1791
|
/** What plain `assemble` reads: the early config plus the plan `--propose-plan` printed. */
|
|
@@ -1807,7 +1863,7 @@ function parseEarlyConfigFrom(raw: Json, door: EarlyDoor, base: string | null, p
|
|
|
1807
1863
|
if (door === 'layers') {
|
|
1808
1864
|
if ('seethrough' in t) checkSeeThrough(c, t.seethrough);
|
|
1809
1865
|
if ('assemble' in t) {
|
|
1810
|
-
const a = c.object('config.assemble', t.assemble, sectionRequired(door, 'assemble'), ['plan', 'extend_below_crop', 'patches', 'cuts', 'alternates', 'head_face_underfill', 'yield_refused', 'stage_map', 'keep_under_occluders', 'require_hidden_extent', 'extend_painting', 'edge_splits', 'take', 'seam', 'project', 'ground', 'editor_receipts', 'occluders']);
|
|
1866
|
+
const a = c.object('config.assemble', t.assemble, sectionRequired(door, 'assemble'), ['plan', 'extend_below_crop', 'patches', 'cuts', 'alternates', 'head_face_underfill', 'yield_refused', 'stage_map', 'keep_under_occluders', 'require_hidden_extent', 'extend_painting', 'edge_splits', 'take', 'seam', 'project', 'ground', 'editor_receipts', 'edited_parts', 'occluders']);
|
|
1811
1867
|
if (a !== null) {
|
|
1812
1868
|
checkAssembleRules(c, a);
|
|
1813
1869
|
if ('rig_scale' in a) c.number('config.assemble.rig_scale', a.rig_scale, 'positive');
|
|
@@ -1824,6 +1880,7 @@ function parseEarlyConfigFrom(raw: Json, door: EarlyDoor, base: string | null, p
|
|
|
1824
1880
|
if ('edge_splits' in a) checkEdgeSplits(c, a.edge_splits, Array.isArray(a.plan) ? new Set(a.plan.filter((r): r is Json[] => Array.isArray(r) && typeof r[0] === 'string').map(r => r[0] as string)) : null);
|
|
1825
1881
|
if ('take' in a) checkTakeLayers(c, a.take, null, a);
|
|
1826
1882
|
if ('editor_receipts' in a) checkEditorReceipts(c, a.editor_receipts);
|
|
1883
|
+
if ('edited_parts' in a) checkEditedParts(c, a.edited_parts, a.plan);
|
|
1827
1884
|
if ('yield_refused' in a && typeof a.yield_refused !== 'boolean') {
|
|
1828
1885
|
c.fail('CONFIG_FIELD_TYPE', 'config.assemble.yield_refused', `is ${show(a.yield_refused)}; true or false is required`);
|
|
1829
1886
|
}
|
|
@@ -2770,13 +2827,35 @@ export function editorReceiptProblems(value: unknown, at: string): Problem[] {
|
|
|
2770
2827
|
return c.problems;
|
|
2771
2828
|
}
|
|
2772
2829
|
|
|
2773
|
-
/**
|
|
2774
|
-
|
|
2775
|
-
|
|
2776
|
-
|
|
2777
|
-
|
|
2778
|
-
|
|
2779
|
-
|
|
2830
|
+
/** Whole-file rig-space receipts; file/baseline verification is at assemble. */
|
|
2831
|
+
function checkEditedParts(c: Check, value: Json, plan: Json | undefined): void {
|
|
2832
|
+
const at = 'config.assemble.edited_parts';
|
|
2833
|
+
const absolute = (path: string): boolean => isAbsolute(path) || /^(?:[\\/]|[A-Za-z]:[\\/])/.test(path);
|
|
2834
|
+
const o = c.object(at, value, ['dir', 'receipts'], []);
|
|
2835
|
+
if (o === null) return;
|
|
2836
|
+
if (typeof o.dir === 'string' && o.dir.trim().length === 0 && o.dir !== '') c.fail('CONFIG_FIELD_TYPE', at + '.dir', 'is blank; a non-empty directory is required');
|
|
2837
|
+
if ('dir' in o && c.string(at + '.dir', o.dir) && absolute(o.dir as string)) c.fail('CONFIG_FIELD_TYPE', at + '.dir', 'is absolute; a directory relative to the config is required');
|
|
2838
|
+
if (!('receipts' in o) || !c.array(at + '.receipts', o.receipts, false)) return;
|
|
2839
|
+
const names = Array.isArray(plan) ? new Set(plan.filter((r): r is Json[] => Array.isArray(r) && typeof r[0] === 'string').map(r => r[0] as string)) : null;
|
|
2840
|
+
const seen = new Map<string, number>();
|
|
2841
|
+
(o.receipts as Json[]).forEach((value, i) => {
|
|
2842
|
+
const p = at + '.receipts[' + i + ']';
|
|
2843
|
+
const r = c.object(p, value, ['part', 'file', 'sha256', 'from_sha256', 'editor'], []);
|
|
2844
|
+
if (r === null) return;
|
|
2845
|
+
if ('part' in r && c.string(p + '.part', r.part)) {
|
|
2846
|
+
const part = r.part as string;
|
|
2847
|
+
if (seen.has(part)) c.fail('ASSEMBLE_EDITED_PART_DUPLICATE', p + '.part', `names "${part}" again (first at receipts[${seen.get(part)}]); one receipt per part is required`);
|
|
2848
|
+
else seen.set(part, i);
|
|
2849
|
+
if (names !== null && !names.has(part)) c.fail('ASSEMBLE_EDITED_PART_UNKNOWN', p + '.part', `names "${part}"; an existing assemble.plan part is required`);
|
|
2850
|
+
}
|
|
2851
|
+
if ('file' in r && c.string(p + '.file', r.file) && absolute(r.file as string)) c.fail('CONFIG_FIELD_TYPE', p + '.file', 'is absolute; a PNG path relative to edited_parts.dir is required');
|
|
2852
|
+
if ('editor' in r) c.string(p + '.editor', r.editor);
|
|
2853
|
+
for (const key of ['part', 'file', 'editor'] as const) if (typeof r[key] === 'string' && (r[key] as string).trim().length === 0 && r[key] !== '') c.fail('CONFIG_FIELD_TYPE', p + '.' + key, 'is blank; a non-empty value is required');
|
|
2854
|
+
for (const key of ['sha256', 'from_sha256'] as const) if (key in r && (typeof r[key] !== 'string' || !SHA256_PATTERN.test(r[key] as string))) c.fail('CONFIG_FIELD_TYPE', p + '.' + key, `is ${show(r[key])}; ${SHA256_RULE} is required`);
|
|
2855
|
+
});
|
|
2856
|
+
}
|
|
2857
|
+
|
|
2858
|
+
/** Existing source-image receipts keep their own config-relative file contract. */
|
|
2780
2859
|
function checkEditorReceipts(c: Check, value: Json, at = 'config.assemble.editor_receipts'): void {
|
|
2781
2860
|
const o = c.object(at, value, ['receipts'], ['required', 'trace_parts']);
|
|
2782
2861
|
if (o === null) return;
|
|
@@ -2816,7 +2895,7 @@ function checkAssembleRules(c: Check, a: Record<string, Json>): void {
|
|
|
2816
2895
|
|
|
2817
2896
|
function checkAssemble(c: Check, v: Json, door: 'assemble' | 'full'): { parts: string[]; patches: string[]; cuts: string[] } {
|
|
2818
2897
|
const required = sectionRequired(door, 'assemble');
|
|
2819
|
-
const a = c.object('config.assemble', v, required.filter((k) => k !== 'plan'), ['plan', 'extend_below_crop', 'patches', 'cuts', 'alternates', 'head_face_underfill', 'yield_refused', 'stage_map', 'keep_under_occluders', 'require_hidden_extent', 'extend_painting', 'edge_splits', 'take', 'seam', 'project', 'ground', 'editor_receipts', 'occluders']);
|
|
2898
|
+
const a = c.object('config.assemble', v, required.filter((k) => k !== 'plan'), ['plan', 'extend_below_crop', 'patches', 'cuts', 'alternates', 'head_face_underfill', 'yield_refused', 'stage_map', 'keep_under_occluders', 'require_hidden_extent', 'extend_painting', 'edge_splits', 'take', 'seam', 'project', 'ground', 'editor_receipts', 'edited_parts', 'occluders']);
|
|
2820
2899
|
if (a === null) return { parts: [], patches: [], cuts: [] };
|
|
2821
2900
|
checkAssembleRules(c, a);
|
|
2822
2901
|
if (required.includes('plan') && !('plan' in a)) {
|
|
@@ -2861,6 +2940,7 @@ function checkAssemble(c: Check, v: Json, door: 'assemble' | 'full'): { parts: s
|
|
|
2861
2940
|
if ('edge_splits' in a) checkEdgeSplits(c, a.edge_splits, new Set(parts));
|
|
2862
2941
|
if ('take' in a) checkTakeLayers(c, a.take, parts, a);
|
|
2863
2942
|
if ('editor_receipts' in a) checkEditorReceipts(c, a.editor_receipts);
|
|
2943
|
+
if ('edited_parts' in a) checkEditedParts(c, a.edited_parts, a.plan);
|
|
2864
2944
|
if ('extend_below_crop' in a && c.array(`${p}.extend_below_crop`, a.extend_below_crop, false)) {
|
|
2865
2945
|
(a.extend_below_crop as Json[]).forEach((entry, i) => {
|
|
2866
2946
|
const at = `${p}.extend_below_crop[${i}]`;
|
package/src/depthworkflow.ts
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
import { createHash } from 'node:crypto';
|
|
6
6
|
import { existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, statSync, writeFileSync } from 'node:fs';
|
|
7
7
|
import { basename, dirname, join, relative, resolve, sep } from 'node:path';
|
|
8
|
-
import { loadConfigAndAnimations, parseConfig } from './config.ts';
|
|
8
|
+
import { configFileReferences, loadConfigAndAnimations, parseConfig } from './config.ts';
|
|
9
9
|
import { depthReading, readSourceDepth } from './depthsheets.ts';
|
|
10
10
|
import { alphaSupport, depthMapFail as fail, floatBox, integrateNormals, mapToSheet, readNumericMap, type NumericMap } from './depthmaps.ts';
|
|
11
11
|
import { depthImageReference, partImageReference, readParts } from './parts.ts';
|
|
@@ -13,7 +13,6 @@ import { readPartSet } from './propose.ts';
|
|
|
13
13
|
import { decodePngBytes, encodePngBytes } from './raster/png.ts';
|
|
14
14
|
import { resize } from './raster/resize.ts';
|
|
15
15
|
import { connectedComponents } from './raster/components.ts';
|
|
16
|
-
import { isSkeletonName } from './skeleton.ts';
|
|
17
16
|
import { newRaster, type Raster } from './raster/types.ts';
|
|
18
17
|
|
|
19
18
|
type Obj = Record<string, unknown>;
|
|
@@ -165,11 +164,9 @@ export function applyDepth(input: { parts: string; manifest: string; config: str
|
|
|
165
164
|
if (group.unitDepths !== undefined) target.unitDepths = group.unitDepths;
|
|
166
165
|
}
|
|
167
166
|
// Keep relative paths portable when relocating the output directory with its inputs.
|
|
168
|
-
const
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
if (typeof control?.skeleton === 'string' && !isSkeletonName(control.skeleton)) control.skeleton = relative(resolve(input.out), resolve(dirname(input.rigConfig), control.skeleton));
|
|
172
|
-
if (typeof raw.requirements === 'string') raw.requirements = relative(resolve(input.out), resolve(dirname(input.rigConfig), raw.requirements));
|
|
167
|
+
for (const ref of configFileReferences(raw)) {
|
|
168
|
+
ref.set(relative(resolve(input.out), resolve(dirname(input.rigConfig), ref.value)));
|
|
169
|
+
}
|
|
173
170
|
parseConfig(raw);
|
|
174
171
|
const writes = new Map<string, Uint8Array>(), rows: Obj[] = [], recs = rawParts.parts as Obj[];
|
|
175
172
|
// Retain auxiliary art (including alternate sets) and diagnostics byte-for-byte.
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
/** Rig-space whole-file replacements, applied after the last normal raster pass. */
|
|
2
|
+
import { createHash } from 'node:crypto';
|
|
3
|
+
import { readFileSync } from 'node:fs';
|
|
4
|
+
import { dirname, resolve } from 'node:path';
|
|
5
|
+
import type { EditorReceipt } from './editreceipt.ts';
|
|
6
|
+
import { refuseIfAny, type Problem } from './errors.ts';
|
|
7
|
+
import { OPAQUE_ALPHA_ABOVE } from './layers.ts';
|
|
8
|
+
import { AUTOMATIC_WRITERS, EXCLUDED_PIXEL, NOT_OVERRIDDEN_PIXEL, rgbaEqual, type AutomaticWriter, type PartStageMap, type PixelProvenance, type StageMap, type ValueBaseline } from './provenance.ts';
|
|
9
|
+
import { decodePngBytes, encodePngBytes } from './raster/png.ts';
|
|
10
|
+
import type { Mask, Raster } from './raster/types.ts';
|
|
11
|
+
import type { PlacedPart } from './assemble.ts';
|
|
12
|
+
import type { PartDepthReference } from './depthsheets.ts';
|
|
13
|
+
|
|
14
|
+
export interface EditedPartReceipt extends EditorReceipt { part: string }
|
|
15
|
+
export interface EditedParts { dir: string; receipts: EditedPartReceipt[] }
|
|
16
|
+
export interface VerifiedEditedPart {
|
|
17
|
+
index: number;
|
|
18
|
+
dir: string;
|
|
19
|
+
receipt: EditedPartReceipt;
|
|
20
|
+
bytes: Uint8Array;
|
|
21
|
+
image: Raster;
|
|
22
|
+
}
|
|
23
|
+
export interface EditedPartProvenance {
|
|
24
|
+
edit: string;
|
|
25
|
+
dir: string;
|
|
26
|
+
receipt: EditedPartReceipt;
|
|
27
|
+
changed_px: number;
|
|
28
|
+
changed_counted_px: number;
|
|
29
|
+
changed_excluded_px: number;
|
|
30
|
+
removed_opaque_px: number;
|
|
31
|
+
}
|
|
32
|
+
/** Only held for an edited build, including its region-take counterfactual. */
|
|
33
|
+
export interface EditedPartContext {
|
|
34
|
+
baseline: ValueBaseline | null;
|
|
35
|
+
visible?: Mask;
|
|
36
|
+
projected?: Mask;
|
|
37
|
+
paintingGain?: Mask;
|
|
38
|
+
/** Validate newly visible material against declared scalar sources. */
|
|
39
|
+
depthForEdit?: (image: Raster) => { reference: PartDepthReference; image: Raster; clampedSamples: number } | undefined;
|
|
40
|
+
depthClampedSamples?: number;
|
|
41
|
+
}
|
|
42
|
+
const AT = 'config.assemble.edited_parts';
|
|
43
|
+
const sha = (bytes: Uint8Array): string => createHash('sha256').update(bytes).digest('hex');
|
|
44
|
+
|
|
45
|
+
/** Read once: validation, decoding and final emission all use these exact bytes. */
|
|
46
|
+
export function readEditedParts(spec: EditedParts | undefined, configPath: string, plan: ReadonlyArray<readonly [string, string, string]>): VerifiedEditedPart[] {
|
|
47
|
+
if (spec === undefined) return [];
|
|
48
|
+
const out: VerifiedEditedPart[] = [], problems: Problem[] = [];
|
|
49
|
+
const names = new Set(plan.map(([name]) => name)), seen = new Set<string>();
|
|
50
|
+
for (const [index, receipt] of spec.receipts.entries()) {
|
|
51
|
+
const object = `${AT}.receipts[${index}] (part "${receipt.part}")`;
|
|
52
|
+
if (seen.has(receipt.part)) problems.push({ code: 'ASSEMBLE_EDITED_PART_DUPLICATE', object, detail: 'names the same part twice; one receipt per plan part is required' });
|
|
53
|
+
seen.add(receipt.part);
|
|
54
|
+
if (!names.has(receipt.part)) problems.push({ code: 'ASSEMBLE_EDITED_PART_UNKNOWN', object, detail: `names "${receipt.part}"; an existing assemble.plan part is required` });
|
|
55
|
+
const path = resolve(dirname(resolve(configPath)), spec.dir, receipt.file);
|
|
56
|
+
let bytes: Uint8Array;
|
|
57
|
+
try { bytes = new Uint8Array(readFileSync(path)); }
|
|
58
|
+
catch { problems.push({ code: 'ASSEMBLE_EDITED_PART_FILE', object, detail: `file "${receipt.file}" in dir "${spec.dir}" is not readable; a PNG relative to edited_parts.dir is required` }); continue; }
|
|
59
|
+
const found = sha(bytes);
|
|
60
|
+
if (found !== receipt.sha256) {
|
|
61
|
+
problems.push({ code: 'ASSEMBLE_EDITED_PART_SHA256', object, detail: `file sha256 is ${found}; receipt sha256 ${receipt.sha256} is required` });
|
|
62
|
+
continue;
|
|
63
|
+
}
|
|
64
|
+
try { out.push({ index, dir: spec.dir, receipt, bytes, image: decodePngBytes(bytes, receipt.file) }); }
|
|
65
|
+
catch (error) { problems.push({ code: 'ASSEMBLE_EDITED_PART_DECODES', object, detail: `file "${receipt.file}" is not a decodable PNG: ${(error as Error).message.split('\n')[0]}` }); }
|
|
66
|
+
}
|
|
67
|
+
refuseIfAny(problems);
|
|
68
|
+
return out;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function append(runs: Array<[number, number]>, id: number): void {
|
|
72
|
+
const last = runs[runs.length - 1];
|
|
73
|
+
if (last?.[0] === id) last[1]++;
|
|
74
|
+
else runs.push([id, 1]);
|
|
75
|
+
}
|
|
76
|
+
function reader(runs: ReadonlyArray<readonly [number, number]>): () => number {
|
|
77
|
+
let at = 0, used = 0;
|
|
78
|
+
return () => {
|
|
79
|
+
const [id, length] = runs[at];
|
|
80
|
+
if (++used === length) { at++; used = 0; }
|
|
81
|
+
return id;
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Validate every baseline before replacing any image. No output writes here. */
|
|
86
|
+
export function replaceEditedParts(placed: PlacedPart[], edits: readonly VerifiedEditedPart[], plan: ReadonlySet<string>, map: StageMap, contexts: ReadonlyMap<PlacedPart, EditedPartContext>): void {
|
|
87
|
+
const problems: Problem[] = [], seen = new Set<string>();
|
|
88
|
+
for (const edit of edits) {
|
|
89
|
+
const { receipt, image } = edit, part = placed.find(p => p.record.name === receipt.part);
|
|
90
|
+
const object = `${AT}.receipts[${edit.index}] (part "${receipt.part}")`;
|
|
91
|
+
if (seen.has(receipt.part)) problems.push({ code: 'ASSEMBLE_EDITED_PART_DUPLICATE', object, detail: 'names the same part twice; one receipt per plan part is required' });
|
|
92
|
+
seen.add(receipt.part);
|
|
93
|
+
if (!plan.has(receipt.part) || part === undefined) {
|
|
94
|
+
problems.push({ code: 'ASSEMBLE_EDITED_PART_UNKNOWN', object, detail: 'requires an existing plan part emitted under the same name; a part consumed by limb splitting is not a final plan part' });
|
|
95
|
+
continue;
|
|
96
|
+
}
|
|
97
|
+
const found = sha(encodePngBytes(part.image));
|
|
98
|
+
if (found !== receipt.from_sha256) problems.push({ code: 'ASSEMBLE_EDITED_PART_BASELINE', object, detail: `the current assembled PNG sha256 is ${found}; receipt from_sha256 ${receipt.from_sha256} is required` });
|
|
99
|
+
if (image.width !== part.record.w || image.height !== part.record.h) problems.push({ code: 'ASSEMBLE_EDITED_PART_SIZE', object, detail: `edited PNG is ${image.width}x${image.height}; assembled box ${part.record.w}x${part.record.h} is required` });
|
|
100
|
+
const actual = sha(edit.bytes);
|
|
101
|
+
if (actual !== receipt.sha256) problems.push({ code: 'ASSEMBLE_EDITED_PART_SHA256', object, detail: `edited bytes sha256 is ${actual}; receipt sha256 ${receipt.sha256} is required` });
|
|
102
|
+
}
|
|
103
|
+
refuseIfAny(problems);
|
|
104
|
+
for (const edit of edits) {
|
|
105
|
+
const part = placed.find(p => p.record.name === edit.receipt.part)!;
|
|
106
|
+
const old = part.image, record = part.record, context = contexts.get(part)!;
|
|
107
|
+
const stage = map.parts.find(p => p.name === record.name)!;
|
|
108
|
+
const previous = reader(stage.runs), preSeam = reader(stage.pre_seam_writer_runs);
|
|
109
|
+
const name = `edited_parts[${edit.index}]`;
|
|
110
|
+
let id = map.edits.indexOf(name) + 1;
|
|
111
|
+
if (id === 0) { map.edits.push(name); id = map.edits.length; }
|
|
112
|
+
const metadata: EditedPartProvenance = { edit: name, dir: edit.dir,
|
|
113
|
+
receipt: { part: edit.receipt.part, file: edit.receipt.file, sha256: edit.receipt.sha256, from_sha256: edit.receipt.from_sha256, editor: edit.receipt.editor },
|
|
114
|
+
changed_px: 0, changed_counted_px: 0, changed_excluded_px: 0, removed_opaque_px: 0 };
|
|
115
|
+
const next: PartStageMap = { name: stage.name, x: stage.x, y: stage.y, w: stage.w, h: stage.h,
|
|
116
|
+
excluded_px: 0, runs: [], pre_seam_writer_runs: [], edited_part: metadata };
|
|
117
|
+
const provenance: PixelProvenance = { unchanged_layer_px: 0, hand_px: 0, automatic_px: 0, edits: [], automatic: [],
|
|
118
|
+
...(record.provenance?.depth === undefined ? {} : { depth: record.provenance.depth }), edited_part: metadata };
|
|
119
|
+
const counts = new Map<number, number>();
|
|
120
|
+
let opaque = 0, visible = 0, projected = 0, paintingGain = 0;
|
|
121
|
+
const baseline = context.baseline;
|
|
122
|
+
for (let p = 0; p < old.width * old.height; p++) {
|
|
123
|
+
const offset = p * 4, prior = previous(), priorSeam = preSeam();
|
|
124
|
+
const changed = !rgbaEqual(old.data, offset, edit.image.data, offset);
|
|
125
|
+
const counted = edit.image.data[offset + 3] > OPAQUE_ALPHA_ABOVE;
|
|
126
|
+
if (changed) {
|
|
127
|
+
metadata.changed_px++;
|
|
128
|
+
if (counted) metadata.changed_counted_px++; else metadata.changed_excluded_px++;
|
|
129
|
+
}
|
|
130
|
+
if (old.data[offset + 3] > OPAQUE_ALPHA_ABOVE && !counted) metadata.removed_opaque_px++;
|
|
131
|
+
if (!counted) { next.excluded_px++; append(next.runs, EXCLUDED_PIXEL); append(next.pre_seam_writer_runs, EXCLUDED_PIXEL); continue; }
|
|
132
|
+
opaque++;
|
|
133
|
+
const x = record.x + p % record.w, y = record.y + Math.floor(p / record.w);
|
|
134
|
+
const q = y * map.rig_size[0] + x;
|
|
135
|
+
if (context.visible?.data[q] === 1) visible++;
|
|
136
|
+
if (context.visible?.data[q] === 1 && context.projected?.data[q] === 1) projected++;
|
|
137
|
+
if (context.paintingGain?.data[q] === 1) paintingGain++;
|
|
138
|
+
const u = x - (baseline?.x ?? 0), v = y - (baseline?.y ?? 0);
|
|
139
|
+
const sameRaw = baseline !== null && u >= 0 && v >= 0 && u < baseline.image.width && v < baseline.image.height &&
|
|
140
|
+
rgbaEqual(edit.image.data, offset, baseline.image.data, (v * baseline.image.width + u) * 4);
|
|
141
|
+
const writer = changed ? sameRaw ? 0 : id : prior;
|
|
142
|
+
append(next.runs, writer);
|
|
143
|
+
append(next.pre_seam_writer_runs, !changed && writer === AUTOMATIC_WRITERS.seamOverride ? priorSeam : NOT_OVERRIDDEN_PIXEL);
|
|
144
|
+
if (writer === 0) provenance.unchanged_layer_px++;
|
|
145
|
+
else if (writer > 0) provenance.hand_px++;
|
|
146
|
+
else provenance.automatic_px++;
|
|
147
|
+
counts.set(writer, (counts.get(writer) ?? 0) + 1);
|
|
148
|
+
}
|
|
149
|
+
provenance.edits = map.edits.flatMap((edit, i) => counts.has(i + 1) ? [{ edit, px: counts.get(i + 1)! }] : []);
|
|
150
|
+
provenance.automatic = (Object.keys(AUTOMATIC_WRITERS) as AutomaticWriter[]).flatMap(stage => counts.has(AUTOMATIC_WRITERS[stage]) ? [{ stage, px: counts.get(AUTOMATIC_WRITERS[stage])! }] : []);
|
|
151
|
+
record.opaque_px = opaque;
|
|
152
|
+
// Visibility/projection masks describe the normal source passes. Intersect
|
|
153
|
+
// them with final alpha; newly painted pixels outside those masks are occluded.
|
|
154
|
+
record.visible_px = visible; record.occluded_px = opaque - visible;
|
|
155
|
+
record.visible_not_projected_px = visible - projected;
|
|
156
|
+
if (record.painting_extension_px !== undefined) record.painting_extension_px = paintingGain;
|
|
157
|
+
record.provenance = provenance;
|
|
158
|
+
const scalar = context.depthForEdit?.(edit.image);
|
|
159
|
+
if (scalar !== undefined) {
|
|
160
|
+
record.depth = scalar.reference;
|
|
161
|
+
part.depthImage = scalar.image;
|
|
162
|
+
context.depthClampedSamples = scalar.clampedSamples;
|
|
163
|
+
}
|
|
164
|
+
part.image = edit.image;
|
|
165
|
+
part.encodedBytes = edit.bytes;
|
|
166
|
+
map.parts[map.parts.indexOf(stage)] = next;
|
|
167
|
+
}
|
|
168
|
+
}
|
package/src/meshdraft.ts
CHANGED
|
@@ -60,7 +60,7 @@
|
|
|
60
60
|
* but the process is injected, exactly as `src/check.ts` and `src/build.ts` take it.
|
|
61
61
|
*/
|
|
62
62
|
import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
|
63
|
-
import { dirname, isAbsolute, join, resolve } from 'node:path';
|
|
63
|
+
import { dirname, isAbsolute, join, relative, resolve } from 'node:path';
|
|
64
64
|
import type { AlphaMask, MeasureRow, MeshQualityReport, MotionSchedule } from '@rig-c/core/mesh';
|
|
65
65
|
import { compareMeshesInMotion, type MotionComparisonInput } from '@rig-c/core/meshcompare';
|
|
66
66
|
import { MeshReductionError } from '@rig-c/core/mesh';
|
|
@@ -728,13 +728,17 @@ export function relativeConfigPaths(_configDir: string, o: Json): RelativeConfig
|
|
|
728
728
|
|
|
729
729
|
/**
|
|
730
730
|
* A config the stage builds, written as `<dir>/config.json`: `text` (the author's config at `configPath`) with
|
|
731
|
-
* `meshes.<part>` replaced for every part in `meshes`, and each of its {@link relativeConfigPaths}
|
|
732
|
-
*
|
|
731
|
+
* `meshes.<part>` replaced for every part in `meshes`, and each of its {@link relativeConfigPaths} rebased to
|
|
732
|
+
* the file the author's config names. Edited receipt files stay relative to the destination config directory;
|
|
733
|
+
* other references become absolute. `remesh` (issue #495) builds through the same door.
|
|
733
734
|
*/
|
|
734
735
|
export function scratchConfig(configPath: string, text: string, dir: string, meshes: ReadonlyMap<string, unknown>): string {
|
|
735
736
|
const configDir = dirname(resolve(configPath));
|
|
736
737
|
const o = JSON.parse(text) as Json;
|
|
737
|
-
for (const r of relativeConfigPaths(configDir, o))
|
|
738
|
+
for (const r of relativeConfigPaths(configDir, o)) {
|
|
739
|
+
const target = resolve(configDir, r.value);
|
|
740
|
+
r.set(r.at.startsWith('assemble.edited_parts.receipts[') ? relative(resolve(dir), target).replaceAll('\\', '/') : target);
|
|
741
|
+
}
|
|
738
742
|
o.meshes = { ...(o.meshes as Json), ...Object.fromEntries(meshes) };
|
|
739
743
|
mkdirSync(dir, { recursive: true });
|
|
740
744
|
writeFileSync(join(dir, 'config.json'), `${JSON.stringify(o, null, 2)}\n`);
|
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
/** A source-bound painting reference for an existing, immutable parts manifest. */
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import { createHash } from 'node:crypto';
|
|
4
|
+
import { basename, dirname, join, resolve } from 'node:path';
|
|
5
|
+
import { checkGeometry, sourceInRig, stageFields } from './assemble.ts';
|
|
6
|
+
import { parseEarlyConfig } from './config.ts';
|
|
7
|
+
import { PartsError } from './errors.ts';
|
|
8
|
+
import { PAINTING_IN_RIG_FILE, readParts } from './parts.ts';
|
|
9
|
+
import { decodePngBytes, encodePngBytes } from './raster/png.ts';
|
|
10
|
+
|
|
11
|
+
export const PAINTING_REFERENCE_SCHEMA = 'rig-parts-painting-reference/1';
|
|
12
|
+
export const PAINTING_REFERENCE_FILE = 'painting_in_rig.json';
|
|
13
|
+
|
|
14
|
+
export interface PaintingReference {
|
|
15
|
+
schema: typeof PAINTING_REFERENCE_SCHEMA;
|
|
16
|
+
manifest_sha256: string;
|
|
17
|
+
path: string;
|
|
18
|
+
sha256: string;
|
|
19
|
+
resample: 'lanczos3-rgb-opaque';
|
|
20
|
+
rig_size: [number, number];
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface PaintingReferenceSeal { path: string; sha256: string }
|
|
24
|
+
export interface PaintingReferenceInput {
|
|
25
|
+
manifest: PaintingReferenceSeal;
|
|
26
|
+
source: PaintingReferenceSeal;
|
|
27
|
+
config: PaintingReferenceSeal;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** The caller retains this execution trace outside the inspected package. */
|
|
31
|
+
export interface PaintingReferenceReceipt {
|
|
32
|
+
schema: 'rig-parts-painting-reference-write/1';
|
|
33
|
+
inputs: PaintingReferenceInput;
|
|
34
|
+
outputs: { declaration: PaintingReferenceSeal; image: PaintingReferenceSeal };
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const hash = (bytes: Uint8Array): string => createHash('sha256').update(bytes).digest('hex');
|
|
38
|
+
const hex = (value: unknown): value is string => typeof value === 'string' && /^[a-f0-9]{64}$/.test(value);
|
|
39
|
+
const record = (value: unknown): value is Record<string, unknown> => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
40
|
+
|
|
41
|
+
function fail(code: string, object: string, detail: string): never {
|
|
42
|
+
throw new PartsError([{ code, object, detail }]);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function portable(value: unknown): value is string {
|
|
46
|
+
return typeof value === 'string' && value.trim().length > 0 && !/[:\\%?#\x00-\x1f]/.test(value)
|
|
47
|
+
&& value.split('/').every(part => part !== '' && part !== '.' && part !== '..');
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** The six-key public sidecar grammar. Package/PNG binding is checked by its reader. */
|
|
51
|
+
export function parsePaintingReference(value: unknown, label = PAINTING_REFERENCE_FILE): PaintingReference {
|
|
52
|
+
const keys = ['schema', 'manifest_sha256', 'path', 'sha256', 'resample', 'rig_size'];
|
|
53
|
+
if (!record(value) || Object.keys(value).length !== keys.length || keys.some(key => !Object.hasOwn(value, key))
|
|
54
|
+
|| value.schema !== PAINTING_REFERENCE_SCHEMA || !hex(value.manifest_sha256) || !portable(value.path)
|
|
55
|
+
|| !hex(value.sha256) || value.resample !== 'lanczos3-rgb-opaque' || !Array.isArray(value.rig_size)
|
|
56
|
+
|| value.rig_size.length !== 2
|
|
57
|
+
|| !Number.isSafeInteger(value.rig_size[0]) || value.rig_size[0] <= 0
|
|
58
|
+
|| !Number.isSafeInteger(value.rig_size[1]) || value.rig_size[1] <= 0) {
|
|
59
|
+
return fail('PARTS_PAINTING_REFERENCE_SCHEMA', label, 'requires exactly schema, manifest_sha256, portable path, sha256, resample and positive safe-integer rig_size [W,H]; restore the producer declaration');
|
|
60
|
+
}
|
|
61
|
+
return { schema: PAINTING_REFERENCE_SCHEMA, manifest_sha256: value.manifest_sha256,
|
|
62
|
+
path: value.path, sha256: value.sha256, resample: value.resample, rig_size: [value.rig_size[0], value.rig_size[1]] };
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function readSealed(input: PaintingReferenceSeal, label: string): Buffer {
|
|
66
|
+
if (!record(input) || typeof input.path !== 'string' || !input.path.trim() || !hex(input.sha256)) {
|
|
67
|
+
return fail('PARTS_PAINTING_REFERENCE_INPUT', label, 'requires an explicit file path and expected lowercase SHA-256; supply the frozen input seal');
|
|
68
|
+
}
|
|
69
|
+
let bytes: Buffer;
|
|
70
|
+
try {
|
|
71
|
+
if (!fs.lstatSync(input.path).isFile()) throw new Error('requires a regular file without a symlink');
|
|
72
|
+
const descriptor = fs.openSync(input.path, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW);
|
|
73
|
+
try {
|
|
74
|
+
if (!fs.fstatSync(descriptor).isFile()) throw new Error('requires a regular file');
|
|
75
|
+
bytes = fs.readFileSync(descriptor);
|
|
76
|
+
} finally { fs.closeSync(descriptor); }
|
|
77
|
+
} catch (error) {
|
|
78
|
+
return fail('PARTS_PAINTING_REFERENCE_INPUT', input.path, `${label} is unreadable (${String(error)}); restore the sealed regular input`);
|
|
79
|
+
}
|
|
80
|
+
if (hash(bytes) !== input.sha256) return fail('PARTS_PAINTING_REFERENCE_HASH', input.path, `${label} differs from expected SHA-256 ${input.sha256}; restore the frozen input`);
|
|
81
|
+
return bytes;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function readJson(bytes: Uint8Array, label: string): unknown {
|
|
85
|
+
try { return JSON.parse(Buffer.from(bytes).toString('utf8')); }
|
|
86
|
+
catch { return fail('PARTS_PAINTING_REFERENCE_INPUT', label, 'requires readable JSON; restore the sealed manifest or config'); }
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** Existing output is usable only when it is a regular file with identical bytes. */
|
|
90
|
+
function existingOutput(path: string, expected: Uint8Array): boolean {
|
|
91
|
+
let descriptor: number | undefined;
|
|
92
|
+
try {
|
|
93
|
+
if (!fs.lstatSync(path).isFile()) fail('PARTS_PAINTING_REFERENCE_OUTPUT', path, 'is not a regular file; preserve it and resolve the output collision');
|
|
94
|
+
descriptor = fs.openSync(path, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW);
|
|
95
|
+
if (!fs.fstatSync(descriptor).isFile() || !fs.readFileSync(descriptor).equals(Buffer.from(expected))) {
|
|
96
|
+
fail('PARTS_PAINTING_REFERENCE_OUTPUT', path, 'already exists with different bytes; preserve the existing file and resolve the collision before retrying');
|
|
97
|
+
}
|
|
98
|
+
return true;
|
|
99
|
+
}
|
|
100
|
+
catch (error) {
|
|
101
|
+
if (error instanceof PartsError) throw error;
|
|
102
|
+
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return false;
|
|
103
|
+
return fail('PARTS_PAINTING_REFERENCE_OUTPUT', path, `cannot inspect the destination (${String(error)}); restore its directory permissions`);
|
|
104
|
+
} finally {
|
|
105
|
+
if (descriptor !== undefined) fs.closeSync(descriptor);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** Publish complete bytes with a no-replace link, including a concurrent exact retry. */
|
|
110
|
+
function publishFile(staged: string, target: string, bytes: Uint8Array): void {
|
|
111
|
+
try { fs.linkSync(staged, target); }
|
|
112
|
+
catch (error) {
|
|
113
|
+
if ((error as NodeJS.ErrnoException).code === 'EEXIST' && existingOutput(target, bytes)) return;
|
|
114
|
+
throw error;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Add the reference PNG and adjacent sidecar after validating all sealed inputs.
|
|
120
|
+
* The sidecar is the commit point. An interrupted writer can leave an unreferenced
|
|
121
|
+
* complete PNG; an exact retry verifies it and finishes the declaration. Each
|
|
122
|
+
* destination is published without replacement, so concurrent writers cannot
|
|
123
|
+
* overwrite accepted files. The caller holds independent input writers frozen.
|
|
124
|
+
*/
|
|
125
|
+
export function writePaintingReference(input: PaintingReferenceInput): PaintingReferenceReceipt {
|
|
126
|
+
const manifestBytes = readSealed(input.manifest, 'manifest');
|
|
127
|
+
const sourceBytes = readSealed(input.source, 'source');
|
|
128
|
+
const configBytes = readSealed(input.config, 'config');
|
|
129
|
+
if (basename(input.manifest.path) !== 'parts.json') {
|
|
130
|
+
return fail('PARTS_PAINTING_REFERENCE_INPUT', input.manifest.path, 'requires the exact parts.json file; select the frozen parts manifest');
|
|
131
|
+
}
|
|
132
|
+
const directory = fs.realpathSync(dirname(resolve(input.manifest.path)));
|
|
133
|
+
const manifest = readParts(input.manifest.path);
|
|
134
|
+
const size = manifest.rig_size;
|
|
135
|
+
if (size.length !== 2 || !size.every(n => Number.isSafeInteger(n) && n > 0)) {
|
|
136
|
+
return fail('PARTS_PAINTING_REFERENCE_FRAME', input.manifest.path, 'rig_size must contain two positive safe integers; restore the recorded producer frame');
|
|
137
|
+
}
|
|
138
|
+
const config = parseEarlyConfig(readJson(configBytes, input.config.path), 'assemble');
|
|
139
|
+
let source: ReturnType<typeof decodePngBytes>;
|
|
140
|
+
try { source = decodePngBytes(sourceBytes, input.source.path); }
|
|
141
|
+
catch (error) { return fail('PARTS_PAINTING_REFERENCE_INPUT', input.source.path, `source PNG cannot be decoded (${String(error)}); restore the sealed original painting`); }
|
|
142
|
+
// Assemble records every run layer in ghost_px, including zero counts.
|
|
143
|
+
// A resolution-square single run has this census but no padding record.
|
|
144
|
+
const runKeys = Object.keys(manifest.ghost_px);
|
|
145
|
+
const hasHeadRun = runKeys.some(key => key.startsWith('head:'));
|
|
146
|
+
if (!runKeys.some(key => key.startsWith('full:'))) {
|
|
147
|
+
return fail('PARTS_PAINTING_REFERENCE_FRAME', input.manifest.path, 'ghost_px has no full-run census to bind the run mode; restore the original producer manifest');
|
|
148
|
+
}
|
|
149
|
+
const pad = manifest.single_run_pad;
|
|
150
|
+
if (hasHeadRun && pad !== undefined) {
|
|
151
|
+
return fail('PARTS_PAINTING_REFERENCE_FRAME', input.manifest.path, 'head-run census conflicts with single_run_pad; restore the original producer manifest');
|
|
152
|
+
}
|
|
153
|
+
if (!hasHeadRun) {
|
|
154
|
+
if (manifest.parts.some(part => part.from.startsWith('head:')) || config.assemble.plan.some(([, run]) => run === 'head')
|
|
155
|
+
|| (config.assemble.extend_below_crop?.length ?? 0) > 0) {
|
|
156
|
+
return fail('PARTS_PAINTING_REFERENCE_FRAME', input.manifest.path, 'full-only run census conflicts with head-run part, plan or crop-extension references; supply the matching original config and manifest');
|
|
157
|
+
}
|
|
158
|
+
if (pad === undefined && (source.width !== config.seethrough.resolution || source.height !== config.seethrough.resolution)) {
|
|
159
|
+
return fail('PARTS_PAINTING_REFERENCE_FRAME', input.manifest.path, 'single-run source is not the resolution square and has no single_run_pad; restore its recorded producer padding');
|
|
160
|
+
}
|
|
161
|
+
if (pad !== undefined && (pad.file_size[0] !== source.width || pad.file_size[1] !== source.height || pad.side !== config.seethrough.resolution)) {
|
|
162
|
+
return fail('PARTS_PAINTING_REFERENCE_FRAME', input.manifest.path, 'single_run_pad file_size or side differs from sealed source/config; supply the original source and config');
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
const single = hasHeadRun ? null : { w: source.width, h: source.height };
|
|
166
|
+
const fields = stageFields(config, single);
|
|
167
|
+
const frame = checkGeometry({ sourceW: source.width, sourceH: source.height, ...fields });
|
|
168
|
+
if (frame.W !== size[0] || frame.H !== size[1] || frame.S !== manifest.scale_rig_per_source) {
|
|
169
|
+
return fail('PARTS_PAINTING_REFERENCE_FRAME', input.manifest.path, `recorded ${size.join('x')} at scale ${manifest.scale_rig_per_source} differs from the sealed source/config frame ${frame.W}x${frame.H} at scale ${frame.S}; supply the original source and config`);
|
|
170
|
+
}
|
|
171
|
+
const imageBytes = encodePngBytes(sourceInRig(source, size[0], size[1]));
|
|
172
|
+
const declaration = parsePaintingReference({ schema: PAINTING_REFERENCE_SCHEMA,
|
|
173
|
+
manifest_sha256: hash(manifestBytes), path: PAINTING_IN_RIG_FILE, sha256: hash(imageBytes),
|
|
174
|
+
resample: 'lanczos3-rgb-opaque', rig_size: size });
|
|
175
|
+
const declarationBytes = Buffer.from(JSON.stringify(declaration, null, 2) + '\n');
|
|
176
|
+
const imagePath = join(directory, PAINTING_IN_RIG_FILE);
|
|
177
|
+
const declarationPath = join(directory, PAINTING_REFERENCE_FILE);
|
|
178
|
+
const unchanged = (): void => {
|
|
179
|
+
readSealed(input.manifest, 'manifest');
|
|
180
|
+
readSealed(input.source, 'source');
|
|
181
|
+
readSealed(input.config, 'config');
|
|
182
|
+
if (fs.realpathSync(dirname(resolve(input.manifest.path))) !== directory) {
|
|
183
|
+
fail('PARTS_PAINTING_REFERENCE_INPUT', input.manifest.path, 'manifest directory moved; restore the frozen package location');
|
|
184
|
+
}
|
|
185
|
+
};
|
|
186
|
+
const receipt: PaintingReferenceReceipt = { schema: 'rig-parts-painting-reference-write/1',
|
|
187
|
+
inputs: { manifest: { ...input.manifest }, source: { ...input.source }, config: { ...input.config } },
|
|
188
|
+
outputs: { declaration: { path: declarationPath, sha256: hash(declarationBytes) }, image: { path: imagePath, sha256: hash(imageBytes) } } };
|
|
189
|
+
const imageExists = existingOutput(imagePath, imageBytes);
|
|
190
|
+
const declarationExists = existingOutput(declarationPath, declarationBytes);
|
|
191
|
+
unchanged();
|
|
192
|
+
if (imageExists && declarationExists) return receipt;
|
|
193
|
+
let stage: string | undefined;
|
|
194
|
+
try {
|
|
195
|
+
stage = fs.mkdtempSync(join(directory, '.painting-reference-'));
|
|
196
|
+
const stagedImage = join(stage, PAINTING_IN_RIG_FILE), stagedDeclaration = join(stage, PAINTING_REFERENCE_FILE);
|
|
197
|
+
fs.writeFileSync(stagedImage, imageBytes, { flag: 'wx' });
|
|
198
|
+
fs.writeFileSync(stagedDeclaration, declarationBytes, { flag: 'wx' });
|
|
199
|
+
unchanged();
|
|
200
|
+
publishFile(stagedImage, imagePath, imageBytes);
|
|
201
|
+
unchanged();
|
|
202
|
+
publishFile(stagedDeclaration, declarationPath, declarationBytes);
|
|
203
|
+
return receipt;
|
|
204
|
+
} catch (error) {
|
|
205
|
+
if (error instanceof PartsError) throw error;
|
|
206
|
+
return fail('PARTS_PAINTING_REFERENCE_WRITE', declarationPath, `publication failed (${String(error)}); preserve existing files and retry with the same input seals`);
|
|
207
|
+
} finally {
|
|
208
|
+
if (stage !== undefined) fs.rmSync(stage, { recursive: true, force: true });
|
|
209
|
+
}
|
|
210
|
+
}
|