rig-parts 2.68.0 → 2.69.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/check.ts CHANGED
@@ -10325,6 +10325,13 @@ export interface SliderStretchPeak {
10325
10325
  triangle: number;
10326
10326
  vertices: StretchAt['vertices'];
10327
10327
  edge: StretchAt['edge'];
10328
+ area_share: number;
10329
+ on_hull: boolean;
10330
+ }
10331
+
10332
+ export interface SliderStretchPassingDial {
10333
+ lower: number | null;
10334
+ upper: number | null;
10328
10335
  }
10329
10336
 
10330
10337
  export interface SliderStretchRow {
@@ -10333,6 +10340,7 @@ export interface SliderStretchRow {
10333
10340
  status: 'PASS' | 'FAIL' | 'SKIP';
10334
10341
  range: [number, number] | null;
10335
10342
  sample_count: number;
10343
+ last_passing_dial?: SliderStretchPassingDial;
10336
10344
  peak?: SliderStretchPeak;
10337
10345
  reason?: string;
10338
10346
  }
@@ -10411,11 +10419,54 @@ function sliderMeshGeometry(mesh: AttachmentRest, pose: AttachmentPose): string
10411
10419
  }
10412
10420
  }
10413
10421
 
10422
+ interface SliderMeshFacts {
10423
+ triangle: (index: number) => { area_share: number; on_hull: boolean };
10424
+ }
10425
+
10426
+ function sliderMeshFacts(mesh: MeshRest): SliderMeshFacts | null {
10427
+ const { vertices: v, triangles: t } = mesh;
10428
+ const twiceAreas: number[] = [];
10429
+ const edgeUses = new Map<string, number>();
10430
+ const edgeKey = (p: number, q: number) => `${Math.min(p, q)},${Math.max(p, q)}`;
10431
+ for (let i = 0; i < t.length; i += 3) {
10432
+ const a = t[i], b = t[i + 1], c = t[i + 2];
10433
+ const twice = Math.abs((v[2 * b] - v[2 * a]) * (v[2 * c + 1] - v[2 * a + 1]) - (v[2 * b + 1] - v[2 * a + 1]) * (v[2 * c] - v[2 * a]));
10434
+ if (!Number.isFinite(twice)) return null;
10435
+ twiceAreas.push(twice);
10436
+ for (const key of new Set([edgeKey(a, b), edgeKey(b, c), edgeKey(c, a)])) {
10437
+ edgeUses.set(key, (edgeUses.get(key) ?? 0) + 1);
10438
+ }
10439
+ }
10440
+ const totalTwiceArea = twiceAreas.reduce((sum, area) => sum + area, 0);
10441
+ if (!Number.isFinite(totalTwiceArea) || totalTwiceArea <= 0) return null;
10442
+ return {
10443
+ triangle: index => {
10444
+ const i = 3 * index;
10445
+ const a = t[i], b = t[i + 1], c = t[i + 2];
10446
+ return {
10447
+ area_share: round6(twiceAreas[index] / totalTwiceArea),
10448
+ on_hull: [edgeKey(a, b), edgeKey(b, c), edgeKey(c, a)].some(key => edgeUses.get(key) === 1),
10449
+ };
10450
+ },
10451
+ };
10452
+ }
10453
+
10454
+ function sliderLastPassingDial(dials: readonly number[], passes: (sample: number) => boolean): SliderStretchPassingDial {
10455
+ const mid = (dials.length - 1) / 2;
10456
+ if (!passes(mid)) return { lower: null, upper: null };
10457
+ const norm = (d: number) => d === 0 ? 0 : d;
10458
+ let lower = norm(dials[mid]);
10459
+ for (let i = mid - 1; i >= 0 && passes(i); i--) lower = norm(dials[i]);
10460
+ let upper = norm(dials[mid]);
10461
+ for (let i = mid + 1; i < dials.length && passes(i); i++) upper = norm(dials[i]);
10462
+ return { lower, upper };
10463
+ }
10464
+
10414
10465
  function measureSliderStretch(api: OfficialRenderer, candidate: Candidate, binding: SliderStretchBinding, range: [number, number], provide: SliderStretchProvider): SliderStretchRow {
10415
10466
  const dials = sliderDialGrid(range);
10416
- const base = { slider: binding.slider, clip: binding.clip, range };
10417
10467
  const poses: SliderPose[] = [];
10418
10468
  const missed = new Set<number>();
10469
+ const sampleExceeds = new Set<number>();
10419
10470
  let incomplete: { sample: number; reason: string } | undefined;
10420
10471
  const miss = (sample: number, dial: number, detail: string) => {
10421
10472
  missed.add(sample);
@@ -10453,6 +10504,7 @@ function measureSliderStretch(api: OfficialRenderer, candidate: Candidate, bindi
10453
10504
  miss(sample, dial, `setup geometry: ${err.message}`);
10454
10505
  }
10455
10506
  const byAttachment = new Map(rest.map(mesh => [JSON.stringify([mesh.slot, mesh.attachment]), mesh]));
10507
+ const byFacts = new Map<string, SliderMeshFacts | null>();
10456
10508
  for (const { sample, dial, time, attachments } of poses) {
10457
10509
  const meshes: MeshRest[] = [];
10458
10510
  const seen = new Set<string>();
@@ -10472,7 +10524,9 @@ function measureSliderStretch(api: OfficialRenderer, candidate: Candidate, bindi
10472
10524
  else meshes.push(mesh);
10473
10525
  }
10474
10526
  let measurable = false;
10475
- for (const { mesh, peak: hit } of measureTextureStretch(meshes, [{ index: sample, attachments }])) {
10527
+ const figures = measureTextureStretch(meshes, [{ index: sample, attachments }]);
10528
+ for (const [meshIndex, { mesh, peak: hit }] of figures.entries()) {
10529
+ const restMesh = meshes[meshIndex];
10476
10530
  const object = `mesh ${JSON.stringify(mesh.slot)} attachment ${JSON.stringify(mesh.attachment)}`;
10477
10531
  const degenerate = mesh.degenerate[0];
10478
10532
  if (degenerate !== undefined) unmeasured(`${object} triangle ${degenerate.triangle} edge ${degenerate.edge.join('-')} has zero setup length`);
@@ -10482,22 +10536,45 @@ function measureSliderStretch(api: OfficialRenderer, candidate: Candidate, bindi
10482
10536
  unmeasured(`${object} triangle ${at.triangle} edge ${at.edge.join('-')} has no finite stretch severity (ratio ${at.ratio})`);
10483
10537
  continue;
10484
10538
  }
10539
+ const key = JSON.stringify([restMesh.slot, restMesh.attachment]);
10540
+ let facts = byFacts.get(key);
10541
+ if (facts === undefined) {
10542
+ facts = sliderMeshFacts(restMesh);
10543
+ byFacts.set(key, facts);
10544
+ }
10545
+ if (facts === null) {
10546
+ unmeasured(`${object} has zero or non-finite rest area`);
10547
+ continue;
10548
+ }
10485
10549
  measurable = true;
10486
10550
  exceeds ||= hit.exceeds;
10551
+ if (hit.exceeds) sampleExceeds.add(sample);
10487
10552
  if (peak !== undefined && raw <= worstSeverity) continue;
10488
10553
  worstSeverity = raw;
10489
10554
  const frame = Math.round(time * IDLE_FPS);
10555
+ const { area_share, on_hull } = facts.triangle(at.triangle);
10490
10556
  peak = {
10491
- severity: round6(raw), gate: rounded, dial_value: dial, sample,
10557
+ severity: round6(raw), gate: rounded, dial_value: dial === 0 ? 0 : dial, sample,
10492
10558
  clip_frame: Number.isSafeInteger(frame) && Math.abs(time - frame / IDLE_FPS) <= TIME_SLACK ? frame : null,
10493
10559
  clip_time_s: time, slot: mesh.slot, attachment: mesh.attachment, triangle: at.triangle, vertices: at.vertices, edge: at.edge,
10560
+ area_share, on_hull,
10494
10561
  };
10495
10562
  }
10496
10563
  if (!measurable) unmeasured('no posed mesh triangle edge could be measured');
10497
10564
  }
10498
10565
  }
10499
- return { ...base, status: incomplete !== undefined || exceeds ? 'FAIL' : 'PASS', sample_count: dials.length - missed.size,
10500
- ...(peak === undefined ? {} : { peak }), ...(incomplete === undefined ? {} : { reason: incomplete.reason }) };
10566
+ return {
10567
+ slider: binding.slider,
10568
+ clip: binding.clip,
10569
+ status: incomplete !== undefined || exceeds ? 'FAIL' : 'PASS',
10570
+ range,
10571
+ sample_count: dials.length - missed.size,
10572
+ ...(peak === undefined ? {} : {
10573
+ last_passing_dial: sliderLastPassingDial(dials, s => !missed.has(s) && !sampleExceeds.has(s)),
10574
+ peak,
10575
+ }),
10576
+ ...(incomplete === undefined ? {} : { reason: incomplete.reason }),
10577
+ };
10501
10578
  }
10502
10579
 
10503
10580
  /** Measure each slider binding on the pre-gated build. Stock check never votes these rows into its verdict. */
@@ -10507,22 +10584,22 @@ export function readSliderStretch(buildDir: string, bindings: readonly SliderStr
10507
10584
  let source: { api: OfficialRenderer; candidate: Candidate; provider: SliderStretchProvider } | { reason: string } | undefined;
10508
10585
  for (const binding of bindings) {
10509
10586
  const { slider, clip, bone, max } = binding;
10510
- const from = finiteSliderNumber(binding.from) ? binding.from : 0;
10587
+ const from = finiteSliderNumber(binding.from) ? (binding.from === 0 ? 0 : binding.from) : 0;
10511
10588
  const base = { slider, clip, range: null, sample_count: 0 };
10512
10589
  const bad = (['from', 'max'] as const).find(key => Object.hasOwn(binding, key) && !finiteSliderNumber(binding[key]));
10513
10590
  if (bad !== undefined) {
10514
10591
  rows.push({ ...base, status: 'FAIL', reason: `declared dial bound ${bad} is ${String(binding[bad])}; requires a finite number` });
10515
10592
  } else if (finiteSliderNumber(max) && from > max) {
10516
- rows.push({ ...base, status: 'FAIL', reason: `declared dial range [${from}, ${max}] is reversed; requires from <= max` });
10593
+ rows.push({ ...base, status: 'FAIL', reason: `declared dial range [${from}, ${max === 0 ? 0 : max}] is reversed; requires from <= max` });
10517
10594
  } else if (Object.hasOwn(binding, 'bone') && (typeof bone !== 'string' || bone.length === 0)) {
10518
10595
  rows.push({ ...base, status: 'FAIL', reason: `declared driving bone is ${String(bone)}; requires a bone name` });
10519
10596
  } else if (bone === undefined || !finiteSliderNumber(max)) {
10520
10597
  const reason = bone === undefined ? 'no declared dial range; the slider is time-driven' : 'no declared dial range; declare max to measure texture stretch';
10521
10598
  rows.push({ ...base, status: 'SKIP', reason });
10522
10599
  } else if (from === max) {
10523
- rows.push({ ...base, status: 'SKIP', range: [from, max], reason: `declared dial range [${from}, ${max}] has equal endpoints` });
10600
+ rows.push({ ...base, status: 'SKIP', range: [from, from], reason: `declared dial range [${from}, ${from}] has equal endpoints` });
10524
10601
  } else {
10525
- const range: [number, number] = [from, max];
10602
+ const range: [number, number] = [from, max === 0 ? 0 : max];
10526
10603
  if (source === undefined) {
10527
10604
  const api = officialRenderer();
10528
10605
  const skeleton = join(buildDir, 'skeleton.json'), atlas = join(buildDir, 'skeleton.atlas');
@@ -10564,15 +10641,23 @@ export function readSliderStretch(buildDir: string, bindings: readonly SliderStr
10564
10641
  };
10565
10642
  }
10566
10643
 
10644
+ function sliderPassingText(value: number | null, bound: number | undefined): string {
10645
+ if (value === null) return 'none (midpoint fails)';
10646
+ return value === bound ? `${value} (range end)` : String(value);
10647
+ }
10648
+
10567
10649
  export function sliderStretchLine(row: SliderStretchRow, advisory = false): string {
10568
10650
  const object = sliderStretchObject(row);
10569
- const { peak, range, reason, sample_count: samples } = row;
10651
+ const { last_passing_dial: reach, peak, range, reason, sample_count: samples } = row;
10570
10652
  const coverage = samples === SLIDER_STRETCH_SAMPLES ? String(samples) : `${samples} of ${SLIDER_STRETCH_SAMPLES}`;
10571
10653
  const grid = range === null || row.status === 'SKIP' ? '' : `${coverage} dial samples in [${range.join(', ')}]`;
10654
+ const reachClause = reach === undefined ? '' :
10655
+ `, last passing dial lower ${sliderPassingText(reach.lower, range?.[0])}, upper ${sliderPassingText(reach.upper, range?.[1])}`;
10572
10656
  const reading = peak === undefined ? grid :
10573
10657
  `peak ${peak.severity.toFixed(6)}x (gate ${peak.gate.toFixed(3)}x, limit ${TEXTURE_STRETCH_CEILING}x), ${grid}, ` +
10574
10658
  `dial ${peak.dial_value}, sample ${peak.sample}, clip frame ${peak.clip_frame ?? 'off-grid'} at ${peak.clip_time_s.toFixed(6)} s, ` +
10575
- `mesh ${JSON.stringify(peak.slot)} attachment ${JSON.stringify(peak.attachment)}, triangle ${peak.triangle} (vertices ${peak.vertices.join(' ')}), edge ${peak.edge.join('-')}`;
10659
+ `mesh ${JSON.stringify(peak.slot)} attachment ${JSON.stringify(peak.attachment)}, triangle ${peak.triangle} (vertices ${peak.vertices.join(' ')}), ` +
10660
+ `edge ${peak.edge.join('-')}, area share ${peak.area_share.toFixed(6)}, ${peak.on_hull ? 'hull' : 'interior'}${reachClause}`;
10576
10661
  const detail = [reading, reason].filter(Boolean).join('; ');
10577
10662
  if (row.status === 'FAIL' && !advisory) return failLine({ code: SLIDER_STRETCH_RULE, object, detail });
10578
10663
  const level = row.status === 'FAIL' ? 'WARN' : row.status;
@@ -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 { EditorReceipt } from './editreceipt.ts';
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 EditedPartProvenance {
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 found = sha(bytes);
125
- if (found !== receipt.sha256) {
126
- problems.push({ code: 'ASSEMBLE_EDITED_PART_SHA256', object, detail: `file sha256 is ${found}; receipt sha256 ${receipt.sha256} is required` });
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 = !rgbaEqual(old.data, offset, edit.image.data, offset);
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, orderedEditedPartReceipt, type EditedPartReceipt, type EditedPartRemovedRegion } from './editedparts.ts';
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
- const file = readPartsManifest(join(dir, 'parts.json'));
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 !== null && typeof e.receipt === 'object' && !Array.isArray(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
- if ('provenance' in r) checkProvenance(r.provenance, r.opaque_px, label + ' provenance', fail, 'depth' in r, { name: r.name, w: r.w, h: r.h });
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, readdirSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs';
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 = readFileSync(manifestPath);
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
- const visit = (name: string): void => {
202
- if (ignoredPaths.has(name)) return;
203
- const path = join(home, name);
204
- try {
205
- const stat = lstatSync(path);
206
- if (stat.isSymbolicLink() || (!stat.isDirectory() && !stat.isFile())) {
207
- rows.set(name, { path: name, status: 'unreadable', sha256: null });
208
- if (reportErrors) 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 (stat.isDirectory()) {
210
- for (const entry of readdirSync(path).sort()) visit(name === '.' ? entry : `${name}/${entry}`);
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
  }
@@ -0,0 +1,62 @@
1
+ /** Regular-file paths and byte inventories for assembled parts directories. */
2
+ import { createHash } from 'node:crypto';
3
+ import { closeSync, constants, fstatSync, lstatSync, openSync, readFileSync, readdirSync } from 'node:fs';
4
+ import { isAbsolute, join, relative, sep } from 'node:path';
5
+
6
+ export function withinPartsPath(parent: string, path: string): boolean {
7
+ const rel = relative(parent, path);
8
+ return rel === '' || (!isAbsolute(rel) && rel !== '..' && !rel.startsWith(`..${sep}`));
9
+ }
10
+
11
+ export function inventoryPath(path: string): boolean {
12
+ return !/[\\\0]/.test(path) && path.split('/').every(segment => segment !== '' && segment !== '.' && segment !== '..') &&
13
+ !/^[A-Za-z]:/.test(path);
14
+ }
15
+
16
+ export function readRegularFile(path: string): Buffer {
17
+ const fd = openSync(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0));
18
+ try {
19
+ if (!fstatSync(fd).isFile()) throw Object.assign(new Error('input is not a regular file'), { code: 'EINVAL' });
20
+ return readFileSync(fd);
21
+ } finally {
22
+ closeSync(fd);
23
+ }
24
+ }
25
+
26
+ /** Never descend through symlinks or read special files. Paths are relative, including in refusals. */
27
+ export function walkPartsFiles(
28
+ home: string,
29
+ ignore: ReadonlySet<string>,
30
+ file: (name: string, path: string) => void,
31
+ invalid: (name: string, error?: unknown) => void,
32
+ ): void {
33
+ const visit = (name: string): void => {
34
+ if (ignore.has(name)) return;
35
+ const path = join(home, name);
36
+ try {
37
+ const stat = lstatSync(path);
38
+ if (stat.isSymbolicLink() || (!stat.isDirectory() && !stat.isFile())) {
39
+ invalid(name);
40
+ } else if (stat.isDirectory()) {
41
+ for (const entry of readdirSync(path).sort()) visit(name === '.' ? entry : `${name}/${entry}`);
42
+ } else {
43
+ file(name, path);
44
+ }
45
+ } catch (error) {
46
+ if (error instanceof Error && 'code' in error) invalid(name, error);
47
+ else throw error;
48
+ }
49
+ };
50
+ visit('.');
51
+ }
52
+
53
+ export function partsSha256(bytes: Uint8Array | string): string {
54
+ return createHash('sha256').update(bytes).digest('hex');
55
+ }
56
+
57
+ export interface PartsInventoryRow { path: string; bytes: number; sha256: string }
58
+
59
+ export function partsInventoryDigest(rows: readonly PartsInventoryRow[]): string {
60
+ const ordered = [...rows].sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0);
61
+ return partsSha256(JSON.stringify(ordered.map(({ path, bytes, sha256 }) => ({ path, bytes, sha256 }))) + '\n');
62
+ }