@rig-c/parts 1.74.1 → 1.76.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/config.ts CHANGED
@@ -307,6 +307,8 @@ export interface Assemble {
307
307
  alternates?: AlternateSetConfig[];
308
308
  /** Issue #492: composite full:face under head:face on the head canvas to fill transparent holes inside the face silhouette. */
309
309
  head_face_underfill?: boolean;
310
+ /** Opt-in: yield original drift-refused front pixels to an opaque behind holder matching the painting. */
311
+ yield_refused?: boolean;
310
312
  }
311
313
 
312
314
  export interface SingleBone {
@@ -1612,7 +1614,7 @@ export interface EarlyConfig {
1612
1614
  depth?: DepthConfig;
1613
1615
  key: string;
1614
1616
  seethrough: SeeThrough;
1615
- assemble: { rig_scale: number; head_face_underfill?: boolean };
1617
+ assemble: { rig_scale: number; head_face_underfill?: boolean; yield_refused?: boolean };
1616
1618
  }
1617
1619
 
1618
1620
  /** What plain `assemble` reads: the early config plus the plan `--propose-plan` printed. */
@@ -1681,12 +1683,15 @@ function parseEarlyConfigFrom(raw: Json, door: EarlyDoor, base: string | null):
1681
1683
  if (door === 'layers') {
1682
1684
  if ('seethrough' in t) checkSeeThrough(c, t.seethrough);
1683
1685
  if ('assemble' in t) {
1684
- const a = c.object('config.assemble', t.assemble, sectionRequired(door, 'assemble'), ['plan', 'extend_below_crop', 'patches', 'cuts', 'alternates', 'head_face_underfill']);
1686
+ const a = c.object('config.assemble', t.assemble, sectionRequired(door, 'assemble'), ['plan', 'extend_below_crop', 'patches', 'cuts', 'alternates', 'head_face_underfill', 'yield_refused']);
1685
1687
  if (a !== null) {
1686
1688
  if ('rig_scale' in a) c.number('config.assemble.rig_scale', a.rig_scale, 'positive');
1687
1689
  if ('head_face_underfill' in a && typeof a.head_face_underfill !== 'boolean') {
1688
1690
  c.fail('CONFIG_FIELD_TYPE', 'config.assemble.head_face_underfill', `is ${show(a.head_face_underfill)}; true or false is required`);
1689
1691
  }
1692
+ if ('yield_refused' in a && typeof a.yield_refused !== 'boolean') {
1693
+ c.fail('CONFIG_FIELD_TYPE', 'config.assemble.yield_refused', `is ${show(a.yield_refused)}; true or false is required`);
1694
+ }
1690
1695
  }
1691
1696
  }
1692
1697
  }
@@ -2385,7 +2390,7 @@ function checkRunTag(c: Check, path: string, run: Json, tag: Json): void {
2385
2390
  */
2386
2391
  function checkAssemble(c: Check, v: Json, door: 'assemble' | 'full'): { parts: string[]; patches: string[]; cuts: string[] } {
2387
2392
  const required = sectionRequired(door, 'assemble');
2388
- const a = c.object('config.assemble', v, required.filter((k) => k !== 'plan'), ['plan', 'extend_below_crop', 'patches', 'cuts', 'alternates', 'head_face_underfill']);
2393
+ const a = c.object('config.assemble', v, required.filter((k) => k !== 'plan'), ['plan', 'extend_below_crop', 'patches', 'cuts', 'alternates', 'head_face_underfill', 'yield_refused']);
2389
2394
  if (a === null) return { parts: [], patches: [], cuts: [] };
2390
2395
  if (required.includes('plan') && !('plan' in a)) {
2391
2396
  c.fail('CONFIG_FIELD_PRESENT', 'config.assemble.plan', 'is absent and required; `assemble --propose-plan` prints one from the two runs — paste its plan and extend_below_crop into config.assemble');
@@ -2395,6 +2400,9 @@ function checkAssemble(c: Check, v: Json, door: 'assemble' | 'full'): { parts: s
2395
2400
  if ('head_face_underfill' in a && typeof a.head_face_underfill !== 'boolean') {
2396
2401
  c.fail('CONFIG_FIELD_TYPE', `${p}.head_face_underfill`, `is ${show(a.head_face_underfill)}; true or false is required`);
2397
2402
  }
2403
+ if ('yield_refused' in a && typeof a.yield_refused !== 'boolean') {
2404
+ c.fail('CONFIG_FIELD_TYPE', `${p}.yield_refused`, `is ${show(a.yield_refused)}; true or false is required`);
2405
+ }
2398
2406
  const parts: string[] = [];
2399
2407
  if ('plan' in a && c.array(`${p}.plan`, a.plan, true)) {
2400
2408
  const seenPart = new Map<string, number>();
package/src/parts.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { AUTOMATIC_WRITERS, provenanceAddsUp, type PixelProvenance, type CutOwnership } from './provenance.ts';
1
2
  import { baseAnchorProblems, orderedBaseAnchor, type BaseAnchor } from './baseanchor.ts';
2
3
  import { partDepthProblems, type PartDepthReference } from './depthsheets.ts';
3
4
  /**
@@ -96,6 +97,8 @@ import { edgeLength } from './length.ts';
96
97
  import { recordedFocusProblems } from './setfocus.ts';
97
98
 
98
99
  export interface PartRecord {
100
+ /** Report-only final last-writer census (#817); absent on older records. */
101
+ provenance?: PixelProvenance;
99
102
  /** Optional #773 input reference; production geometry does not consume it yet. */
100
103
  depth?: PartDepthReference;
101
104
  name: string;
@@ -326,6 +329,7 @@ export interface AlternateSetMap {
326
329
  export const FRONT_SUFFIX = '_front';
327
330
 
328
331
  export interface AlternatePartsRecord {
332
+ cut_ownership?: CutOwnership[];
329
333
  name: string;
330
334
  base_anchor?: BaseAnchor;
331
335
  /** Original authored painting point and its source size, only when supplied. */
@@ -358,6 +362,8 @@ export interface AlternatePartsRecord {
358
362
  }
359
363
 
360
364
  export interface PartsFile {
365
+ /** Structural moves, independent of per-pixel value equality. */
366
+ cut_ownership?: CutOwnership[];
361
367
  rig_size: [number, number];
362
368
  scale_rig_per_source: number;
363
369
  parts: PartRecord[];
@@ -406,8 +412,8 @@ export interface SceneRecord {
406
412
  figure_mask: string;
407
413
  }
408
414
 
409
- const TOP_KEYS = ['rig_size', 'scale_rig_per_source', 'parts', 'ghost_px', 'recomposite', 'scene', 'single_run_pad', 'alternates', 'motion_seams'] as const;
410
- const REQUIRED_TOP_KEYS = TOP_KEYS.filter((k) => k !== 'recomposite' && k !== 'scene' && k !== 'single_run_pad' && k !== 'alternates' && k !== 'motion_seams');
415
+ const TOP_KEYS = ['rig_size', 'scale_rig_per_source', 'parts', 'ghost_px', 'recomposite', 'scene', 'single_run_pad', 'alternates', 'motion_seams', 'cut_ownership'] as const;
416
+ const REQUIRED_TOP_KEYS = TOP_KEYS.filter((k) => k !== 'recomposite' && k !== 'scene' && k !== 'single_run_pad' && k !== 'alternates' && k !== 'motion_seams' && k !== 'cut_ownership');
411
417
  export const SINGLE_RUN_PAD_KEYS = ['file_size', 'side', 'left', 'top'] as const;
412
418
  export const SCENE_KEYS = ['figure_alpha_above', 'figure_px', 'figure_mask'] as const;
413
419
  export const RECOMPOSITE_KEYS = ['mean_abs', 'within_limit', 'within_share', 'error_limit', 'error_px', 'covered_alpha', 'uncovered_error_px', 'hole_count', 'holes_listed', 'holes'] as const;
@@ -423,6 +429,7 @@ export const PART_KEYS = [
423
429
  'w',
424
430
  'h',
425
431
  'opaque_px',
432
+ 'provenance',
426
433
  'visible_px',
427
434
  'occluded_px',
428
435
  'projected_core_px',
@@ -441,10 +448,10 @@ const FRINGE_KEY = 'fringe_pushed_back';
441
448
  const CUT_FROM_KEY = 'cut_from';
442
449
  /** The one part field that is a record of its own: a limb segment's provenance (issue #349), written only on one. */
443
450
  const LIMB_KEY = 'limb';
444
- const COUNT_KEYS = PART_KEYS.slice(2).filter((k) => k !== FRINGE_KEY && k !== CUT_FROM_KEY && k !== LIMB_KEY && k !== 'depth') as ReadonlyArray<(typeof PART_KEYS)[number]>;
451
+ const COUNT_KEYS = PART_KEYS.slice(2).filter((k) => k !== FRINGE_KEY && k !== CUT_FROM_KEY && k !== LIMB_KEY && k !== 'depth' && k !== 'provenance') as ReadonlyArray<(typeof PART_KEYS)[number]>;
445
452
  /** The port's own counts: all three or none (none = a record the reference wrote). */
446
453
  export const VISIBILITY_KEYS = ['visible_px', 'occluded_px', 'visible_not_projected_px'] as const;
447
- const REQUIRED_KEYS = PART_KEYS.filter((k) => !(VISIBILITY_KEYS as readonly string[]).includes(k) && k !== FRINGE_KEY && k !== CUT_FROM_KEY && k !== LIMB_KEY && k !== 'depth');
454
+ const REQUIRED_KEYS = PART_KEYS.filter((k) => !(VISIBILITY_KEYS as readonly string[]).includes(k) && k !== FRINGE_KEY && k !== CUT_FROM_KEY && k !== LIMB_KEY && k !== 'depth' && k !== 'provenance');
448
455
 
449
456
  /** 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. */
450
457
  export type From = { run: 'full' | 'head'; tag: string } | { run: 'painting'; patch: string };
@@ -467,9 +474,34 @@ export function tagOf(from: string): string | null {
467
474
  return f === null || f.run === 'painting' ? null : f.tag;
468
475
  }
469
476
 
477
+ 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'] as const;
478
+ function orderedOwnership(rows: readonly CutOwnership[]): Array<Record<string, unknown>> {
479
+ return rows.map(r => Object.fromEntries(OWNERSHIP_KEYS.map(k => [k, r[k]])));
480
+ }
481
+ function checkOwnership(raw: unknown, object: string, fail: (code: string, object: string, detail: string) => void): void {
482
+ if (!Array.isArray(raw)) { fail('PARTS_FIELD_TYPE', object, `is ${show(raw)}; an array of indexed cut ownership records is required`); return; }
483
+ const seen = new Set<string>();
484
+ raw.forEach((row, i) => {
485
+ const r = row as CutOwnership | null;
486
+ const shape = r !== null && typeof r === 'object' && !Array.isArray(r) && Object.keys(r).sort().join(',') === [...OWNERSHIP_KEYS].sort().join(',') &&
487
+ typeof r.edit === 'string' && /^cuts\[\d+\]$/.test(r.edit) && !seen.has(r.edit) && typeof r.from === 'string' && r.from !== '' && typeof r.into === 'string' && r.into !== '' &&
488
+ OWNERSHIP_KEYS.slice(3).every(k => Number.isSafeInteger(r[k]) && (k === 'net_cleared_opaque_px' || (r[k] as number) >= 0));
489
+ if (!shape) { fail('PARTS_FIELD_TYPE', `${object}[${i}]`, `is ${show(row)}; a distinct cuts[i] with from/into names, nonnegative move/clear/fill counts and signed net_cleared_opaque_px is required`); return; }
490
+ const q = r as CutOwnership; seen.add(q.edit);
491
+ if (q.moved_in_opaque_px - q.retained_band_opaque_px !== q.cleared_opaque_px || q.cleared_opaque_px - q.under_filled_opaque_px !== q.net_cleared_opaque_px || q.under_filled_opaque_px > q.under_filled_px) {
492
+ fail('PARTS_COUNTS_ADD_UP', `${object}[${i}]`, `moved ${q.moved_in_opaque_px} - retained ${q.retained_band_opaque_px} = ${q.moved_in_opaque_px - q.retained_band_opaque_px} (gross cleared ${q.cleared_opaque_px} required); cleared - opaque fill ${q.under_filled_opaque_px} = ${q.cleared_opaque_px - q.under_filled_opaque_px} (net ${q.net_cleared_opaque_px} required); opaque fill must be at most total fill ${q.under_filled_px}`);
493
+ }
494
+ });
495
+ }
496
+
497
+ function orderedProvenance(p: PixelProvenance): PixelProvenance {
498
+ return { unchanged_layer_px: p.unchanged_layer_px, hand_px: p.hand_px, automatic_px: p.automatic_px,
499
+ edits: p.edits.map(e => ({ edit: e.edit, px: e.px })), automatic: p.automatic.map(e => ({ stage: e.stage, px: e.px })) };
500
+ }
501
+
470
502
  function serializePartList(parts: readonly PartRecord[]): Array<Record<string, unknown>> {
471
503
  return parts.map((p) =>
472
- Object.fromEntries(PART_KEYS.filter((k) => p[k] !== undefined).map((k) => [k, k === FRINGE_KEY ? (p.fringe_pushed_back ?? []).map((q) => ({ part: q.part, px: q.px })) : k === LIMB_KEY ? orderedLimb(p.limb as LimbRecord) : p[k]])),
504
+ Object.fromEntries(PART_KEYS.filter((k) => p[k] !== undefined).map((k) => [k, k === FRINGE_KEY ? (p.fringe_pushed_back ?? []).map((q) => ({ part: q.part, px: q.px })) : k === LIMB_KEY ? orderedLimb(p.limb as LimbRecord) : k === 'provenance' ? orderedProvenance(p.provenance as PixelProvenance) : p[k]])),
473
505
  );
474
506
  }
475
507
 
@@ -485,6 +517,7 @@ export function serializeParts(file: PartsFile): string {
485
517
  rig_size: file.rig_size,
486
518
  scale_rig_per_source: file.scale_rig_per_source,
487
519
  parts: serializePartList(file.parts),
520
+ ...(file.cut_ownership === undefined ? {} : { cut_ownership: orderedOwnership(file.cut_ownership) }),
488
521
  ...(file.motion_seams === undefined ? {} : { motion_seams: file.motion_seams.map(({ part, neighbour }) => ({ part, neighbour })) }),
489
522
  ghost_px: Object.fromEntries(Object.keys(file.ghost_px).sort().map((k) => [k, file.ghost_px[k]])),
490
523
  ...(file.recomposite === undefined ? {} : { recomposite: serializeRecomposite(file.recomposite) }),
@@ -501,6 +534,7 @@ export function serializeParts(file: PartsFile): string {
501
534
  ...(a.front === undefined ? {} : { front: a.front }),
502
535
  slots: a.slots,
503
536
  records: serializePartList(a.records),
537
+ ...(a.cut_ownership === undefined ? {} : { cut_ownership: orderedOwnership(a.cut_ownership) }),
504
538
  ghost_px: Object.fromEntries(Object.keys(a.ghost_px).sort().map((k) => [k, a.ghost_px[k]])),
505
539
  recomposite: serializeRecomposite(a.recomposite),
506
540
  ...(a.scene === undefined ? {} : { scene: Object.fromEntries(SCENE_KEYS.map((k) => [k, (a.scene as SceneRecord)[k]])) }),
@@ -541,6 +575,30 @@ function show(v: unknown): string {
541
575
  return v === undefined ? 'absent' : JSON.stringify(v);
542
576
  }
543
577
 
578
+ /** The same optional measurement contract for base and alternate records. */
579
+ function checkProvenance(raw: unknown, opaque: unknown, object: string, fail: (code: string, object: string, detail: string) => void): void {
580
+ const v = raw as PixelProvenance | null;
581
+ const count = (n: unknown): boolean => Number.isSafeInteger(n) && (n as number) >= 0;
582
+ const edit = (name: string): boolean => /^(cuts\[\d+\]|patches\[\d+\])$/.test(name) ||
583
+ (/^(full|head):author:/.test(name) && readFrom(name) !== null);
584
+ const shape = v !== null && typeof v === 'object' && !Array.isArray(v) &&
585
+ Object.keys(v).sort().join(',') === 'automatic,automatic_px,edits,hand_px,unchanged_layer_px' &&
586
+ [v.unchanged_layer_px, v.hand_px, v.automatic_px].every(count) && Array.isArray(v.edits) && Array.isArray(v.automatic) &&
587
+ v.edits.every(e => e !== null && typeof e === 'object' && Object.keys(e).sort().join(',') === 'edit,px' && typeof e.edit === 'string' && edit(e.edit) && count(e.px) && e.px > 0) &&
588
+ v.automatic.every(e => e !== null && typeof e === 'object' && Object.keys(e).sort().join(',') === 'px,stage' && typeof e.stage === 'string' && Object.hasOwn(AUTOMATIC_WRITERS, e.stage) && count(e.px) && e.px > 0) &&
589
+ new Set(v.edits.map(e => e.edit)).size === v.edits.length && new Set(v.automatic.map(e => e.stage)).size === v.automatic.length;
590
+ if (!shape) {
591
+ fail('PARTS_FIELD_TYPE', object, `is ${show(raw)}; unchanged_layer_px, hand_px and automatic_px as nonnegative safe integers, edits as distinct cuts[i]/patches[i]/<run>:author:<label> entries, and automatic as distinct known stage entries, each with a positive integer px, are required`);
592
+ } else if (!count(opaque)) {
593
+ fail('PARTS_FIELD_TYPE', object, `opaque_px is ${show(opaque)}; a nonnegative safe integer opaque_px is required beside provenance`);
594
+ } else if (!provenanceAddsUp(v as PixelProvenance, opaque as number)) {
595
+ const p = v as PixelProvenance;
596
+ const total = p.unchanged_layer_px + p.hand_px + p.automatic_px;
597
+ const hand = p.edits.reduce((n, e) => n + e.px, 0), automatic = p.automatic.reduce((n, e) => n + e.px, 0);
598
+ fail('PARTS_COUNTS_ADD_UP', object, `unchanged_layer_px ${p.unchanged_layer_px} + hand_px ${p.hand_px} + automatic_px ${p.automatic_px} = ${total}; opaque_px ${opaque} is required; edit subtotal ${hand} (hand_px ${p.hand_px} required), stage subtotal ${automatic} (automatic_px ${p.automatic_px} required)`);
599
+ }
600
+ }
601
+
544
602
  function checkParts(raw: unknown, path: string): PartsFile {
545
603
  const problems: Problem[] = [];
546
604
  const fail = (code: string, object: string, detail: string): void => {
@@ -601,6 +659,7 @@ function checkParts(raw: unknown, path: string): PartsFile {
601
659
  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`);
602
660
  }
603
661
  const count = (k: string): number | null => (Number.isInteger(r[k]) && (r[k] as number) >= 0 ? (r[k] as number) : null);
662
+ if ('provenance' in r) checkProvenance(r.provenance, r.opaque_px, label + ' provenance', fail);
604
663
  const [op, vis, occ, vnp] = ['opaque_px', 'visible_px', 'occluded_px', 'visible_not_projected_px'].map(count);
605
664
  if (held.length === VISIBILITY_KEYS.length && op !== null && vis !== null && occ !== null && vnp !== null) {
606
665
  if (vis + occ !== op) fail('PARTS_COUNTS_ADD_UP', `${label}`, `visible_px ${vis} + occluded_px ${occ} = ${vis + occ}; opaque_px ${op} is required`);
@@ -692,6 +751,7 @@ function checkParts(raw: unknown, path: string): PartsFile {
692
751
  if (!('recomposite' in o)) fail('PARTS_FIELD_PRESENT', `${path} field "recomposite"`, 'is absent; a scene block says how the recomposite block beside it was measured, so it is required with one');
693
752
  }
694
753
  }
754
+ if ('cut_ownership' in o) checkOwnership(o.cut_ownership, `${path} cut_ownership`, fail);
695
755
  if ('single_run_pad' in o) checkSingleRunPad(o.single_run_pad, path, sizeOk ? (size as [number, number]) : null, typeof scale === 'number' ? scale : null, fail);
696
756
  if ('recomposite' in o && sizeOk) {
697
757
  const names = Array.isArray(o.parts) ? new Set(o.parts.map((p) => (typeof p === 'object' && p !== null ? (p as Record<string, unknown>).name : undefined)).filter((n): n is string => typeof n === 'string')) : new Set<string>();
@@ -706,6 +766,7 @@ function checkParts(raw: unknown, path: string): PartsFile {
706
766
  if (typeof a !== 'object' || a === null || Array.isArray(a)) return;
707
767
  const set = a as Record<string, unknown>;
708
768
  const at = `${path} alternates[${i}]${typeof set.name === 'string' ? ` (set "${set.name}")` : ''}`;
769
+ if ('cut_ownership' in set) checkOwnership(set.cut_ownership, `${at} cut_ownership`, fail);
709
770
  if ('base_anchor' in set) {
710
771
  const names = new Set(Array.isArray(set.records) ? set.records.flatMap(v => typeof v === 'object' && v !== null && typeof v.name === 'string' ? [v.name] : []) : []);
711
772
  const patches = new Set(Array.isArray(set.records) ? set.records.flatMap(v => typeof v === 'object' && v !== null && typeof v.name === 'string' && typeof v.from === 'string' && v.from.startsWith('painting:') ? [v.name] : []) : []);
@@ -749,6 +810,8 @@ function checkParts(raw: unknown, path: string): PartsFile {
749
810
  set.records.forEach((p, j) => {
750
811
  if (typeof p !== 'object' || p === null || Array.isArray(p)) return;
751
812
  const r = p as Record<string, unknown>;
813
+ const part817 = typeof r.name === 'string' ? `part "${r.name}"` : `records[${j}]`;
814
+ if ('provenance' in r) checkProvenance(r.provenance, r.opaque_px, `${at} ${part817} provenance`, fail);
752
815
  const l = r[LIMB_KEY];
753
816
  if (typeof l !== 'object' || l === null || Array.isArray(l) || !('cap' in l)) return;
754
817
  const part = typeof r.name === 'string' ? `part "${r.name}"` : `records[${j}]`;
@@ -0,0 +1,106 @@
1
+ /** Report-only last-writer accounting over final output pixels (#817). */
2
+ import { OPAQUE_ALPHA_ABOVE } from './layers.ts';
3
+ import type { PartRecord } from './parts.ts';
4
+ import { crop, type Raster } from './raster/index.ts';
5
+
6
+ /** Negative IDs distinguish automatic writes from positive, config-indexed hand edits. */
7
+ export const AUTOMATIC_WRITERS = {
8
+ sourceProjection: -1, extend: -2, growRim: -3, limbSplit: -4,
9
+ limbCap: -5, limbHybrid: -6, limbFeather: -7, fringeRestore: -8,
10
+ seamOverride: -9, armSplit: -10, headFaceUnderfill: -11, ghostCleanup: -12, unattributed: -13,
11
+ } as const;
12
+ export type AutomaticWriter = keyof typeof AUTOMATIC_WRITERS;
13
+ export interface PixelProvenance {
14
+ unchanged_layer_px: number;
15
+ hand_px: number;
16
+ automatic_px: number;
17
+ edits: Array<{ edit: string; px: number }>;
18
+ automatic: Array<{ stage: AutomaticWriter; px: number }>;
19
+ }
20
+
21
+ /** RGBA equality on the same rig coordinate, including alpha. */
22
+ export function rgbaEqual(a: Uint8ClampedArray, ai: number, b: Uint8ClampedArray, bi: number): boolean {
23
+ return a[ai] === b[bi] && a[ai + 1] === b[bi + 1] && a[ai + 2] === b[bi + 2] && a[ai + 3] === b[bi + 3];
24
+ }
25
+
26
+ /** An immutable crop of normalized raw samples that can equal an opaque output.
27
+ * Outside this box raw alpha is <= 8, so it cannot equal final alpha > 8.
28
+ * The crop copies RGBA; it must never alias a raster later projected in place. */
29
+ export interface ValueBaseline { readonly image: Raster; readonly x: number; readonly y: number }
30
+ export function compactValueBaseline(raw: Raster): ValueBaseline {
31
+ let x0 = raw.width, y0 = raw.height, x1 = -1, y1 = -1;
32
+ for (let y = 0; y < raw.height; y++) for (let x = 0; x < raw.width; x++) {
33
+ if (raw.data[(y * raw.width + x) * 4 + 3] <= OPAQUE_ALPHA_ABOVE) continue;
34
+ x0 = Math.min(x0, x); y0 = Math.min(y0, y); x1 = Math.max(x1, x); y1 = Math.max(y1, y);
35
+ }
36
+ return x1 < 0 ? { image: crop(raw, 0, 0, 0, 0), x: 0, y: 0 }
37
+ : { image: crop(raw, x0, y0, x1 - x0 + 1, y1 - y0 + 1), x: x0, y: y0 };
38
+ }
39
+
40
+ /** Value equality with the raw normalized See-through baseline wins first.
41
+ * Otherwise the last stage that CHANGED RGBA wins; buffer copies inherit IDs.
42
+ * A null baseline is explicit for authored layers/painting patches. */
43
+ export function pixelProvenance(image: Raster, x: number, y: number, width: number, writers: Int32Array | null, edits: readonly string[], patchId = 0, baseline: Raster | ValueBaseline | null = null): PixelProvenance {
44
+ const out: PixelProvenance = { unchanged_layer_px: 0, hand_px: 0, automatic_px: 0, edits: [], automatic: [] };
45
+ const counts = new Map<number, number>();
46
+ const reference = baseline === null ? null : 'image' in baseline ? baseline.image : baseline;
47
+ const bx = baseline !== null && 'image' in baseline ? baseline.x : 0;
48
+ const by = baseline !== null && 'image' in baseline ? baseline.y : 0;
49
+ for (let j = 0; j < image.height; j++) for (let i = 0; i < image.width; i++) {
50
+ if (image.data[(j * image.width + i) * 4 + 3] <= OPAQUE_ALPHA_ABOVE) continue;
51
+ const q = (y + j) * width + x + i;
52
+ const u = x + i - bx, v = y + j - by;
53
+ const same = reference !== null && u >= 0 && v >= 0 && u < reference.width && v < reference.height &&
54
+ rgbaEqual(image.data, (j * image.width + i) * 4, reference.data, (v * reference.width + u) * 4);
55
+ const previous = writers?.[q] ?? patchId;
56
+ // Unknown lineage is reported explicitly, never invented as unchanged.
57
+ const id = same ? 0 : previous === 0 ? AUTOMATIC_WRITERS.unattributed : previous;
58
+ if (id > 0) out.hand_px++;
59
+ else if (id < 0) out.automatic_px++;
60
+ else out.unchanged_layer_px++;
61
+ if (id !== 0) counts.set(id, (counts.get(id) ?? 0) + 1);
62
+ }
63
+ out.edits = edits.flatMap((edit, i) => counts.has(i + 1) ? [{ edit, px: counts.get(i + 1) as number }] : []);
64
+ out.automatic = (Object.keys(AUTOMATIC_WRITERS) as AutomaticWriter[]).flatMap(stage => counts.has(AUTOMATIC_WRITERS[stage]) ? [{ stage, px: counts.get(AUTOMATIC_WRITERS[stage]) as number }] : []);
65
+ return out;
66
+ }
67
+
68
+ /** The reader and selftests share this arithmetic check; no hand-edit gate. */
69
+ export function provenanceAddsUp(p: PixelProvenance, opaque: number): boolean {
70
+ return p.unchanged_layer_px + p.hand_px + p.automatic_px === opaque &&
71
+ p.edits.reduce((n, e) => n + e.px, 0) === p.hand_px && p.automatic.reduce((n, e) => n + e.px, 0) === p.automatic_px;
72
+ }
73
+
74
+ export function provenanceLines(parts: readonly PartRecord[]): string[] {
75
+ const lines: string[] = [];
76
+ let opaque = 0, unchanged = 0, automatic = 0, hand = 0;
77
+ const edits = new Map<string, number>(), stages = new Map<string, number>();
78
+ const detail = (e: ReadonlyMap<string, number>): string => [...e].map(([name, px]) => `${name} ${px}`).join(', ') || 'none';
79
+ for (const p of parts) {
80
+ const v = p.provenance;
81
+ if (v === undefined) continue;
82
+ opaque += p.opaque_px; unchanged += v.unchanged_layer_px; automatic += v.automatic_px; hand += v.hand_px;
83
+ for (const e of v.edits) edits.set(e.edit, (edits.get(e.edit) ?? 0) + e.px);
84
+ for (const e of v.automatic) stages.set(e.stage, (stages.get(e.stage) ?? 0) + e.px);
85
+ lines.push(` provenance: part "${p.name}" (${p.from}) opaque ${p.opaque_px} = unchanged layer ${v.unchanged_layer_px} + hand ${v.hand_px} + automatic ${v.automatic_px}; edits ${detail(new Map(v.edits.map(e => [e.edit, e.px])))}; stages ${detail(new Map(v.automatic.map(e => [e.stage, e.px])))}`);
86
+ }
87
+ lines.push(` provenance total: opaque ${opaque} = unchanged layer ${unchanged} + hand ${hand} + automatic ${automatic}; edits ${detail(edits)}; stages ${detail(stages)}; output pixels, including copies in separate parts; value equality first; last value-changing stage wins`);
88
+ return lines;
89
+ }
90
+
91
+ /** Structural cut census, independent of the value partition. Counts are from
92
+ * the original parent partition before limb/fringe/seam processing. */
93
+ export interface CutOwnership {
94
+ edit: string;
95
+ from: string;
96
+ into: string;
97
+ moved_in_opaque_px: number;
98
+ retained_band_opaque_px: number;
99
+ cleared_opaque_px: number;
100
+ under_filled_px: number;
101
+ under_filled_opaque_px: number;
102
+ net_cleared_opaque_px: number;
103
+ }
104
+ export function ownershipLines(rows: readonly CutOwnership[]): string[] {
105
+ return rows.map(r => ` ownership: ${r.edit} "${r.from}" -> "${r.into}" moved in ${r.moved_in_opaque_px} opaque px; retained band ${r.retained_band_opaque_px}; gross cleared ${r.cleared_opaque_px} before refill; under filled ${r.under_filled_px} px (${r.under_filled_opaque_px} opaque); net cleared ${r.net_cleared_opaque_px}; independent of RGBA equality`);
106
+ }