@rig-c/parts 2.31.0 → 2.32.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/docs/STABILITY.md CHANGED
@@ -314,7 +314,8 @@ part name, `[i]` an entry of a list):
314
314
  - **generation.control.skeleton**, the pose file it names when it is no built-in — required: `width`, `height`, `points`
315
315
  - **seethrough** — required: `resolution`, `steps`, `seed`, `offload`; optional: `head_box`, `arm_split`
316
316
  - **seethrough.arm_split** — required: `order`, and one of `x` or `line` (issue #439)
317
- - **assemble** — required: `rig_scale`, `plan` (from plain `assemble` on); optional: `seam`, `project`, `ground`, `extend_below_crop`, `patches`, `cuts`, `alternates`, `head_face_underfill`, `yield_refused`, `stage_map`, `keep_under_occluders`, `require_hidden_extent`, `extend_painting`, `take`, `editor_receipts`, `occluders`
317
+ - **assemble** — required: `rig_scale`, `plan` (from plain `assemble` on); optional: `seam`, `project`, `ground`, `extend_below_crop`, `patches`, `cuts`, `alternates`, `head_face_underfill`, `yield_refused`, `stage_map`, `keep_under_occluders`, `require_hidden_extent`, `extend_painting`, `edge_splits`, `take`, `editor_receipts`, `occluders`
318
+ - **assemble.edge_splits[i]** — required: `over`, `under`, `band`
318
319
  - **assemble.require_hidden_extent[i]** — required: `part`, `occluder`
319
320
  - **assemble.occluders[i]** — required: `image`, `sha256`, `under`, `rgb_within` (issue #1230)
320
321
  - **assemble.alternates[i]** — required: `name`; optional: `source`, `full`, `head`, `parts`, `hides`, `head_box`, `cuts`, `skeleton`, `anchor`, `base_anchor`, `drawn`, `tips`, `front`, `layers`, `focus` (issues #454, #465, #543, #652, #664, #666, #719, #780). `focus` is an authored finite `[x, y]` in painting pixels, within its canvas (edges included), refused as CONFIG_SET_FOCUS before assemble output when invalid; only when present, `parts.json` records it with focus_source_size and `sets.json` emits it in setup-world coordinates through the actual rig resize and `src/coords.ts`. Absent focus emits no field or inferred value; changing/removing it requires reassembly
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rig-c/parts",
3
- "version": "2.31.0",
3
+ "version": "2.32.0",
4
4
  "description": "AI-authored 2D character parts from one anime painting and its See-through layer decomposition: measured parts, weighted-mesh rig specs, verified through rig-c before anything is written. A CLI for agents that cannot see the image.",
5
5
  "type": "module",
6
6
  "bin": {
package/src/assemble.ts CHANGED
@@ -12,6 +12,7 @@ import { materialSource, type MaterialSource, materialRows, polygonMaterialEdges
12
12
  import { unionTakenSources } from './takesource.ts';
13
13
  import { authoredUnitDepths, type AuthoredUnitDepth } from './authoredunit.ts';
14
14
  import { paintingExtensionMasks, paintingExtensionProblems, type PaintingExtension } from './paintingextension.ts';
15
+ import { applyEdgeSplits, edgeSplitLines, edgeSplitProblems, type EdgeSplit, type EdgeSplitReading } from './edgesplit.ts';
15
16
  import { AUTOMATIC_WRITERS as AW, compactValueBaseline, pixelProvenance, rgbaEqual, type ValueBaseline, type StageMap } from './provenance.ts';
16
17
  import { bindDepthRun, copyDepthMaterial, registerDepthRun, transportPartDepth, type DepthConfig, type RegisteredDepth } from './depthsheets.ts';
17
18
  /**
@@ -376,6 +377,8 @@ export interface AssembleInput {
376
377
  requireHiddenExtent?: readonly HiddenExtentDeclaration[];
377
378
  /** Base painting only; named final parts, explicit band and path bound (#848). */
378
379
  paintingExtension?: readonly PaintingExtension[];
380
+ /** Painting-edge splits between plan parts before projection (#1231). */
381
+ edgeSplits?: readonly EdgeSplit[];
379
382
  /**
380
383
  * Issue #587: rig pixels taken out of named parts once the cuts and the limbs are made, before the fringe pass and
381
384
  * every figure a part's record holds — each entry clears `part`'s pixels (alpha, colour and region) where `mask` is
@@ -4788,6 +4791,8 @@ export interface AssembleResult {
4788
4791
  splits: SplitCount[];
4789
4792
  /** Issue #637: source-transparent cap pixels assigned before preservation, in either source-art door. */
4790
4793
  capSplits: SplitCount[];
4794
+ /** Issue #1231: what each `edge_splits` entry moved before projection; empty without one. */
4795
+ edgeSplits: EdgeSplitReading[];
4791
4796
  }
4792
4797
 
4793
4798
  /** Issue #953: the edge pixels `paintingEdges` resolved, the part pixels it changed, and the edge pixels it left, by reason. */
@@ -4991,6 +4996,7 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
4991
4996
  const { source, extend, patches, seamRule, projectRule } = input;
4992
4997
  const authoredDepths = input.depth === undefined ? new Map<string, AuthoredUnitDepth>() : authoredUnitDepths(input);
4993
4998
  if (input.paintingExtension !== undefined) refuseIfAny(paintingExtensionProblems(input.paintingExtension));
4999
+ if (input.edgeSplits !== undefined) refuseIfAny(edgeSplitProblems(input.edgeSplits, new Set(input.plan.map(([name]) => name))));
4994
5000
  const single = input.single === true;
4995
5001
  const frame = checkGeometry(
4996
5002
  { sourceW: source.width, sourceH: source.height, resolution: input.resolution, headBox: input.headBox, rigScale: input.rigScale, ...(single ? { single: true } : {}) },
@@ -5107,6 +5113,7 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
5107
5113
  const ghost: Record<string, number> = {};
5108
5114
  /** The full run's layers with an opaque pixel, in draw order: the candidates `uncoveredErrorLayers` reads. */
5109
5115
  const fullTags: string[] = [];
5116
+ const preparedRuns: Array<{ run: Run; set: LayerSet; layers: ReturnType<typeof runLayers>; rigLayers: Raster[]; rank: number[]; keep: Array<Mask | null>; writes: Array<Int32Array | null> }> = [];
5110
5117
  // A single run (issue #359) is read once: there is no head run to place, project or count ghosts for.
5111
5118
  for (const [run, set] of single ? ([['full', full]] as const) : ([['full', full], ['head', head]] as const)) {
5112
5119
  const layers = runLayers(set, input.resolution);
@@ -5193,6 +5200,42 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
5193
5200
  valueBaselines.set(key, raw === null ? null : compactValueBaseline(raw));
5194
5201
  return ids;
5195
5202
  });
5203
+ preparedRuns.push({ run, set, layers, rigLayers, rank, keep, writes });
5204
+ }
5205
+ const edgeSplitNewSampleParts = new Set<string>();
5206
+ const edgeSplits = (input.edgeSplits?.length ?? 0) === 0 ? [] : applyEdgeSplits(
5207
+ input.edgeSplits!,
5208
+ new Map(sourcePlan.flatMap(([name, r, tag]) => {
5209
+ const prep = preparedRuns.find(p => p.run === r);
5210
+ const idx = prep?.layers.findIndex(l => l.tag === tag) ?? -1;
5211
+ return prep !== undefined && idx >= 0 ? [[name, prep.rigLayers[idx]] as [string, Raster]] : [];
5212
+ })),
5213
+ srcr,
5214
+ (part, pixel, cleared, priorAlpha) => {
5215
+ if (!cleared && priorAlpha <= OPAQUE_ALPHA_ABOVE) edgeSplitNewSampleParts.add(part);
5216
+ const row = sourcePlan.find(([name]) => name === part);
5217
+ if (row === undefined) return;
5218
+ const prep = preparedRuns.find(p => p.run === row[1]);
5219
+ const idx = prep?.layers.findIndex(l => l.tag === row[2]) ?? -1;
5220
+ const w = prep !== undefined && idx >= 0 ? prep.writes[idx] : null;
5221
+ if (w !== null && w !== undefined) w[pixel] = cleared ? 0 : AW.sourceProjection;
5222
+ },
5223
+ );
5224
+ const edgeSplitDepthProblems: Problem[] = [];
5225
+ for (const part of edgeSplitNewSampleParts) {
5226
+ const row = sourcePlan.find(([name]) => name === part);
5227
+ if (row === undefined) continue;
5228
+ const keys = [`${row[1]}:${row[2]}`, ...extend.filter(e => e.part === part).map(e => `${e.run}:${e.tag}`)];
5229
+ if (keys.some(k => registeredDepth.has(k))) {
5230
+ edgeSplitDepthProblems.push({
5231
+ code: 'DEPTH_PART_SUPPORT',
5232
+ object: `part "${part}"`,
5233
+ detail: 'edge split (config.assemble.edge_splits) gives new painting samples to a part with a layer depth sheet; remove the split or the target layer depth, never extrapolate a layer sheet onto new painting samples',
5234
+ });
5235
+ }
5236
+ }
5237
+ refuseIfAny(edgeSplitDepthProblems);
5238
+ for (const { run, set, layers, rigLayers, rank, keep, writes } of preparedRuns) {
5196
5239
  const st = projectSource(rigLayers, srcr, frame, run, projectRule, rank, keep, (i, p) => { if (writes[i] !== null) (writes[i] as Int32Array)[p] = AW.sourceProjection; }, owners => {
5197
5240
  if (targets !== undefined && beforeTake === null) return;
5198
5241
  const reading = sourceCoverRun(run, set, run === 'full' ? fullPadded : depthHeadInput,
@@ -5875,10 +5918,12 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
5875
5918
  return whole;
5876
5919
  };
5877
5920
  const canvases = stack.map(onRig);
5878
- const owner = rawPaintingOwner(input.plan.map(([name, run, tag]) => {
5921
+ const rawPlan = input.plan.map(([name, run, tag]) => {
5879
5922
  const layer = input[run].layers.find(l => l.name === tag)!;
5880
5923
  return { name, raster: layerToRig(placeLayer(layer, input.resolution), frame, run) };
5881
- }), W * H);
5924
+ });
5925
+ if ((input.edgeSplits?.length ?? 0) > 0) applyEdgeSplits(input.edgeSplits!, new Map(rawPlan.map(p => [p.name, p.raster])), srcr);
5926
+ const owner = rawPaintingOwner(rawPlan, W * H);
5882
5927
  const lineage: Array<[string, string]> = [
5883
5928
  ...input.cuts.map(c => [c.from, c.into] as [string, string]),
5884
5929
  ...Object.values(input.limbs ?? {}).flatMap(l => l.segments.flatMap(segment => [
@@ -6182,9 +6227,12 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
6182
6227
  islands: islandKept.counts,
6183
6228
  splits: islandKept.splits,
6184
6229
  capSplits: capAssigned.counts,
6230
+ edgeSplits,
6185
6231
  };
6186
6232
  }
6187
6233
 
6234
+ export { edgeSplitLines };
6235
+
6188
6236
  // ---------------------------------------------------------------------------
6189
6237
  // refused bodies: a part whose layer is not what the painting shows (issue #255)
6190
6238
  // ---------------------------------------------------------------------------
@@ -7087,6 +7135,8 @@ export function stageFields(
7087
7135
  requireHiddenExtent?: readonly HiddenExtentDeclaration[];
7088
7136
  /** Base painting only; named final parts, explicit band and path bound (#848). */
7089
7137
  paintingExtension?: readonly PaintingExtension[];
7138
+ /** Painting-edge splits between plan parts before projection (#1231). */
7139
+ edgeSplits?: readonly EdgeSplit[];
7090
7140
  turnMovingPair?: (a: string, b: string) => boolean;
7091
7141
  turn?: TurnSpec;
7092
7142
  regions?: Record<string, RegionSpec>;
@@ -7119,6 +7169,7 @@ export function stageFields(
7119
7169
  ...(cfg.assemble.require_hidden_extent === undefined ? {} : { requireHiddenExtent: cfg.assemble.require_hidden_extent }),
7120
7170
  ...(cfg.assemble.ground === undefined ? {} : { ground: cfg.assemble.ground }),
7121
7171
  ...(cfg.assemble.extend_painting === undefined ? {} : { paintingExtension: cfg.assemble.extend_painting }),
7172
+ ...(cfg.assemble.edge_splits === undefined ? {} : { edgeSplits: cfg.assemble.edge_splits }),
7122
7173
  ...(turnMovingPair === null ? {} : { turnMovingPair }),
7123
7174
  ...(cfg.turn === undefined ? {} : { turn: cfg.turn, regions: cfg.regions, meshes: cfg.meshes, motion: cfg.motion }),
7124
7175
  rigScale: cfg.assemble.rig_scale,
package/src/build.ts CHANGED
@@ -67,7 +67,7 @@ import { createHash } from 'node:crypto';
67
67
  import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
68
68
  import { basename, dirname, join, relative, resolve, sep } from 'node:path';
69
69
  import { type AnimFrame, EncodeError, encodeApng, encodeIndexedApng, INDEXED_DEFAULTS } from './apng.ts';
70
- import { assemble, type AssembleResult, cutLines, type ExcludedCount, excludedLines, setExclusions, islandLines, setIslandSources, type IslandCount, hiddenLines, SINGLE_RUN_FACE_TAGS, singleRunHeadBox, softOcclusionLine, driftLine, limbLines, FIGURE_MASK_FILE, figuresLine, groundWarning, holeKindsLine, holeLines, measurePinholes, measureRecomposite, pinholeProblems, pinholesLine, type ProjectRule, recomposite, recompositeRecord, scenePhrase, type SeamRule, sourceInRig, stageFields, uncoveredLine } from './assemble.ts';
70
+ import { assemble, type AssembleResult, cutLines, edgeSplitLines, type ExcludedCount, excludedLines, setExclusions, islandLines, setIslandSources, type IslandCount, hiddenLines, SINGLE_RUN_FACE_TAGS, singleRunHeadBox, softOcclusionLine, driftLine, limbLines, FIGURE_MASK_FILE, figuresLine, groundWarning, holeKindsLine, holeLines, measurePinholes, measureRecomposite, pinholeProblems, pinholesLine, type ProjectRule, recomposite, recompositeRecord, scenePhrase, type SeamRule, sourceInRig, stageFields, uncoveredLine } from './assemble.ts';
71
71
  import { allocationClause, type Reducer, stageBClause, unboundedClause } from './automesh.ts';
72
72
  import { residualClause } from './autoenvelope.ts';
73
73
  import { type AutoMotionCase, failingRows, idleSchedule, localRow, motionClause, motionDeformation, motionDocument, motionInput, motionRowText, motionStimulus, motionVerdict, noStimulusProblem, prepareComparison, type ReplayCandidate, runComparison, runPreparedComparison, sourceSelfFailure, stimulusMotion, withStimulus } from './automotion.ts';
@@ -1024,6 +1024,7 @@ export function assembleStage(input: AssembleStageInput, outs: AssembleOutputs,
1024
1024
  for (const alt of altBuilt) for (const line of [...provenanceLines(alt.record.records), ...ownershipLines(alt.record.cut_ownership ?? [])]) log(` set "${alt.record.name}" ${line.trimStart()}`);
1025
1025
  // Issue #256: one line per part from an author-made layer, so it never reads as See-through's. None without one.
1026
1026
  for (const l of authorPartLines(result.parts.parts)) log(l);
1027
+ for (const l of edgeSplitLines(result.edgeSplits)) log(l);
1027
1028
  // One line per plan part an assemble.cuts entry cut, before the fringe lines: the cut is made first. None without cuts.
1028
1029
  for (const l of cutLines(result.cuts)) log(l);
1029
1030
  if (materialAsked) for (const line of materialLines({ status: 'SKIP', rows: result.cutMaterial, reason: 'assemble source readings only; check --requirements judges declared joint material' })) log(` ${line}`);
package/src/config.ts CHANGED
@@ -4,6 +4,7 @@ import { SEAM_RULES, type SeamRule } from './seamrule.ts';
4
4
  import { DEFAULT_PROJECT_RULE, GROUNDS, type Ground, PROJECT_RULES, type ProjectRule } from './projectrule.ts';
5
5
  import type { TakeDeclaration } from './takeregion.ts';
6
6
  import { paintingExtensionProblems, type PaintingExtension } from './paintingextension.ts';
7
+ import { edgeSplitProblems, type EdgeSplit } from './edgesplit.ts';
7
8
  import { baseAnchorProblems, type BaseAnchor } from './baseanchor.ts';
8
9
  import type { DepthConfig } from './depthsheets.ts';
9
10
  /**
@@ -327,6 +328,8 @@ export interface Assemble {
327
328
  extend_below_crop?: Extend[];
328
329
  /** Bounded base-painting samples assigned to named final output parts (#848). */
329
330
  extend_painting?: PaintingExtension[];
331
+ /** Painting-edge splits between plan parts before projection (#1231). */
332
+ edge_splits?: EdgeSplit[];
330
333
  patches?: Patch[];
331
334
  cuts?: Cut[];
332
335
  alternates?: AlternateSetConfig[];
@@ -1712,7 +1715,7 @@ export interface EarlyConfig {
1712
1715
  depth?: DepthConfig;
1713
1716
  key: string;
1714
1717
  seethrough: SeeThrough;
1715
- assemble: { rig_scale: number; seam?: SeamRule; project?: ProjectRule; ground?: Ground; take?: TakeDeclaration[]; editor_receipts?: EditorReceipts; head_face_underfill?: boolean; yield_refused?: boolean; stage_map?: boolean; keep_under_occluders?: string[]; require_hidden_extent?: HiddenExtentDeclaration[]; extend_painting?: PaintingExtension[]; occluders?: OccluderDeclaration[] };
1718
+ assemble: { rig_scale: number; seam?: SeamRule; project?: ProjectRule; ground?: Ground; take?: TakeDeclaration[]; editor_receipts?: EditorReceipts; head_face_underfill?: boolean; yield_refused?: boolean; stage_map?: boolean; keep_under_occluders?: string[]; require_hidden_extent?: HiddenExtentDeclaration[]; extend_painting?: PaintingExtension[]; occluders?: OccluderDeclaration[]; edge_splits?: EdgeSplit[] };
1716
1719
  }
1717
1720
 
1718
1721
  /** What plain `assemble` reads: the early config plus the plan `--propose-plan` printed. */
@@ -1790,7 +1793,7 @@ function parseEarlyConfigFrom(raw: Json, door: EarlyDoor, base: string | null, p
1790
1793
  if (door === 'layers') {
1791
1794
  if ('seethrough' in t) checkSeeThrough(c, t.seethrough);
1792
1795
  if ('assemble' in t) {
1793
- const a = c.object('config.assemble', t.assemble, sectionRequired(door, 'assemble'), ['plan', 'extend_below_crop', 'patches', 'cuts', 'alternates', 'head_face_underfill', 'yield_refused', 'stage_map', 'keep_under_occluders', 'require_hidden_extent', 'extend_painting', 'take', 'seam', 'project', 'ground', 'editor_receipts', 'occluders']);
1796
+ const a = c.object('config.assemble', t.assemble, sectionRequired(door, 'assemble'), ['plan', 'extend_below_crop', 'patches', 'cuts', 'alternates', 'head_face_underfill', 'yield_refused', 'stage_map', 'keep_under_occluders', 'require_hidden_extent', 'extend_painting', 'edge_splits', 'take', 'seam', 'project', 'ground', 'editor_receipts', 'occluders']);
1794
1797
  if (a !== null) {
1795
1798
  checkAssembleRules(c, a);
1796
1799
  if ('rig_scale' in a) c.number('config.assemble.rig_scale', a.rig_scale, 'positive');
@@ -1804,6 +1807,7 @@ function parseEarlyConfigFrom(raw: Json, door: EarlyDoor, base: string | null, p
1804
1807
  checkRequiredHiddenExtent(c, a, null);
1805
1808
  checkOccluders(c, a, null, base);
1806
1809
  if ('extend_painting' in a) checkPaintingExtensions(c, a.extend_painting);
1810
+ if ('edge_splits' in a) checkEdgeSplits(c, a.edge_splits, Array.isArray(a.plan) ? new Set(a.plan.filter((r): r is Json[] => Array.isArray(r) && typeof r[0] === 'string').map(r => r[0] as string)) : null);
1807
1811
  if ('take' in a) checkTakeLayers(c, a.take);
1808
1812
  if ('editor_receipts' in a) checkEditorReceipts(c, a.editor_receipts);
1809
1813
  if ('yield_refused' in a && typeof a.yield_refused !== 'boolean') {
@@ -2537,6 +2541,16 @@ function checkPaintingExtensions(c: Check, value: Json, names: ReadonlySet<strin
2537
2541
  }
2538
2542
  }
2539
2543
 
2544
+ function checkEdgeSplits(c: Check, value: Json, names: ReadonlySet<string> | null = null): void {
2545
+ const at = 'config.assemble.edge_splits';
2546
+ if (c.array(at, value, false)) (value as Json[]).forEach((entry, i) => {
2547
+ c.object(`${at}[${i}]`, entry, ['over', 'under', 'band'], []);
2548
+ });
2549
+ for (const p of edgeSplitProblems(value, names)) {
2550
+ if (!c.problems.some(old => old.code === p.code && old.object === p.object)) c.problems.push(p);
2551
+ }
2552
+ }
2553
+
2540
2554
  function checkRequiredHiddenExtent(c: Check, a: Record<string, Json>, names: readonly string[] | null): void {
2541
2555
  if (!('require_hidden_extent' in a)) return;
2542
2556
  const at = 'config.assemble.require_hidden_extent';
@@ -2705,7 +2719,7 @@ function checkAssembleRules(c: Check, a: Record<string, Json>): void {
2705
2719
 
2706
2720
  function checkAssemble(c: Check, v: Json, door: 'assemble' | 'full'): { parts: string[]; patches: string[]; cuts: string[] } {
2707
2721
  const required = sectionRequired(door, 'assemble');
2708
- const a = c.object('config.assemble', v, required.filter((k) => k !== 'plan'), ['plan', 'extend_below_crop', 'patches', 'cuts', 'alternates', 'head_face_underfill', 'yield_refused', 'stage_map', 'keep_under_occluders', 'require_hidden_extent', 'extend_painting', 'take', 'seam', 'project', 'ground', 'editor_receipts', 'occluders']);
2722
+ const a = c.object('config.assemble', v, required.filter((k) => k !== 'plan'), ['plan', 'extend_below_crop', 'patches', 'cuts', 'alternates', 'head_face_underfill', 'yield_refused', 'stage_map', 'keep_under_occluders', 'require_hidden_extent', 'extend_painting', 'edge_splits', 'take', 'seam', 'project', 'ground', 'editor_receipts', 'occluders']);
2709
2723
  if (a === null) return { parts: [], patches: [], cuts: [] };
2710
2724
  checkAssembleRules(c, a);
2711
2725
  if (required.includes('plan') && !('plan' in a)) {
@@ -2747,6 +2761,7 @@ function checkAssemble(c: Check, v: Json, door: 'assemble' | 'full'): { parts: s
2747
2761
  checkRequiredHiddenExtent(c, a, parts);
2748
2762
  checkOccluders(c, a, parts, null);
2749
2763
  if ('extend_painting' in a) checkPaintingExtensions(c, a.extend_painting);
2764
+ if ('edge_splits' in a) checkEdgeSplits(c, a.edge_splits, new Set(parts));
2750
2765
  if ('take' in a) checkTakeLayers(c, a.take, parts);
2751
2766
  if ('editor_receipts' in a) checkEditorReceipts(c, a.editor_receipts);
2752
2767
  if ('extend_below_crop' in a && c.array(`${p}.extend_below_crop`, a.extend_below_crop, false)) {
@@ -0,0 +1,185 @@
1
+ /** Painting-edge part split on pre-projection plan rasters (#1231). */
2
+ import type { Problem } from './errors.ts';
3
+ import { refuseIfAny } from './errors.ts';
4
+ import type { Raster } from './raster/types.ts';
5
+ import { pyRound } from './round.ts';
6
+
7
+ const EDGE_SPLIT_ALPHA = 128;
8
+ const EDGE_SPLIT_STEP = 40;
9
+
10
+ export interface EdgeSplit {
11
+ over: string;
12
+ under: string;
13
+ /** Half-open rectangle in rig pixels [x0, y0, x1, y1]; scopes the search. */
14
+ band: [number, number, number, number];
15
+ }
16
+
17
+ export interface EdgeSplitReading {
18
+ over: string;
19
+ under: string;
20
+ band: [number, number, number, number];
21
+ columns: number;
22
+ edge_share: number;
23
+ moved_px: number;
24
+ y_star_min: number;
25
+ y_star_max: number;
26
+ over_below_edge_px: number;
27
+ }
28
+
29
+ /** Shared by every config door and the callable assemble API. */
30
+ export function edgeSplitProblems(value: unknown, names: ReadonlySet<string> | null = null): Problem[] {
31
+ const at = 'config.assemble.edge_splits', out: Problem[] = [];
32
+ const fail = (code: string, object: string, detail: string): void => { out.push({ code, object, detail }); };
33
+ if (!Array.isArray(value)) {
34
+ fail('CONFIG_FIELD_TYPE', at, 'requires an array of {over, under, band}; omit it for no split');
35
+ return out;
36
+ }
37
+ value.forEach((entry: unknown, i) => {
38
+ const path = `${at}[${i}]`;
39
+ if (typeof entry !== 'object' || entry === null || Array.isArray(entry)) {
40
+ fail('CONFIG_FIELD_TYPE', path, 'requires {over, under, band}');
41
+ return;
42
+ }
43
+ const e = entry as Record<string, unknown>;
44
+ for (const key of Object.keys(e)) {
45
+ if (!['over', 'under', 'band'].includes(key)) {
46
+ fail('CONFIG_KEY_KNOWN', `${path}.${key}`, 'is unknown; only over, under and band are read');
47
+ }
48
+ }
49
+ for (const key of ['over', 'under', 'band']) {
50
+ if (!(key in e)) {
51
+ fail('CONFIG_FIELD_PRESENT', `${path}.${key}`, 'is absent and required; no part or band is inferred');
52
+ }
53
+ }
54
+ for (const key of ['over', 'under'] as const) {
55
+ if (key in e) {
56
+ if (typeof e[key] !== 'string' || e[key] === '') {
57
+ fail('CONFIG_FIELD_TYPE', `${path}.${key}`, `is ${JSON.stringify(e[key])}; a nonempty plan part name is required`);
58
+ } else if (names !== null && !names.has(e[key] as string)) {
59
+ fail('CONFIG_NAME_RESOLVES', `${path}.${key}`, `names "${e[key]}"; a part named in assemble.plan is required — known: ${[...names].join(', ')}`);
60
+ }
61
+ }
62
+ }
63
+ if (typeof e.over === 'string' && e.over !== '' && e.over === e.under) {
64
+ fail('CONFIG_PART_UNIQUE', `${path}.under`, `names "${e.under}", the same part as over; two distinct plan parts are required`);
65
+ }
66
+ if ('band' in e && !(Array.isArray(e.band) && e.band.length === 4 && e.band.every(n => Number.isSafeInteger(n) && n >= 0) && e.band[0] < e.band[2] && e.band[1] < e.band[3])) {
67
+ fail('CONFIG_FIELD_TYPE', `${path}.band`, `is ${JSON.stringify(e.band)}; [x0,y0,x1,y1] as nonnegative safe integers with x0 < x1 and y0 < y1 is required, rig pixels, upper bounds exclusive`);
68
+ }
69
+ });
70
+ return out;
71
+ }
72
+
73
+ /**
74
+ * Splits `over` and `under` plan rasters in place along the strongest painting
75
+ * vertical RGB step in `band`, before source projection.
76
+ */
77
+ export function applyEdgeSplits(
78
+ declarations: readonly EdgeSplit[],
79
+ parts: ReadonlyMap<string, Raster>,
80
+ painting: Raster,
81
+ written?: (part: string, pixel: number, cleared: boolean, priorAlpha: number) => void,
82
+ ): EdgeSplitReading[] {
83
+ refuseIfAny(edgeSplitProblems(declarations, new Set(parts.keys())));
84
+ const { width: W, height: H } = painting;
85
+ const problems: Problem[] = [];
86
+ declarations.forEach((e, i) => {
87
+ if (e.band[2] > W || e.band[3] > H) {
88
+ problems.push({
89
+ code: 'ASSEMBLE_PAINTING_BAND_INSIDE',
90
+ object: `config.assemble.edge_splits[${i}] ("${e.over}" -> "${e.under}")`,
91
+ detail: `band is [${e.band.join(', ')}]; rig is ${W}x${H}, so x1 <= ${W} and y1 <= ${H} are required; no clipping is applied`,
92
+ });
93
+ }
94
+ });
95
+ refuseIfAny(problems);
96
+
97
+ const initialAlpha = new Map<string, Uint8Array>();
98
+ for (const e of declarations) {
99
+ if (!initialAlpha.has(e.under)) {
100
+ const r = parts.get(e.under)!;
101
+ const a = new Uint8Array(W * H);
102
+ for (let i = 0; i < W * H; i++) a[i] = r.data[i * 4 + 3];
103
+ initialAlpha.set(e.under, a);
104
+ }
105
+ }
106
+
107
+ const readings: EdgeSplitReading[] = [];
108
+ for (const e of declarations) {
109
+ const overRaster = parts.get(e.over)!;
110
+ const underRaster = parts.get(e.under)!;
111
+ const underInitialAlpha = initialAlpha.get(e.under)!;
112
+ const [x0, y0, x1, y1] = e.band;
113
+ let columns = 0;
114
+ let strongEdgeColumns = 0;
115
+ let movedPx = 0;
116
+ let yStarMin = Infinity;
117
+ let yStarMax = -1;
118
+ let overBelowEdgePx = 0;
119
+
120
+ for (let x = x0; x < x1; x++) {
121
+ let yStar = -1;
122
+ let bestStep = -1;
123
+ for (let y = y0; y < y1 && y + 1 < H; y++) {
124
+ const p = (y * W + x) * 4;
125
+ if (overRaster.data[p + 3] < EDGE_SPLIT_ALPHA) continue;
126
+ const q = ((y + 1) * W + x) * 4;
127
+ const step = Math.max(
128
+ Math.abs(painting.data[p] - painting.data[q]),
129
+ Math.abs(painting.data[p + 1] - painting.data[q + 1]),
130
+ Math.abs(painting.data[p + 2] - painting.data[q + 2]),
131
+ );
132
+ if (step > bestStep) {
133
+ bestStep = step;
134
+ yStar = y;
135
+ }
136
+ }
137
+ if (yStar < 0) continue;
138
+ columns++;
139
+ if (bestStep > EDGE_SPLIT_STEP) strongEdgeColumns++;
140
+ if (yStar < yStarMin) yStarMin = yStar;
141
+ if (yStar > yStarMax) yStarMax = yStar;
142
+
143
+ for (let y = yStar + 1; y < y1; y++) {
144
+ const idx = y * W + x;
145
+ const p = idx * 4;
146
+ const oa = overRaster.data[p + 3];
147
+ if (oa >= EDGE_SPLIT_ALPHA) {
148
+ const priorUnderAlpha = underInitialAlpha[idx];
149
+ overRaster.data.fill(0, p, p + 4);
150
+ written?.(e.over, idx, true, oa);
151
+ underRaster.data[p] = painting.data[p];
152
+ underRaster.data[p + 1] = painting.data[p + 1];
153
+ underRaster.data[p + 2] = painting.data[p + 2];
154
+ underRaster.data[p + 3] = 255;
155
+ written?.(e.under, idx, false, priorUnderAlpha);
156
+ movedPx++;
157
+ } else if (oa > 0) {
158
+ overRaster.data.fill(0, p, p + 4);
159
+ written?.(e.over, idx, true, oa);
160
+ }
161
+ if (overRaster.data[p + 3] >= EDGE_SPLIT_ALPHA) overBelowEdgePx++;
162
+ }
163
+ }
164
+
165
+ readings.push({
166
+ over: e.over,
167
+ under: e.under,
168
+ band: [x0, y0, x1, y1],
169
+ columns,
170
+ edge_share: columns === 0 ? 0 : pyRound(strongEdgeColumns / columns, 3),
171
+ moved_px: movedPx,
172
+ y_star_min: columns === 0 ? 0 : yStarMin,
173
+ y_star_max: columns === 0 ? 0 : yStarMax,
174
+ over_below_edge_px: overBelowEdgePx,
175
+ });
176
+ }
177
+ return readings;
178
+ }
179
+
180
+ export function edgeSplitLines(readings: readonly EdgeSplitReading[]): string[] {
181
+ return readings.map(
182
+ (r) =>
183
+ ` edge split: "${r.over}" -> "${r.under}" band [${r.band.join(', ')}] columns=${r.columns} edge_share=${r.edge_share} moved=${r.moved_px} px y*=${r.y_star_min}..${r.y_star_max} over_below_edge_px=${r.over_below_edge_px}`,
184
+ );
185
+ }