rig-parts 2.68.0 → 2.70.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 -0
- package/cli.ts +69 -8
- package/docs/AUTHORING.md +159 -41
- package/docs/STABILITY.md +120 -18
- package/package.json +2 -1
- package/src/build.ts +5 -1
- package/src/check.ts +105 -14
- package/src/checkrow.ts +1 -0
- package/src/coincide.ts +337 -27
- package/src/coincideio.ts +57 -4
- package/src/depthworkflow.ts +187 -18
- package/src/editedparts.ts +57 -21
- package/src/parts.ts +27 -21
- package/src/partscheck.ts +13 -23
- package/src/partsfiles.ts +62 -0
- package/src/replacementrecord.ts +508 -0
- package/src/replaceparts.ts +561 -0
- package/src/rig.ts +1 -1
- package/src/runstamp.ts +24 -3
package/src/depthworkflow.ts
CHANGED
|
@@ -1,23 +1,27 @@
|
|
|
1
1
|
/** Explicit opt-in commands for provider maps on already assembled parts (#897).
|
|
2
2
|
* No existing assembly/build path calls these stages. All inputs validate before
|
|
3
|
-
* the first output is emitted
|
|
3
|
+
* the first output is emitted. A signed application publishes to an absent directory.
|
|
4
4
|
*/
|
|
5
5
|
import { createHash } from 'node:crypto';
|
|
6
|
-
import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync, statSync, writeFileSync } from 'node:fs';
|
|
6
|
+
import { existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';
|
|
7
7
|
import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
|
|
8
8
|
import { refuseStaleAssembly } from './assembly-reading.ts';
|
|
9
|
-
import { PartsError, type Problem } from './errors.ts';
|
|
9
|
+
import { foldName, PartsError, type Problem } from './errors.ts';
|
|
10
10
|
import { loadConfigAndAnimations, parseConfig } from './config.ts';
|
|
11
11
|
import { relocateConfigReferences } from './configrelocation.ts';
|
|
12
|
+
import { CUT_MATERIAL_SOURCES } from './cutmaterial.ts';
|
|
12
13
|
import { depthReading, readSourceDepth } from './depthsheets.ts';
|
|
13
14
|
import { readEditorReceipts } from './editreceipt.ts';
|
|
14
15
|
import { alphaSupport, depthMapFail as fail, floatBox, integrateNormals, mapQuantile, mapToSheet, readNumericMap, type NumericMap } from './depthmaps.ts';
|
|
15
|
-
import { depthImageReference, partImageReference, readParts } from './parts.ts';
|
|
16
|
+
import { depthImageReference, partImageReference, readParts, type PartsFile } from './parts.ts';
|
|
17
|
+
import { withinPartsPath, type PartsInventoryRow } from './partsfiles.ts';
|
|
16
18
|
import { readPartSet, type PartSet } from './propose.ts';
|
|
17
19
|
import { decodePngBytes, encodePngBytes } from './raster/png.ts';
|
|
18
20
|
import { resize } from './raster/resize.ts';
|
|
19
21
|
import { connectedComponents } from './raster/components.ts';
|
|
20
22
|
import { newRaster, type Raster } from './raster/types.ts';
|
|
23
|
+
import { verifyReplacementRecord } from './replaceparts.ts';
|
|
24
|
+
import { captureReplacementTree, createDepthReplacementRecord, digestReplacementInventory, readBoundReplacementFile, replacementRecordPath } from './replacementrecord.ts';
|
|
21
25
|
|
|
22
26
|
type Obj = Record<string, unknown>;
|
|
23
27
|
interface PrepareOptions { longSide: number; paddingFraction: number; padding: number }
|
|
@@ -525,17 +529,160 @@ function groupSelection(recipe: DepthRecipe, groups: readonly string[] | undefin
|
|
|
525
529
|
if (problems.length) throw new PartsError(problems);
|
|
526
530
|
return declared.filter(g => seen.has(g));
|
|
527
531
|
}
|
|
528
|
-
|
|
532
|
+
interface ApplyDepthInput {
|
|
533
|
+
parts: string;
|
|
534
|
+
manifest: string;
|
|
535
|
+
config: string;
|
|
536
|
+
rigConfig: string;
|
|
537
|
+
out: string;
|
|
538
|
+
groups?: readonly string[];
|
|
539
|
+
sourceSha256?: string;
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
interface RecordedDepthSource {
|
|
543
|
+
root: string;
|
|
544
|
+
requestedOut: string;
|
|
545
|
+
out: string;
|
|
546
|
+
digest: string;
|
|
547
|
+
pointer: string;
|
|
548
|
+
inventory: ReadonlyMap<string, PartsInventoryRow>;
|
|
549
|
+
file: PartsFile;
|
|
550
|
+
manifest: Obj;
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
function depthBundlePath(path: string): string {
|
|
554
|
+
if (existsSync(path)) return realpathSync(path);
|
|
555
|
+
return join(depthBundlePath(dirname(path)), basename(path));
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
function depthBundleOutput(path: string, source: string, inputs: readonly string[]): string {
|
|
559
|
+
const target = resolve(path);
|
|
560
|
+
const refuse = (): never => fail('DEPTH_RECORD_OUTPUT', '--out', 'found an unavailable, occupied or overlapping path; required an absent directory disjoint from all inputs');
|
|
561
|
+
try {
|
|
562
|
+
if (lstatSync(target, { throwIfNoEntry: false }) !== undefined) return refuse();
|
|
563
|
+
const out = depthBundlePath(target);
|
|
564
|
+
if (withinPartsPath(source, out)) return refuse();
|
|
565
|
+
for (const input of [source, ...inputs]) {
|
|
566
|
+
const full = resolve(input);
|
|
567
|
+
if (withinPartsPath(target, full) || withinPartsPath(out, depthBundlePath(full))) return refuse();
|
|
568
|
+
}
|
|
569
|
+
return out;
|
|
570
|
+
} catch (error) {
|
|
571
|
+
if (error instanceof PartsError) throw error;
|
|
572
|
+
return refuse();
|
|
573
|
+
}
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
function recordedDepthSource(input: ApplyDepthInput, digest: string, paths: readonly string[]): RecordedDepthSource {
|
|
577
|
+
const path = resolve(input.parts);
|
|
578
|
+
if (!lstatSync(path, { throwIfNoEntry: false })?.isDirectory()) {
|
|
579
|
+
fail('REPLACE_PART_INPUT', '--parts', 'found a missing, linked or non-directory source; required a regular parts root');
|
|
580
|
+
}
|
|
581
|
+
const root = realpathSync(path);
|
|
582
|
+
const out = depthBundleOutput(input.out, root, paths);
|
|
583
|
+
if (lstatSync(join(root, CUT_MATERIAL_SOURCES), { throwIfNoEntry: false }) !== undefined) {
|
|
584
|
+
fail('DEPTH_RECORD_MANIFEST_BOUND', CUT_MATERIAL_SOURCES, 'found a source manifest binding; required a source set without cut_material_sources.json');
|
|
585
|
+
}
|
|
586
|
+
const inventory = captureReplacementTree(root), actual = digestReplacementInventory(inventory);
|
|
587
|
+
if (actual !== digest) {
|
|
588
|
+
fail('REPLACE_PART_SOURCE_HASH', 'recorded set', `found sha256 ${actual} — required sha256 ${digest}`);
|
|
589
|
+
}
|
|
590
|
+
const file = readParts(join(root, 'parts.json'));
|
|
591
|
+
const manifest = object(JSON.parse(readBoundReplacementFile(root, inventory, 'parts.json').toString('utf8')), 'parts.json');
|
|
592
|
+
if (text(file) !== text(manifest)) fail('REPLACE_PART_INPUT', 'parts.json', 'manifest changed while reading the source inventory');
|
|
593
|
+
verifyReplacementRecord(root, file);
|
|
594
|
+
const pointer = replacementRecordPath(digest);
|
|
595
|
+
if ([...inventory.keys()].some(path => foldName(path) === pointer)) {
|
|
596
|
+
fail('DEPTH_RECORD_OUTPUT', pointer, 'found an existing source receipt path; required a new active receipt path');
|
|
597
|
+
}
|
|
598
|
+
return { root, requestedOut: resolve(input.out), out, digest, pointer, inventory, file, manifest };
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
function writeDepthBundle(
|
|
602
|
+
source: RecordedDepthSource, parts: Obj, config: Obj, report: Obj,
|
|
603
|
+
writes: ReadonlyMap<string, Uint8Array>, removed: ReadonlySet<string>,
|
|
604
|
+
groups: ReadonlyMap<string, Group>, partGroups: ReadonlyMap<string, string | null>,
|
|
605
|
+
): void {
|
|
606
|
+
const parent = dirname(source.out);
|
|
607
|
+
const refuse = (): never => fail('DEPTH_RECORD_OUTPUT', '--out', 'found an unavailable or occupied destination; required an absent directory in a writable, stable parent');
|
|
608
|
+
const available = (): boolean => realpathSync(parent) === parent && depthBundlePath(source.requestedOut) === source.out &&
|
|
609
|
+
lstatSync(source.out, { throwIfNoEntry: false }) === undefined;
|
|
610
|
+
let scratch: string;
|
|
611
|
+
try {
|
|
612
|
+
mkdirSync(parent, { recursive: true });
|
|
613
|
+
if (!available()) return refuse();
|
|
614
|
+
scratch = mkdtempSync(join(parent, '.depth-apply-'));
|
|
615
|
+
} catch (error) {
|
|
616
|
+
if (error instanceof PartsError) throw error;
|
|
617
|
+
return refuse();
|
|
618
|
+
}
|
|
619
|
+
try {
|
|
620
|
+
const stage = join(scratch, 'bundle');
|
|
621
|
+
const set = join(stage, 'set');
|
|
622
|
+
const emit = (path: string, bytes: Uint8Array | string): void => {
|
|
623
|
+
const target = join(set, path);
|
|
624
|
+
try {
|
|
625
|
+
mkdirSync(dirname(target), { recursive: true });
|
|
626
|
+
writeFileSync(target, bytes, { flag: 'wx' });
|
|
627
|
+
} catch (error) {
|
|
628
|
+
const code = (error as NodeJS.ErrnoException).code;
|
|
629
|
+
if (code === 'EEXIST' || code === 'ENOTDIR' || code === 'EISDIR') {
|
|
630
|
+
fail('DEPTH_RECORD_DELTA', path, 'found a file or directory alias in the staged set; required a unique owned path');
|
|
631
|
+
}
|
|
632
|
+
refuse();
|
|
633
|
+
}
|
|
634
|
+
};
|
|
635
|
+
for (const path of source.inventory.keys()) {
|
|
636
|
+
if (path !== 'parts.json' && !removed.has(path)) emit(path, readBoundReplacementFile(source.root, source.inventory, path));
|
|
637
|
+
}
|
|
638
|
+
for (const [file, bytes] of writes) emit(`parts/${file}`, bytes);
|
|
639
|
+
parts.replacement_record = source.pointer;
|
|
640
|
+
emit('parts.json', text(parts));
|
|
641
|
+
const record = createDepthReplacementRecord(source.root, set, groups, partGroups);
|
|
642
|
+
emit(source.pointer, text(record));
|
|
643
|
+
verifyReplacementRecord(set, readParts(join(set, 'parts.json')));
|
|
644
|
+
try {
|
|
645
|
+
writeFileSync(join(stage, 'config.json'), text(config), { flag: 'wx' });
|
|
646
|
+
writeFileSync(join(stage, 'depth-report.json'), text(report), { flag: 'wx' });
|
|
647
|
+
} catch { return refuse(); }
|
|
648
|
+
|
|
649
|
+
const actual = digestReplacementInventory(captureReplacementTree(source.root));
|
|
650
|
+
if (actual !== source.digest) {
|
|
651
|
+
fail('REPLACE_PART_SOURCE_HASH', 'recorded set', `found sha256 ${actual} before publication — required sha256 ${source.digest}`);
|
|
652
|
+
}
|
|
653
|
+
try {
|
|
654
|
+
if (!available()) return refuse();
|
|
655
|
+
renameSync(stage, source.out);
|
|
656
|
+
} catch (error) {
|
|
657
|
+
if (error instanceof PartsError) throw error;
|
|
658
|
+
return refuse();
|
|
659
|
+
}
|
|
660
|
+
} finally {
|
|
661
|
+
rmSync(scratch, { recursive: true, force: true });
|
|
662
|
+
}
|
|
663
|
+
}
|
|
664
|
+
|
|
665
|
+
export function applyDepth(input: ApplyDepthInput, log: (line: string) => void = console.warn): Obj {
|
|
529
666
|
const recipe = parseDepthRecipe(readJson(input.config)), selection = groupSelection(recipe, input.groups), applied = (group: string): boolean => selection === undefined || selection.includes(group);
|
|
530
|
-
const
|
|
667
|
+
const inputPaths = [input.config, input.manifest, input.rigConfig, ...Object.values(recipe.parts).flatMap(p => { const map = resolve(dirname(input.config), p.map); return [map, map + '.binding.json']; })];
|
|
668
|
+
const recorded = input.sourceSha256 === undefined ? undefined : recordedDepthSource(input, input.sourceSha256, [
|
|
669
|
+
...inputPaths, ...Object.keys(recipe.parts).map(name => join(dirname(input.manifest), `${name}.png`)),
|
|
670
|
+
]);
|
|
671
|
+
const source = recorded?.root ?? input.parts;
|
|
672
|
+
const expected = preparedParts(source, recipe);
|
|
673
|
+
if (recorded !== undefined && (expected.manifest.partsSha256 !== recorded.inventory.get('parts.json')?.sha256 ||
|
|
674
|
+
expected.manifest.parts.some(p => p.sourceSha256 !== recorded.inventory.get(`parts/${p.part}.png`)?.sha256))) {
|
|
675
|
+
fail('REPLACE_PART_INPUT', '--parts', 'manifest or art changed after capture of the source inventory');
|
|
676
|
+
}
|
|
531
677
|
const supplied = readJson(input.manifest);
|
|
532
678
|
if (text(supplied) !== text(expected.manifest)) fail('DEPTH_INPUT_BINDING', input.manifest, 'does not match the recipe, parts.json, art hashes, crop or padding; run depth-prepare again for these exact inputs');
|
|
533
679
|
for (const p of expected.manifest.parts) {
|
|
534
680
|
const file = join(dirname(input.manifest), p.input);
|
|
535
681
|
if (!existsSync(file) || hash(readFileSync(file)) !== p.inputSha256) fail('DEPTH_INPUT_BINDING', p.part, 'prepared inference PNG is missing or changed; restore its exact bytes or prepare again');
|
|
536
682
|
}
|
|
537
|
-
|
|
538
|
-
const rawParts = object(readJson(join(
|
|
683
|
+
if (recorded === undefined) emptyOutput(input.out, [source, ...inputPaths]);
|
|
684
|
+
const rawParts = recorded?.manifest ?? object(readJson(join(source, 'parts.json')), 'parts.json');
|
|
685
|
+
const file = recorded?.file ?? readParts(join(source, 'parts.json'));
|
|
539
686
|
for (const p of file.parts) if (Object.hasOwn(recipe.parts, p.name) && applied(recipe.parts[p.name].group) && p.provenance?.depth?.kind === 'authored-unit') fail('DEPTH_AUTHORED_UNIT_CONFLICT', `part "${p.name}"`, 'has provenance.depth.kind "authored-unit"; a transported scalar reference cannot coexist with authored unit depth — retain the unit declaration or supply an explicitly reassembled scalar-compatible input; no automatic transition is made');
|
|
540
687
|
const { config } = loadConfigAndAnimations(input.rigConfig);
|
|
541
688
|
const receiptProblems = readEditorReceipts(config.assemble.editor_receipts, input.rigConfig).problems;
|
|
@@ -559,13 +706,15 @@ export function applyDepth(input: { parts: string; manifest: string; config: str
|
|
|
559
706
|
if (group.unitDepths !== undefined) target.unitDepths = group.unitDepths;
|
|
560
707
|
}
|
|
561
708
|
// Keep relative paths portable when relocating the output directory with its inputs.
|
|
562
|
-
|
|
563
|
-
|
|
709
|
+
const configDir = recorded?.out ?? input.out;
|
|
710
|
+
relocateConfigReferences(raw, dirname(input.rigConfig), configDir, 'relative');
|
|
711
|
+
const relocatedConfig = parseConfig(raw), outConfig = join(configDir, 'config.json');
|
|
564
712
|
const relocatedReceiptProblems = readEditorReceipts(relocatedConfig.assemble.editor_receipts, outConfig).problems;
|
|
565
713
|
if (relocatedReceiptProblems.length) throw new PartsError(relocatedReceiptProblems);
|
|
566
714
|
refuseStaleAssembly(outConfig, file, relocatedConfig);
|
|
567
715
|
const warnings: string[] = [];
|
|
568
716
|
const writes = new Map<string, Uint8Array>(), rows: Obj[] = [], recs = rawParts.parts as Obj[];
|
|
717
|
+
const removed = new Set<string>(), partGroups = new Map<string, string | null>();
|
|
569
718
|
const groupMaxZ = new Map<string, number>();
|
|
570
719
|
const clipped: { name: string; group: string; fraction: number; clipsHigh: boolean; median: number; minMedian?: number }[] = [];
|
|
571
720
|
// Retain auxiliary art (including alternate sets) and diagnostics byte-for-byte.
|
|
@@ -579,16 +728,30 @@ export function applyDepth(input: { parts: string; manifest: string; config: str
|
|
|
579
728
|
else fail('DEPTH_INPUT_PRESENT', path, 'is not a regular owned file/directory; supply a self-contained assembled directory without symlinks');
|
|
580
729
|
}
|
|
581
730
|
};
|
|
582
|
-
collect(
|
|
731
|
+
if (recorded === undefined) collect(source, '');
|
|
583
732
|
for (const p of file.parts) {
|
|
584
|
-
const name = p.name,
|
|
585
|
-
|
|
733
|
+
const name = p.name, artPath = partImageReference(p).path;
|
|
734
|
+
const bytes = recorded === undefined ? readFileSync(join(source, artPath)) : readBoundReplacementFile(source, recorded.inventory, artPath);
|
|
735
|
+
const art = decodePngBytes(bytes, name), rec = recs.find(r => r.name === name) as Obj;
|
|
736
|
+
if (recorded === undefined) writes.set(`${name}.png`, bytes);
|
|
586
737
|
const declaration = Object.hasOwn(recipe.parts, name) ? recipe.parts[name] : undefined;
|
|
738
|
+
const removeDepth = (group: string | null): void => {
|
|
739
|
+
if (p.depth !== undefined) {
|
|
740
|
+
const path = depthImageReference(p.depth).path;
|
|
741
|
+
if (recorded === undefined) retained.delete(path);
|
|
742
|
+
else removed.add(path);
|
|
743
|
+
}
|
|
744
|
+
if (recorded !== undefined && (p.depth !== undefined || group !== null)) partGroups.set(name, group);
|
|
745
|
+
};
|
|
587
746
|
// A left-out group's part gets no new sheet, and any sheet it carried is dropped, never retained stale.
|
|
588
|
-
if (declaration !== undefined && !applied(declaration.group)) {
|
|
747
|
+
if (declaration !== undefined && !applied(declaration.group)) { removeDepth(null); delete rec.depth; continue; }
|
|
589
748
|
if (declaration === undefined) {
|
|
590
|
-
if (recipe.clear.includes(name)) {
|
|
591
|
-
else if (p.depth !== undefined) {
|
|
749
|
+
if (recipe.clear.includes(name)) { removeDepth(null); delete rec.depth; }
|
|
750
|
+
else if (p.depth !== undefined) {
|
|
751
|
+
const depthPath = join(source, depthImageReference(p.depth).path);
|
|
752
|
+
readSourceDepth(depthPath, art, null);
|
|
753
|
+
if (recorded === undefined) writes.set(p.depth.image, readFileSync(depthPath));
|
|
754
|
+
}
|
|
592
755
|
continue;
|
|
593
756
|
}
|
|
594
757
|
const g = recipe.groups[declaration.group], target = declaration.group === 'head' ? turn : object(turn.body, 'config.turn.body');
|
|
@@ -618,9 +781,9 @@ export function applyDepth(input: { parts: string; manifest: string; config: str
|
|
|
618
781
|
continue;
|
|
619
782
|
}
|
|
620
783
|
const image = `${name}_depth.png`, sheetBytes = encodePngBytes(sheet);
|
|
621
|
-
if (file.parts.some(p => `${p.name}.png` === image)) fail('DEPTH_GROUP_BINDING', name, `sheet filename ${image} collides with artwork; use noncolliding part names`);
|
|
784
|
+
if (recorded === undefined && file.parts.some(p => `${p.name}.png` === image)) fail('DEPTH_GROUP_BINDING', name, `sheet filename ${image} collides with artwork; use noncolliding part names`);
|
|
622
785
|
writes.set(image, sheetBytes);
|
|
623
|
-
|
|
786
|
+
removeDepth(declaration.group);
|
|
624
787
|
rec.depth = { image, near: g.near, zScale: g.zScale, sources: [{ from: p.from, image: basename(declaration.map), sha256: hash(mapBytes), crop: [0, 0, art.width, art.height], reading: depthReading(sheet, art, null) }] };
|
|
625
788
|
rows.push({ part: name, group: declaration.group, source: declaration.source, frame: declaration.frame, sourceSha256: prepared.sourceSha256, mapSha256: hash(mapBytes), inputSha256: prepared.inputSha256, sheetSha256: hash(sheetBytes), median: declaration.median, relief: declaration.relief, near: g.near, zScale: g.zScale, pivot: g.pivot, ...reading, sign: normal?.sign ?? 1, ...(normal === undefined ? {} : { integration: { stride: 2, iterations: normal.iterations, residual: normal.residual, coreMinusRim: normal.coreMinusRim, maxIterations: 3000, atol: 1e-6, btol: 1e-6 } }) });
|
|
626
789
|
}
|
|
@@ -647,6 +810,12 @@ export function applyDepth(input: { parts: string; manifest: string; config: str
|
|
|
647
810
|
}
|
|
648
811
|
const report = { spec: 'rig-parts-depth-report/1', partsSha256: expected.manifest.partsSha256, recipeSha256: expected.manifest.recipeSha256, manifestSha256: hash(readFileSync(input.manifest)), rigConfigSha256: hash(readFileSync(input.rigConfig)), alpha: 128, normalization: 'median, linear p5..p95', extension: 'nearest alpha>=128, row-major ties', cleared: recipe.clear,
|
|
649
812
|
...(selection === undefined ? {} : { selection: { groups: selection, leftOut: file.parts.filter(p => Object.hasOwn(recipe.parts, p.name) && !applied(recipe.parts[p.name].group)).map(p => p.name) } }), parts: rows };
|
|
813
|
+
if (recorded !== undefined) {
|
|
814
|
+
const groups = new Map(Object.entries(recipe.groups).filter(([name]) => applied(name)));
|
|
815
|
+
writeDepthBundle(recorded, rawParts, raw, report, writes, removed, groups, partGroups);
|
|
816
|
+
for (const warning of warnings) log(warning);
|
|
817
|
+
return report;
|
|
818
|
+
}
|
|
650
819
|
mkdirSync(join(input.out, 'parts'), { recursive: true });
|
|
651
820
|
for (const [file, bytes] of retained) {
|
|
652
821
|
if (['parts.json', 'config.json', 'depth-report.json'].includes(file)) continue;
|
package/src/editedparts.ts
CHANGED
|
@@ -3,8 +3,8 @@ import type { PartVisibility } from './partvisibility.ts';
|
|
|
3
3
|
import { createHash } from 'node:crypto';
|
|
4
4
|
import { readFileSync } from 'node:fs';
|
|
5
5
|
import { dirname, resolve } from 'node:path';
|
|
6
|
-
import type
|
|
7
|
-
import { parseReceiptProducer, type ReceiptProducer } from './receiptproducer.ts';
|
|
6
|
+
import { SHA256_PATTERN, type EditorReceipt } from './editreceipt.ts';
|
|
7
|
+
import { parseReceiptProducer, receiptObject, receiptText, type ReceiptProducer } from './receiptproducer.ts';
|
|
8
8
|
import { refuseIfAny, type Problem } from './errors.ts';
|
|
9
9
|
import { OPAQUE_ALPHA_ABOVE } from './layers.ts';
|
|
10
10
|
import { AUTOMATIC_WRITERS, EXCLUDED_PIXEL, NOT_OVERRIDDEN_PIXEL, rgbaEqual, type AutomaticWriter, type PartStageMap, type PixelProvenance, type StageMap, type ValueBaseline } from './provenance.ts';
|
|
@@ -17,6 +17,23 @@ import type { PaintingOwner } from './paintingowner.ts';
|
|
|
17
17
|
export type EditedPartReceipt = Omit<EditorReceipt, 'editor'> & { part: string } &
|
|
18
18
|
({ editor: string; producer?: never } | { producer: ReceiptProducer; editor?: never });
|
|
19
19
|
|
|
20
|
+
export function editedPartReceiptProblem(value: unknown): string | undefined {
|
|
21
|
+
if (!receiptObject(value)) return 'missing or invalid receipt object';
|
|
22
|
+
if (!receiptText(value.part)) return 'missing or invalid part';
|
|
23
|
+
if (!receiptText(value.file) || /^(?:[\\/]|[A-Za-z]:[\\/])/.test(value.file)) return 'missing or invalid relative file';
|
|
24
|
+
for (const key of ['sha256', 'from_sha256'] as const) {
|
|
25
|
+
const hash = value[key];
|
|
26
|
+
if (typeof hash !== 'string' || !SHA256_PATTERN.test(hash)) return `missing or invalid ${key}`;
|
|
27
|
+
}
|
|
28
|
+
const keys = Object.keys(value).sort().join(',');
|
|
29
|
+
if (keys === 'editor,file,from_sha256,part,sha256') return receiptText(value.editor) ? undefined : 'invalid editor';
|
|
30
|
+
if (keys === 'file,from_sha256,part,producer,sha256') {
|
|
31
|
+
try { parseReceiptProducer(value.producer, 'edited part producer'); return undefined; }
|
|
32
|
+
catch { return 'invalid producer'; }
|
|
33
|
+
}
|
|
34
|
+
return 'missing exclusive editor or producer, or unexpected receipt field';
|
|
35
|
+
}
|
|
36
|
+
|
|
20
37
|
export function orderedEditedPartReceipt(receipt: EditedPartReceipt): EditedPartReceipt {
|
|
21
38
|
const { part, file, sha256, from_sha256, editor, producer } = receipt;
|
|
22
39
|
const fields = { part, file, sha256, from_sha256 };
|
|
@@ -31,10 +48,7 @@ export interface VerifiedEditedPart {
|
|
|
31
48
|
bytes: Uint8Array;
|
|
32
49
|
image: Raster;
|
|
33
50
|
}
|
|
34
|
-
export interface
|
|
35
|
-
edit: string;
|
|
36
|
-
dir: string;
|
|
37
|
-
receipt: EditedPartReceipt;
|
|
51
|
+
export interface EditedPixelCounts {
|
|
38
52
|
changed_px: number;
|
|
39
53
|
changed_counted_px: number;
|
|
40
54
|
changed_excluded_px: number;
|
|
@@ -49,8 +63,33 @@ export interface EditedPartProvenance {
|
|
|
49
63
|
*/
|
|
50
64
|
removed_opaque_regions?: EditedPartRemovedRegion[];
|
|
51
65
|
}
|
|
66
|
+
export interface EditedPartProvenance extends EditedPixelCounts {
|
|
67
|
+
edit: string;
|
|
68
|
+
dir: string;
|
|
69
|
+
receipt: EditedPartReceipt;
|
|
70
|
+
}
|
|
52
71
|
export interface EditedPartRemovedRegion { box: [number, number, number, number]; px: number }
|
|
53
72
|
|
|
73
|
+
export function editedPixelCounts(): EditedPixelCounts {
|
|
74
|
+
return { changed_px: 0, changed_counted_px: 0, changed_excluded_px: 0, removed_opaque_px: 0 };
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** One shared census for edits applied during or after assembly. */
|
|
78
|
+
export function editedPixelChanged(old: Raster, next: Raster, p: number, counts: EditedPixelCounts, removed: Uint8Array): boolean {
|
|
79
|
+
const offset = p * 4;
|
|
80
|
+
if (rgbaEqual(old.data, offset, next.data, offset)) return false;
|
|
81
|
+
counts.changed_px++;
|
|
82
|
+
if (next.data[offset + 3] > OPAQUE_ALPHA_ABOVE) counts.changed_counted_px++;
|
|
83
|
+
else {
|
|
84
|
+
counts.changed_excluded_px++;
|
|
85
|
+
if (old.data[offset + 3] > OPAQUE_ALPHA_ABOVE) {
|
|
86
|
+
counts.removed_opaque_px++;
|
|
87
|
+
removed[p] = 1;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
return true;
|
|
91
|
+
}
|
|
92
|
+
|
|
54
93
|
/** 8-connected regions of a part-sized 0/1 mask, ordered as `removed_opaque_regions` requires. */
|
|
55
94
|
export function removedOpaqueRegions(removed: Uint8Array, width: number, height: number): EditedPartRemovedRegion[] {
|
|
56
95
|
const seen = new Uint8Array(removed.length), out: EditedPartRemovedRegion[] = [];
|
|
@@ -107,6 +146,13 @@ export interface EditedPartContext {
|
|
|
107
146
|
const AT = 'config.assemble.edited_parts';
|
|
108
147
|
const sha = (bytes: Uint8Array): string => createHash('sha256').update(bytes).digest('hex');
|
|
109
148
|
|
|
149
|
+
export function decodeEditedPart(bytes: Uint8Array, receipt: EditedPartReceipt): { image: Raster } | { kind: 'hash' | 'decode'; detail: string } {
|
|
150
|
+
const found = sha(bytes);
|
|
151
|
+
if (found !== receipt.sha256) return { kind: 'hash', detail: `file sha256 is ${found}; receipt sha256 ${receipt.sha256} is required` };
|
|
152
|
+
try { return { image: decodePngBytes(bytes, receipt.file) }; }
|
|
153
|
+
catch (error) { return { kind: 'decode', detail: `file "${receipt.file}" is not a decodable PNG: ${(error as Error).message.split('\n')[0]}` }; }
|
|
154
|
+
}
|
|
155
|
+
|
|
110
156
|
/** Read once: validation, decoding and final emission all use these exact bytes. */
|
|
111
157
|
export function readEditedParts(spec: EditedParts | undefined, configPath: string, plan: ReadonlyArray<readonly [string, string, string]>): VerifiedEditedPart[] {
|
|
112
158
|
if (spec === undefined) return [];
|
|
@@ -121,13 +167,9 @@ export function readEditedParts(spec: EditedParts | undefined, configPath: strin
|
|
|
121
167
|
let bytes: Uint8Array;
|
|
122
168
|
try { bytes = new Uint8Array(readFileSync(path)); }
|
|
123
169
|
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; }
|
|
124
|
-
const
|
|
125
|
-
if (
|
|
126
|
-
|
|
127
|
-
continue;
|
|
128
|
-
}
|
|
129
|
-
try { out.push({ index, dir: spec.dir, receipt, bytes, image: decodePngBytes(bytes, receipt.file) }); }
|
|
130
|
-
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]}` }); }
|
|
170
|
+
const decoded = decodeEditedPart(bytes, receipt);
|
|
171
|
+
if ('image' in decoded) out.push({ index, dir: spec.dir, receipt, bytes, image: decoded.image });
|
|
172
|
+
else problems.push({ code: decoded.kind === 'hash' ? 'ASSEMBLE_EDITED_PART_SHA256' : 'ASSEMBLE_EDITED_PART_DECODES', object, detail: decoded.detail });
|
|
131
173
|
}
|
|
132
174
|
refuseIfAny(problems);
|
|
133
175
|
return out;
|
|
@@ -191,8 +233,7 @@ export function replaceEditedParts(
|
|
|
191
233
|
let id = map.edits.indexOf(name) + 1;
|
|
192
234
|
if (id === 0) { map.edits.push(name); id = map.edits.length; }
|
|
193
235
|
const metadata: EditedPartProvenance = { edit: name, dir: edit.dir,
|
|
194
|
-
receipt: orderedEditedPartReceipt(edit.receipt),
|
|
195
|
-
changed_px: 0, changed_counted_px: 0, changed_excluded_px: 0, removed_opaque_px: 0 };
|
|
236
|
+
receipt: orderedEditedPartReceipt(edit.receipt), ...editedPixelCounts() };
|
|
196
237
|
const next: PartStageMap = { name: stage.name, x: stage.x, y: stage.y, w: stage.w, h: stage.h,
|
|
197
238
|
excluded_px: 0, runs: [], pre_seam_writer_runs: [], edited_part: metadata };
|
|
198
239
|
const provenance: PixelProvenance = { unchanged_layer_px: 0, hand_px: 0, automatic_px: 0, edits: [], automatic: [],
|
|
@@ -206,14 +247,9 @@ export function replaceEditedParts(
|
|
|
206
247
|
const baseline = context.baseline;
|
|
207
248
|
for (let p = 0; p < old.width * old.height; p++) {
|
|
208
249
|
const offset = p * 4, prior = previous(), priorSeam = preSeam();
|
|
209
|
-
const changed =
|
|
250
|
+
const changed = editedPixelChanged(old, edit.image, p, metadata, removed);
|
|
210
251
|
const counted = edit.image.data[offset + 3] > OPAQUE_ALPHA_ABOVE;
|
|
211
252
|
if (!changed && counted) visibility?.copy(edit.image, p, old);
|
|
212
|
-
if (changed) {
|
|
213
|
-
metadata.changed_px++;
|
|
214
|
-
if (counted) metadata.changed_counted_px++; else metadata.changed_excluded_px++;
|
|
215
|
-
}
|
|
216
|
-
if (old.data[offset + 3] > OPAQUE_ALPHA_ABOVE && !counted) { metadata.removed_opaque_px++; removed[p] = 1; }
|
|
217
253
|
if (!counted) { next.excluded_px++; append(next.runs, EXCLUDED_PIXEL); append(next.pre_seam_writer_runs, EXCLUDED_PIXEL); continue; }
|
|
218
254
|
opaque++;
|
|
219
255
|
const x = record.x + p % record.w, y = record.y + Math.floor(p / record.w);
|
package/src/parts.ts
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { assemblyFieldDigest, isSplitTakeMetadataField } from './assembly-reading.ts';
|
|
2
|
-
import { compareRemovedRegions,
|
|
3
|
-
import { parseReceiptProducer, receiptText } from './receiptproducer.ts';
|
|
2
|
+
import { compareRemovedRegions, editedPartReceiptProblem, orderedEditedPartReceipt, type EditedPartRemovedRegion } from './editedparts.ts';
|
|
4
3
|
import { takenSourceProblems, type TakenLayerSource } from './takesource.ts';
|
|
5
4
|
import { AUTOMATIC_WRITERS, provenanceAddsUp, type PixelProvenance, type CutOwnership } from './provenance.ts';
|
|
6
5
|
import { baseAnchorProblems, orderedBaseAnchor, type BaseAnchor } from './baseanchor.ts';
|
|
6
|
+
import { REPLACEMENT_RECORD_PATH } from './replacementrecord.ts';
|
|
7
7
|
import { partDepthProblems, type PartDepthReference } from './depthsheets.ts';
|
|
8
8
|
/**
|
|
9
9
|
* The output contract of the assemble stage: `parts.json`, one record per
|
|
@@ -155,6 +155,8 @@ export interface PartRecord {
|
|
|
155
155
|
w: number;
|
|
156
156
|
h: number;
|
|
157
157
|
opaque_px: number;
|
|
158
|
+
/** On a post-assembly replacement, the original scope of the mandatory assembly counters and authored-unit provenance. */
|
|
159
|
+
assembly_opaque_px?: number;
|
|
158
160
|
source_visibility?: PartSourceVisibility;
|
|
159
161
|
source_state_map?: PartSourceStateMap;
|
|
160
162
|
/** With `source_visibility` only: every later part this one overlaps, in draw order (issue #1474). */
|
|
@@ -464,6 +466,8 @@ export interface AssemblyConfigRecord {
|
|
|
464
466
|
|
|
465
467
|
export interface PartsFile {
|
|
466
468
|
assembly_config?: AssemblyConfigRecord;
|
|
469
|
+
/** Current derivation attestation, relative to the directory holding parts.json. */
|
|
470
|
+
replacement_record?: string;
|
|
467
471
|
/** Optional on legacy packages; binds the opaque RGB raster assemble actually read. */
|
|
468
472
|
painting_in_rig?: PaintingInRig;
|
|
469
473
|
/** Structural moves, independent of per-pixel value equality. */
|
|
@@ -522,8 +526,8 @@ export interface SceneRecord {
|
|
|
522
526
|
figure_mask: string;
|
|
523
527
|
}
|
|
524
528
|
|
|
525
|
-
const TOP_KEYS = ['assembly_config', 'painting_in_rig', 'rig_size', 'scale_rig_per_source', 'parts', 'ghost_px', 'recomposite', 'scene', 'occluder_plates', 'occluder_grow', 'occluder_guard', 'single_run_pad', 'alternates', 'motion_seams', 'cut_ownership'] as const;
|
|
526
|
-
const REQUIRED_TOP_KEYS = TOP_KEYS.filter((k) => k !== 'assembly_config' && k !== 'painting_in_rig' && k !== 'recomposite' && k !== 'scene' && k !== 'single_run_pad' && k !== 'occluder_plates' && k !== 'occluder_grow' && k !== 'occluder_guard' && k !== 'alternates' && k !== 'motion_seams' && k !== 'cut_ownership');
|
|
529
|
+
const TOP_KEYS = ['assembly_config', 'painting_in_rig', 'rig_size', 'scale_rig_per_source', 'parts', 'ghost_px', 'recomposite', 'scene', 'occluder_plates', 'occluder_grow', 'occluder_guard', 'single_run_pad', 'alternates', 'motion_seams', 'cut_ownership', 'replacement_record'] as const;
|
|
530
|
+
const REQUIRED_TOP_KEYS = TOP_KEYS.filter((k) => k !== 'assembly_config' && k !== 'painting_in_rig' && k !== 'recomposite' && k !== 'scene' && k !== 'single_run_pad' && k !== 'occluder_plates' && k !== 'occluder_grow' && k !== 'occluder_guard' && k !== 'alternates' && k !== 'motion_seams' && k !== 'cut_ownership' && k !== 'replacement_record');
|
|
527
531
|
export const OCCLUDER_PLATE_KEYS = ['receipt', 'receipt_sha256', 'occluder_sha256', 'painting_sha256', 'output_sha256', 'mask_sha256'] as const;
|
|
528
532
|
export const OCCLUDER_GROW_KEYS = ['occluder', 'image', 'grow', 'covered_px_before', 'covered_px_after'] as const;
|
|
529
533
|
export const OCCLUDER_GUARD_KEYS = ['occluder', 'image', 'guard', 'guarded_px_before', 'guarded_px_after'] as const;
|
|
@@ -543,6 +547,7 @@ export const PART_KEYS = [
|
|
|
543
547
|
'w',
|
|
544
548
|
'h',
|
|
545
549
|
'opaque_px',
|
|
550
|
+
'assembly_opaque_px',
|
|
546
551
|
'source_visibility',
|
|
547
552
|
'source_state_map',
|
|
548
553
|
'source_overlaps',
|
|
@@ -569,7 +574,7 @@ const LIMB_KEY = 'limb';
|
|
|
569
574
|
const COUNT_KEYS = PART_KEYS.slice(2).filter((k) => k !== FRINGE_KEY && k !== CUT_FROM_KEY && k !== LIMB_KEY && k !== 'depth' && k !== 'provenance' && k !== 'taken_layers' && k !== 'source_visibility' && k !== 'source_state_map' && k !== 'source_overlaps') as ReadonlyArray<(typeof PART_KEYS)[number]>;
|
|
570
575
|
/** The port's own counts: all three or none (none = a record the reference wrote). */
|
|
571
576
|
export const VISIBILITY_KEYS = ['visible_px', 'occluded_px', 'visible_not_projected_px'] as const;
|
|
572
|
-
const REQUIRED_KEYS = PART_KEYS.filter((k) => k !== 'painting_extension_px' && !(VISIBILITY_KEYS as readonly string[]).includes(k) && k !== FRINGE_KEY && k !== CUT_FROM_KEY && k !== LIMB_KEY && k !== 'depth' && k !== 'provenance' && k !== 'taken_layers' && k !== 'source_visibility' && k !== 'source_state_map' && k !== 'source_overlaps');
|
|
577
|
+
const REQUIRED_KEYS = PART_KEYS.filter((k) => k !== 'assembly_opaque_px' && k !== 'painting_extension_px' && !(VISIBILITY_KEYS as readonly string[]).includes(k) && k !== FRINGE_KEY && k !== CUT_FROM_KEY && k !== LIMB_KEY && k !== 'depth' && k !== 'provenance' && k !== 'taken_layers' && k !== 'source_visibility' && k !== 'source_state_map' && k !== 'source_overlaps');
|
|
573
578
|
|
|
574
579
|
/** Where a part came from: a See-through run and a v3 tag or an author-made layer's `author:<label>` (issue #256), or the painting itself for a patch. */
|
|
575
580
|
export type From = { run: 'full' | 'head'; tag: string } | { run: 'painting'; patch: string };
|
|
@@ -620,14 +625,6 @@ function editedRemovedRegions(value: unknown, removed: number, w: unknown, h: un
|
|
|
620
625
|
if (sum !== removed) fail('PARTS_COUNTS_ADD_UP', object, `px sum to ${sum}; removed_opaque_px ${removed} is required`);
|
|
621
626
|
}
|
|
622
627
|
|
|
623
|
-
function validEditedPartAuthor(receipt: EditedPartReceipt): boolean {
|
|
624
|
-
const keys = Object.keys(receipt).sort().join(',');
|
|
625
|
-
if (keys === 'editor,file,from_sha256,part,sha256') return receiptText(receipt.editor);
|
|
626
|
-
if (keys !== 'file,from_sha256,part,producer,sha256') return false;
|
|
627
|
-
try { parseReceiptProducer(receipt.producer, 'edited part producer'); return true; }
|
|
628
|
-
catch { return false; }
|
|
629
|
-
}
|
|
630
|
-
|
|
631
628
|
const OWNERSHIP_KEYS = ['edit', 'from', 'into', 'moved_in_opaque_px', 'retained_band_opaque_px', 'cleared_opaque_px', 'under_filled_px', 'under_filled_opaque_px', 'net_cleared_opaque_px', 'under_plate'] as const;
|
|
632
629
|
const REQUIRED_OWNERSHIP_KEYS = OWNERSHIP_KEYS.filter((k) => k !== 'under_plate');
|
|
633
630
|
function orderedOwnership(rows: readonly CutOwnership[]): Array<Record<string, unknown>> {
|
|
@@ -766,6 +763,7 @@ export function serializeParts(file: PartsFile): string {
|
|
|
766
763
|
} }),
|
|
767
764
|
parts: serializePartList(file.parts),
|
|
768
765
|
...(file.assembly_config === undefined ? {} : { assembly_config: { sha256: file.assembly_config.sha256, fields: file.assembly_config.fields.map(({ name, sha256 }) => ({ name, sha256 })) } }),
|
|
766
|
+
...(file.replacement_record === undefined ? {} : { replacement_record: file.replacement_record }),
|
|
769
767
|
...(file.cut_ownership === undefined ? {} : { cut_ownership: orderedOwnership(file.cut_ownership) }),
|
|
770
768
|
...(file.motion_seams === undefined ? {} : { motion_seams: file.motion_seams.map(({ part, neighbour }) => ({ part, neighbour })) }),
|
|
771
769
|
ghost_px: Object.fromEntries(Object.keys(file.ghost_px).sort().map((k) => [k, file.ghost_px[k]])),
|
|
@@ -837,7 +835,10 @@ function paintingImageReference(painting: PaintingInRig): PartsFileReference {
|
|
|
837
835
|
|
|
838
836
|
/** Read the manifest without opening, hashing or decoding its PNG references. */
|
|
839
837
|
export function partsFileReferences(dir: string): PartsFileReference[] {
|
|
840
|
-
|
|
838
|
+
return declaredPartsFiles(readPartsManifest(join(dir, 'parts.json')));
|
|
839
|
+
}
|
|
840
|
+
|
|
841
|
+
export function declaredPartsFiles(file: PartsFile): PartsFileReference[] {
|
|
841
842
|
const references: PartsFileReference[] = [];
|
|
842
843
|
const addScene = (scene: SceneRecord | undefined): void => {
|
|
843
844
|
if (scene !== undefined) references.push({ path: scene.figure_mask, role: 'figure_mask' });
|
|
@@ -1056,10 +1057,7 @@ function checkProvenance(raw: unknown, opaque: unknown, object: string, fail: (c
|
|
|
1056
1057
|
const valid = e !== null && e !== undefined && typeof e === 'object' && !Array.isArray(e) && [keys, withRegions].includes(Object.keys(e).sort().join(',')) &&
|
|
1057
1058
|
typeof e.edit === 'string' && /^edited_parts\[\d+\]$/.test(e.edit) && relativePath(e.dir) &&
|
|
1058
1059
|
[e.changed_px, e.changed_counted_px, e.changed_excluded_px, e.removed_opaque_px].every(count) &&
|
|
1059
|
-
e.receipt
|
|
1060
|
-
validEditedPartAuthor(e.receipt) &&
|
|
1061
|
-
nonempty(e.receipt.part) && e.receipt.part === identity?.name && relativePath(e.receipt.file) &&
|
|
1062
|
-
[e.receipt.sha256, e.receipt.from_sha256].every(s => typeof s === 'string' && /^[a-f0-9]{64}$/.test(s));
|
|
1060
|
+
editedPartReceiptProblem(e.receipt) === undefined && e.receipt.part === identity?.name;
|
|
1063
1061
|
if (!valid) fail('PARTS_FIELD_TYPE', object + ' edited_part', 'requires edited_parts[i], a config-relative dir, a receipt with the enclosing part name, dir-relative file, two lowercase sha256 hashes and either editor or producer, and four nonnegative safe integer change counts');
|
|
1064
1062
|
else {
|
|
1065
1063
|
const area = typeof identity?.w === 'number' && typeof identity.h === 'number' ? identity.w * identity.h : NaN;
|
|
@@ -1097,6 +1095,9 @@ function checkParts(raw: unknown, path: string): PartsFile {
|
|
|
1097
1095
|
const o = raw as Record<string, unknown>;
|
|
1098
1096
|
for (const k of Object.keys(o)) if (!(TOP_KEYS as readonly string[]).includes(k)) fail('PARTS_KEY_KNOWN', `${path} key "${k}"`, `is not a parts.json field; known: ${TOP_KEYS.join(', ')}`);
|
|
1099
1097
|
for (const k of REQUIRED_TOP_KEYS) if (!(k in o)) fail('PARTS_FIELD_PRESENT', `${path} field "${k}"`, 'is absent and required');
|
|
1098
|
+
if ('replacement_record' in o && (typeof o.replacement_record !== 'string' || !REPLACEMENT_RECORD_PATH.test(o.replacement_record))) {
|
|
1099
|
+
fail('PARTS_FIELD_TYPE', `${path} field "replacement_record"`, 'requires a .parts-replacements/<lowercase sha256>.json path');
|
|
1100
|
+
}
|
|
1100
1101
|
if ('assembly_config' in o) {
|
|
1101
1102
|
const value = o.assembly_config as Partial<AssemblyConfigRecord> | null;
|
|
1102
1103
|
const digest = (input: unknown): input is string => typeof input === 'string' && /^[a-f0-9]{64}$/.test(input);
|
|
@@ -1171,7 +1172,12 @@ function checkParts(raw: unknown, path: string): PartsFile {
|
|
|
1171
1172
|
if (k in r && !(Number.isInteger(r[k]) && (r[k] as number) >= 0)) fail('PARTS_FIELD_TYPE', `${label} field "${k}"`, `is ${show(r[k])}; a non-negative integer is required`);
|
|
1172
1173
|
}
|
|
1173
1174
|
const count = (k: string): number | null => (Number.isInteger(r[k]) && (r[k] as number) >= 0 ? (r[k] as number) : null);
|
|
1174
|
-
|
|
1175
|
+
const assemblyOpaque = count('assembly_opaque_px');
|
|
1176
|
+
if ('assembly_opaque_px' in r && (!('replacement_record' in o) || assemblyOpaque === null || !Number.isSafeInteger(assemblyOpaque) ||
|
|
1177
|
+
(typeof r.w === 'number' && typeof r.h === 'number' && assemblyOpaque > r.w * r.h))) {
|
|
1178
|
+
fail('PARTS_FIELD_TYPE', label + ' assembly_opaque_px', 'requires a replacement record and an original opaque count within the crop');
|
|
1179
|
+
}
|
|
1180
|
+
if ('provenance' in r) checkProvenance(r.provenance, assemblyOpaque ?? r.opaque_px, label + ' provenance', fail, 'depth' in r, { name: r.name, w: r.w, h: r.h });
|
|
1175
1181
|
checkPaintingExtensionCount(r, label, fail);
|
|
1176
1182
|
if ('source_visibility' in r) checkSourceVisibility(r.source_visibility, r.opaque_px, label, fail);
|
|
1177
1183
|
if ('source_state_map' in r) checkSourceStateMap(r, label, fail);
|
|
@@ -1183,10 +1189,10 @@ function checkParts(raw: unknown, path: string): PartsFile {
|
|
|
1183
1189
|
}
|
|
1184
1190
|
if (from !== null && from.run === 'painting' && op !== null) {
|
|
1185
1191
|
// A patch is 100 % source: every count is opaque_px or 0 (module doc).
|
|
1186
|
-
const whole = ['visible_px', 'projected_core_px', 'source_px_taken'].filter((k) => k in r && count(k) !== op);
|
|
1192
|
+
const whole = ['visible_px', 'projected_core_px', 'source_px_taken'].filter((k) => k in r && count(k) !== (k === 'visible_px' ? op : assemblyOpaque ?? op));
|
|
1187
1193
|
const none = ['occluded_px', 'visible_not_projected_px', 'refused_drift_px', 'merged_px'].filter((k) => k in r && count(k) !== 0);
|
|
1188
1194
|
if (whole.length > 0 || none.length > 0) {
|
|
1189
|
-
const said = [...whole.map((k) => `${k} ${show(r[k])} (opaque_px ${op} required)`), ...none.map((k) => `${k} ${show(r[k])} (0 required)`)].join(', ');
|
|
1195
|
+
const said = [...whole.map((k) => `${k} ${show(r[k])} (${assemblyOpaque === null || k === 'visible_px' ? 'opaque_px' : 'assembly_opaque_px'} ${k === 'visible_px' ? op : assemblyOpaque ?? op} required)`), ...none.map((k) => `${k} ${show(r[k])} (0 required)`)].join(', ');
|
|
1190
1196
|
fail('PARTS_COUNTS_ADD_UP', `${label}`, `is a painting patch (${String(r.from)}), which is 100 % source; ${said}`);
|
|
1191
1197
|
}
|
|
1192
1198
|
}
|
package/src/partscheck.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/** Assemble-output integrity and explicit unmeasured quality classes. No rig or renderer. */
|
|
2
2
|
import { createHash } from 'node:crypto';
|
|
3
|
-
import { existsSync, lstatSync, mkdirSync, readFileSync,
|
|
3
|
+
import { existsSync, lstatSync, mkdirSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs';
|
|
4
4
|
import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
|
|
5
5
|
import { failLine, PartsError, type Problem } from './errors.ts';
|
|
6
6
|
import { FIGURE_MASK_FILE, orderedSourceOverlap, orderedSourceVisibility, partImageReference, partsFileReferences, readParts, type PartsFile, type PartSourceOverlap, type PartSourceVisibility } from './parts.ts';
|
|
@@ -8,6 +8,7 @@ import { readPng } from './raster/png.ts';
|
|
|
8
8
|
import { RasterError } from './raster/types.ts';
|
|
9
9
|
import { NotAPngError } from '@rig-c/core/png';
|
|
10
10
|
import { SOURCE_COVER_SPEC, sourceCoverReport } from './sourcecover.ts';
|
|
11
|
+
import { readRegularFile, walkPartsFiles } from './partsfiles.ts';
|
|
11
12
|
|
|
12
13
|
export const PARTS_CHECK_SPEC = 'rig-parts-parts-check/1';
|
|
13
14
|
export const PARTS_CHECK_FILE = 'parts-check.json';
|
|
@@ -182,7 +183,7 @@ export function checkPartsStage(input: string, output: string, log: (line: strin
|
|
|
182
183
|
try {
|
|
183
184
|
const manifestPath = join(home, 'parts.json');
|
|
184
185
|
if (lstatSync(manifestPath).isFile()) {
|
|
185
|
-
const bytes =
|
|
186
|
+
const bytes = readRegularFile(manifestPath);
|
|
186
187
|
initialManifestHash = createHash('sha256').update(bytes).digest('hex');
|
|
187
188
|
const raw: unknown = JSON.parse(bytes.toString('utf8'));
|
|
188
189
|
if (object(raw)) {
|
|
@@ -198,27 +199,16 @@ export function checkPartsStage(input: string, output: string, log: (line: strin
|
|
|
198
199
|
}
|
|
199
200
|
const inventory = (reportErrors: boolean): PartsCheckInput[] => {
|
|
200
201
|
const rows = new Map<string, PartsCheckInput>();
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
} else {
|
|
212
|
-
rows.set(name, { path: name, status: 'read', sha256: createHash('sha256').update(readFileSync(path)).digest('hex') });
|
|
213
|
-
}
|
|
214
|
-
} catch (error) {
|
|
215
|
-
if (!ioError(error)) throw error;
|
|
216
|
-
const missing = 'code' in error && error.code === 'ENOENT';
|
|
217
|
-
rows.set(name, { path: name, status: missing ? 'missing' : 'unreadable', sha256: null });
|
|
218
|
-
if (reportErrors) refuse('PARTS_CHECK_INPUT_READ', name, clean(error.message), 'readable regular input', 'input inventory could not read this object');
|
|
219
|
-
}
|
|
220
|
-
};
|
|
221
|
-
visit('.');
|
|
202
|
+
walkPartsFiles(home, ignoredPaths, (name, path) => {
|
|
203
|
+
rows.set(name, { path: name, status: 'read', sha256: createHash('sha256').update(readRegularFile(path)).digest('hex') });
|
|
204
|
+
}, (name, error) => {
|
|
205
|
+
const missing = error instanceof Error && 'code' in error && error.code === 'ENOENT';
|
|
206
|
+
rows.set(name, { path: name, status: missing ? 'missing' : 'unreadable', sha256: null });
|
|
207
|
+
if (!reportErrors) return;
|
|
208
|
+
if (error === undefined) refuse('PARTS_CHECK_INPUT_READ', name, 'non-regular input', 'regular file or directory', 'input links and special files require a regular-file scratch copy');
|
|
209
|
+
else if (ioError(error)) refuse('PARTS_CHECK_INPUT_READ', name, clean(error.message), 'readable regular input', 'input inventory could not read this object');
|
|
210
|
+
else throw error;
|
|
211
|
+
});
|
|
222
212
|
for (const name of [...requiredPaths, ...optionalPaths]) if (!rows.has(name)) {
|
|
223
213
|
rows.set(name, { path: name, status: optionalPaths.has(name) ? 'absent' : 'missing', sha256: null });
|
|
224
214
|
}
|