@rig-c/parts 1.60.2 → 1.61.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.
@@ -0,0 +1,115 @@
1
+ /** Per-covered-part alternate sources; all coordinates and pixels stay in their original run. */
2
+ import type { Cut, Limb, PlanEntry } from './config.ts';
3
+ import type { OtherLimbs } from './assemble.ts';
4
+ import { refuseIfAny, type Problem } from './errors.ts';
5
+ import { readLayerTag } from './tags.ts';
6
+
7
+ export interface AlternateLayerSources {
8
+ plan: PlanEntry[];
9
+ cuts: Cut[];
10
+ limbs: Record<string, Limb>;
11
+ /** Cut output -> independently selected piece layer; its from still names the parent's own source. */
12
+ cutLayers: ReadonlyMap<string, string>;
13
+ /** Effective source name -> original logical source, only for sources split across layers. */
14
+ groups: ReadonlyMap<string, string>;
15
+ }
16
+
17
+ /** Resolve output names before the stage checks required layers. Never mutate the base plan or limb declarations. */
18
+ export function alternateLayerSources(
19
+ plan: PlanEntry[], cuts: Cut[], limbs: Record<string, Limb>, covered: ReadonlySet<string>, layers?: Readonly<Record<string, string>>,
20
+ ): AlternateLayerSources {
21
+ if (layers === undefined || Object.keys(layers).length === 0) return { plan, cuts, limbs, cutLayers: new Map(), groups: new Map() };
22
+ const problems: Problem[] = [];
23
+ const planByName = new Map(plan.map(p => [p[0], p]));
24
+ const cutByName = new Map(cuts.map(c => [c.into, c]));
25
+ const segments = Object.values(limbs).flatMap(l => l.segments);
26
+ const sourceOf = (part: string): string => segments.find(s => s.part === part)?.from ?? part;
27
+ const rowOf = (source: string): PlanEntry | undefined => planByName.get(cutByName.get(source)?.from ?? source);
28
+ for (const [part, layer] of Object.entries(layers)) {
29
+ const at = `alternate layers.${part}`;
30
+ if (!covered.has(part)) problems.push({ code: 'CONFIG_SET_LAYERS', object: at, detail: `names "${part}", which the set does not cover; name a covered, nonhidden part` });
31
+ if (rowOf(sourceOf(part)) === undefined) problems.push({ code: 'ASSEMBLE_ALT_LAYER_SOURCE', object: at, detail: `"${part}" has no planned layer source; a painting patch cannot take a run layer — declare a layer-backed plan part instead` });
32
+ if (typeof layer !== 'string' || readLayerTag(layer) === null) problems.push({ code: 'CONFIG_TAG_KNOWN', object: at, detail: `is ${JSON.stringify(layer)}; a See-through tag or author:<label> layer name is required` });
33
+ }
34
+ refuseIfAny(problems);
35
+ const occupied = new Set([...planByName.keys(), ...cutByName.keys(), ...segments.map(s => s.part)]);
36
+ const variants = new Map<string, Map<string, string>>();
37
+ const madePlans = new Map<string, PlanEntry[]>();
38
+ const madeCuts = new Map<string, Cut[]>();
39
+ const cutLayers = new Map<string, string>();
40
+ const originalTag = (source: string): string => (rowOf(source) as PlanEntry)[2];
41
+ const chosen = (part: string, source: string): string => Object.hasOwn(layers, part) ? layers[part] : originalTag(source);
42
+ const variant = (source: string, layer: string): string => {
43
+ let choices = variants.get(source);
44
+ if (choices === undefined) { choices = new Map(); variants.set(source, choices); }
45
+ const existing = choices.get(layer);
46
+ if (existing !== undefined) return existing;
47
+ let name = source;
48
+ if (choices.size > 0) {
49
+ let n = 1;
50
+ do { name = `${source}_layer_${n++}`; } while (occupied.has(name));
51
+ occupied.add(name);
52
+ }
53
+ choices.set(layer, name);
54
+ const cut = cutByName.get(source);
55
+ if (cut !== undefined) {
56
+ const parentLayer = chosen(cut.from, cut.from);
57
+ const next = { ...cut, into: name, from: variant(cut.from, parentLayer) };
58
+ if (layer !== parentLayer) cutLayers.set(name, layer);
59
+ madeCuts.set(source, [...(madeCuts.get(source) ?? []), next]);
60
+ } else {
61
+ const row = planByName.get(source) as PlanEntry;
62
+ madePlans.set(source, [...(madePlans.get(source) ?? []), [name, row[1], layer]]);
63
+ }
64
+ return name;
65
+ };
66
+ // Direct output names keep their identity; limb-only sources follow declaration order.
67
+ for (const [name] of plan) if (covered.has(name)) variant(name, chosen(name, name));
68
+ for (const cut of cuts) if (covered.has(cut.into)) variant(cut.into, chosen(cut.into, cut.into));
69
+ const selected = Object.fromEntries(Object.entries(limbs).map(([name, limb]) => [name, {
70
+ ...limb, segments: limb.segments.map(s => ({ ...s, from: variant(s.from, chosen(s.part, s.from)) })),
71
+ }]));
72
+ // Uncovered cuts can still remove art from a covered source. Keep their declared route.
73
+ for (const c of cuts) if (!variants.has(c.into)) variant(c.into, originalTag(c.into));
74
+ const consumed = new Set(segments.map(s => s.from));
75
+ for (const [name] of plan) if (!variants.has(name) && !consumed.has(name)) variant(name, originalTag(name));
76
+ const groups = new Map<string, string>();
77
+ for (const [source, choices] of variants) if (choices.size > 1) for (const name of choices.values()) groups.set(name, source);
78
+ return {
79
+ plan: plan.flatMap(([name]) => madePlans.get(name) ?? []),
80
+ cuts: cuts.flatMap(c => madeCuts.get(c.into) ?? []),
81
+ limbs: selected,
82
+ cutLayers,
83
+ groups,
84
+ };
85
+ }
86
+
87
+ /** Shared-source island rules follow every selected layer of that logical source. */
88
+ export function alternateLayerIslands(sources: readonly string[], groups: ReadonlyMap<string, string>): string[] {
89
+ return sources.flatMap(source => {
90
+ const choices = [...groups].filter(([, original]) => original === source).map(([name]) => name);
91
+ return choices.length === 0 ? [source] : choices;
92
+ });
93
+ }
94
+
95
+ /** Preserve the other limb's pose/evidence while giving each selected source its own ownership reading. */
96
+ export function alternateLayerOthers(other: OtherLimbs, groups: ReadonlyMap<string, string>): OtherLimbs {
97
+ if (groups.size === 0) return other;
98
+ const limbs: Record<string, Limb> = {}, unposed: Record<string, readonly string[]> = {}, baseArt: Record<string, OtherLimbs['baseArt'][string]> = {};
99
+ const occupied = new Set(Object.keys(other.limbs));
100
+ for (const [name, limb] of Object.entries(other.limbs)) {
101
+ let copies = [limb];
102
+ for (const source of new Set(limb.segments.map(s => s.from))) {
103
+ const choices = [...groups].filter(([, original]) => original === source).map(([effective]) => effective);
104
+ if (choices.length > 0) copies = copies.flatMap(copy => choices.map(choice => ({ ...copy, segments: copy.segments.map(s => s.from === source ? { ...s, from: choice } : s) })));
105
+ }
106
+ copies.forEach((copy, i) => {
107
+ let key = name;
108
+ if (i > 0) { let n = i; do { key = `${name}_layer_${n++}`; } while (occupied.has(key)); occupied.add(key); }
109
+ limbs[key] = copy;
110
+ unposed[key] = other.unposed[name];
111
+ baseArt[key] = other.baseArt[name];
112
+ });
113
+ }
114
+ return { ...other, limbs, unposed, baseArt };
115
+ }
package/src/assemble.ts CHANGED
@@ -322,6 +322,8 @@ export interface AssembleInput {
322
322
  patches: Patch[];
323
323
  /** `assemble.cuts`: plan parts' pixels taken into new parts by polygon (`cutPart`), placed per their `draw`. */
324
324
  cuts: Cut[];
325
+ /** Internal alternate selection: piece layer by cut output; polygon subtraction and under stay on from. */
326
+ cutLayers?: ReadonlyMap<string, string>;
325
327
  /**
326
328
  * `cuts[i].under`'s image, decoded by the caller (the stage reads no file),
327
329
  * at the cut's index: null for a cut without `under`. Absent = every cut
@@ -335,6 +337,8 @@ export interface AssembleInput {
335
337
  scene?: boolean;
336
338
  /** `config.limbs` (issue #349): the parts cut at their joints ({@link LimbCount}). Absent or empty: nothing changes. */
337
339
  limbs?: Record<string, Limb>;
340
+ /** Alternate sources with different layers retain the original joint cut bounds. */
341
+ limbSourceGroups?: ReadonlyMap<string, string>;
338
342
  /** `config.bones`, read for the limbs' joints; required with `limbs`. */
339
343
  bones?: BoneEntry[];
340
344
  /** Already normalized alternate endpoints; applied after bones have been posed. */
@@ -623,6 +627,13 @@ function squaredDistanceTo(cc: Components, W: number, label: number, at: readonl
623
627
  * set whose layer holds its one leg writes what it wrote before. A pixel the limbs wrote where the source is
624
628
  * transparent (a `cap_shape: "ball"` lower half from the cap image) is on no island and kept.
625
629
  */
630
+ /** Layer variants share the original source's segment line for ownership, without changing its pixel source. */
631
+ function logicalSourceLimb(limb: Limb, source: string, groups: ReadonlyMap<string, string>): Limb {
632
+ if (!groups.has(source)) return limb;
633
+ const original = groups.get(source);
634
+ return { ...limb, segments: limb.segments.map(s => (groups.get(s.from) ?? s.from) === original ? { ...s, from: source } : s) };
635
+ }
636
+
626
637
  function keepJointIslands(
627
638
  sources: readonly string[],
628
639
  limbs: Readonly<Record<string, Limb>>,
@@ -635,6 +646,7 @@ function keepJointIslands(
635
646
  floorShare: number,
636
647
  others?: OtherLimbs,
637
648
  tips?: Record<string, [number, number]>,
649
+ sourceGroups: ReadonlyMap<string, string> = new Map(),
638
650
  ): { counts: IslandCount[]; splits: SplitCount[]; problems: Problem[] } {
639
651
  const counts: IslandCount[] = [];
640
652
  const splits: SplitCount[] = [];
@@ -650,7 +662,7 @@ function keepJointIslands(
650
662
  const n = reading.candidates.length;
651
663
  if (n < 2) {
652
664
  // Issue #609: one island may hold both limbs, overlapping; the island rule cannot part them, the segment lines can.
653
- if (n === 1 && others !== undefined) splitOneIsland(src, b, limbs, places, parts, pieces, others, W, H, splits, problems);
665
+ if (n === 1 && others !== undefined) splitOneIsland(src, b, limbs, places, parts, pieces, others, W, H, splits, problems, sourceGroups);
654
666
  continue;
655
667
  }
656
668
  const numberOf = new Map(reading.candidates.map((l, i) => [l, i + 1]));
@@ -864,6 +876,7 @@ function splitOneIsland(
864
876
  H: number,
865
877
  splits: SplitCount[],
866
878
  problems: Problem[],
879
+ sourceGroups: ReadonlyMap<string, string> = new Map(),
867
880
  ): void {
868
881
  const mine = parts.map((q, i) => ({ q, i })).filter(({ q }) => q.of === src);
869
882
  if (mine.length === 0) return;
@@ -903,9 +916,9 @@ function splitOneIsland(
903
916
  // The same source selection applies to every segment, without reading a part name or a layer tag.
904
917
  const taking = (l: string, all: Readonly<Record<string, Limb>>): Limb => others.line === 'whole-limb'
905
918
  ? all[l]
906
- : { ...all[l], segments: all[l].segments.filter((sg) => sg.from === src) };
919
+ : { ...all[l], segments: logicalSourceLimb(all[l], src, sourceGroups).segments.filter((sg) => sg.from === src) };
907
920
  const polyOf = (l: string, all: Readonly<Record<string, Limb>>): Array<[number, number]> =>
908
- others.line === 'whole-limb' ? limbPolyline(all[l], places) : sourceLimbTarget(all[l], src, places).line;
921
+ others.line === 'whole-limb' ? limbPolyline(all[l], places) : sourceLimbTarget(logicalSourceLimb(all[l], src, sourceGroups), src, places).line;
909
922
  for (const [l, all] of [...ownNames.map((l) => [l, limbs] as const), ...posed.map((l) => [l, others.limbs] as const)]) {
910
923
  const selected = taking(l, all);
911
924
  const line = polyOf(l, all);
@@ -1011,6 +1024,7 @@ function assignCapOwnership(
1011
1024
  sources: readonly string[], limbs: Readonly<Record<string, Limb>>, bones: readonly BoneEntry[],
1012
1025
  parts: readonly LimbPart[], pieces: readonly Built[], sourceOf: (name: string) => Built | null,
1013
1026
  capFrom: ReadonlyArray<CapFrom | null>, W: number, H: number, others?: OtherLimbs, tips?: Record<string, [number, number]>,
1027
+ sourceGroups: ReadonlyMap<string, string> = new Map(),
1014
1028
  ): { counts: SplitCount[]; problems: Problem[] } {
1015
1029
  const counts: SplitCount[] = [], problems: Problem[] = [];
1016
1030
  if (others === undefined) return { counts, problems };
@@ -1041,8 +1055,8 @@ function assignCapOwnership(
1041
1055
  detail: `holds ${on} cap pixels where the base draws ${l}, but the set does not pose ${unposed.map((b) => `"${b}"`).join(', ')}; a supplied pose for the other limb is required to assign the cap by its target source segments, never its base place` });
1042
1056
  }
1043
1057
  if (problems.length > before || posed.length === 0) return;
1044
- const own = sourceLimbTarget(limbs[q.limb], q.of, places);
1045
- const other = posed.map((l) => ({ l, target: sourceLimbTarget(others.limbs[l], q.of, places) }));
1058
+ const own = sourceLimbTarget(logicalSourceLimb(limbs[q.limb], q.of, sourceGroups), q.of, places);
1059
+ const other = posed.map((l) => ({ l, target: sourceLimbTarget(logicalSourceLimb(others.limbs[l], q.of, sourceGroups), q.of, places) }));
1046
1060
  for (const { l, target } of [{ l: q.limb, target: own }, ...other]) {
1047
1061
  if (target.missingEndBone !== null) problems.push({ code: 'ASSEMBLE_ALT_LIMB_POSE', object: `config.limbs.${l} (part "${q.part}", source-transparent cap, bone "${target.missingEndBone}")`,
1048
1062
  detail: `takes "${q.of}" on a segment with no supplied end; an explicit bone tip or the following segment's joint in the set's pose is required to assign its cap, never an invented endpoint` });
@@ -3800,7 +3814,9 @@ function cutLimbs(
3800
3814
  hiddenOf: (part: string) => HiddenArt | null = () => null,
3801
3815
  readHidden: (layer: string, by: string) => void = () => undefined,
3802
3816
  tips?: Record<string, [number, number]>,
3817
+ sourceGroups: ReadonlyMap<string, string> = new Map(),
3803
3818
  ): { parts: LimbPart[]; pieces: Built[]; counts: LimbCount[]; capFrom: Array<CapFrom | null> } {
3819
+ const logical = (source: string): string => sourceGroups.get(source) ?? source;
3804
3820
  const names = Object.keys(limbs);
3805
3821
  if (names.length === 0) return { parts: [], pieces: [], counts: [], capFrom: [] };
3806
3822
  const problems: Problem[] = [];
@@ -3809,7 +3825,7 @@ function cutLimbs(
3809
3825
  for (const l of names) {
3810
3826
  const covering = limbs[l].split !== undefined;
3811
3827
  limbs[l].segments.forEach((sg, k) =>
3812
- parts.push({ limb: l, segment: k, part: sg.part, of: sg.from, ...(covering ? { covering: true } : {}), record: { name: l, segment: k, of: sg.from, bone: sg.bone, ...(k === 0 ? {} : { joint: sg.joint as string, ...(sg.range === undefined ? {} : { range: [sg.range[0], sg.range[1]] as [number, number] }) }) } }),
3828
+ parts.push({ limb: l, segment: k, part: sg.part, of: sg.from, ...(covering ? { covering: true } : {}), record: { name: l, segment: k, of: logical(sg.from), bone: sg.bone, ...(k === 0 ? {} : { joint: sg.joint as string, ...(sg.range === undefined ? {} : { range: [sg.range[0], sg.range[1]] as [number, number] }) }) } }),
3813
3829
  );
3814
3830
  }
3815
3831
  const polylines = new Map(names.map((l) => [l, limbPolyline(limbs[l], places)]));
@@ -3850,10 +3866,11 @@ function cutLimbs(
3850
3866
  const counts: LimbCount[] = [];
3851
3867
  // Issue #603: which count of its cap each pixel of a lower segment's cap box was counted in, for the set exclusion.
3852
3868
  const capFrom: Array<CapFrom | null> = parts.map(() => null);
3869
+ const jobs: Array<{ src: string; b: Built; on: string[]; own: Int32Array; before: number }> = [];
3853
3870
  for (const src of sources) {
3854
3871
  const b = builtOf(src);
3855
3872
  if (b === null) continue;
3856
- const on = names.filter((l) => limbs[l].segments.some((sg) => sg.from === src));
3873
+ const on = names.filter((l) => limbs[l].segments.some((sg) => logical(sg.from) === logical(src)));
3857
3874
  const own = new Int32Array(W * H).fill(-1);
3858
3875
  const before = opaqueOf(b.r);
3859
3876
  if (before === 0) {
@@ -3878,11 +3895,17 @@ function cutLimbs(
3878
3895
  const underPolys = underNames.map((l) => polylines.get(l) as Array<[number, number]>);
3879
3896
  assignCrossedLimbs(coverIdx, polylines.get(coverLimb) as Array<[number, number]>, limbs[coverLimb].split as NonNullable<Limb['split']>, underIndices, underPolys, b.r, OPAQUE_ALPHA_ABOVE, own);
3880
3897
  }
3898
+ owners.set(src, own);
3899
+ jobs.push({ src, b, on, own, before });
3900
+ }
3901
+ // Place every cut on the selected lower source before any source is split.
3902
+ // A per-part layer change does not turn a logical elbow into two uncut layers.
3903
+ for (const { src, b, on, own } of jobs) {
3881
3904
  // Issue #360 (item 14): each joint of this part that declares cut_band has its cut placed, on the limb's own art.
3882
3905
  for (const l of on) {
3883
3906
  const li = names.indexOf(l);
3884
3907
  limbs[l].segments.forEach((sg, k) => {
3885
- if (k === 0 || sg.cut_band === undefined || sg.from !== src || limbs[l].segments[k - 1].from !== src) return;
3908
+ if (k === 0 || sg.cut_band === undefined || sg.from !== src || logical(limbs[l].segments[k - 1].from) !== logical(src)) return;
3886
3909
  const line = (lines.get(l) as Array<JointLine | null>)[k] as JointLine;
3887
3910
  const art = (x: number, y: number): boolean => x >= 0 && y >= 0 && x < W && y < H && own[y * W + x] === li && b.r.data[(y * W + x) * 4 + 3] > OPAQUE_ALPHA_ABOVE;
3888
3911
  const luma = (x: number, y: number): number => luma601(b.r.data[(y * W + x) * 4], b.r.data[(y * W + x) * 4 + 1], b.r.data[(y * W + x) * 4 + 2]);
@@ -3901,12 +3924,15 @@ function cutLimbs(
3901
3924
  placements.set(`${l}/${k}`, placed);
3902
3925
  });
3903
3926
  }
3927
+ }
3928
+ for (const { src, b, on, own, before: wholeBefore } of jobs) {
3929
+ let selectedBefore = 0;
3904
3930
  const segOverride = new Int32Array(W * H).fill(-1);
3905
3931
  const segAt = (l: string, x: number, y: number): number => {
3906
3932
  const segs = limbs[l].segments;
3907
- const first = segs.findIndex((sg) => sg.from === src);
3933
+ const first = segs.findIndex((sg) => logical(sg.from) === logical(src));
3908
3934
  let last = first;
3909
- while (last + 1 < segs.length && segs[last + 1].from === src) last++;
3935
+ while (last + 1 < segs.length && logical(segs[last + 1].from) === logical(src)) last++;
3910
3936
  return segmentOf(cutLines.get(l) as Array<JointLine | null>, first, last, x, y);
3911
3937
  };
3912
3938
  // Issue #400: when two forearm segments share `src` and their hand regions overlap, the overlap goes to the front
@@ -3914,7 +3940,7 @@ function cutLimbs(
3914
3940
  const forearms = on.flatMap((l) => {
3915
3941
  const li = names.indexOf(l);
3916
3942
  return limbs[l].segments.flatMap((sg, k) => {
3917
- if (k === 0 || sg.joint !== 'elbow' || sg.from !== src) return [];
3943
+ if (k === 0 || sg.joint !== 'elbow' || logical(sg.from) !== logical(src)) return [];
3918
3944
  const me = places.get(sg.bone) as BonePlace;
3919
3945
  return me.end === null ? [] : [{ limb: li, seg: k, elbow: me.at, wrist: me.end, isSeg: (x: number, y: number): boolean => segAt(l, x, y) === k }];
3920
3946
  });
@@ -3931,6 +3957,8 @@ function cutLimbs(
3931
3957
  const l = names[own[p]];
3932
3958
  const k = segOverride[p] >= 0 ? segOverride[p] : segAt(l, x, y);
3933
3959
  const at = parts.findIndex((q) => q.limb === l && q.segment === k);
3960
+ if (parts[at].of !== src) continue;
3961
+ if (b.r.data[p * 4 + 3] > OPAQUE_ALPHA_ABOVE) selectedBefore++;
3934
3962
  rasters[at].data.set(b.r.data.subarray(p * 4, p * 4 + 4), p * 4);
3935
3963
  if (b.region === null || b.region.data[p] === 1) regions[at].data[p] = 1;
3936
3964
  }
@@ -3938,6 +3966,7 @@ function cutLimbs(
3938
3966
  owners.set(src, own);
3939
3967
  const shares = parts.map((q, i) => ({ q, i })).filter(({ q }) => q.of === src);
3940
3968
  const counted = shares.map(({ q, i }) => ({ part: q.part, px: opaqueOf(rasters[i]) }));
3969
+ const before = sourceGroups.has(src) ? selectedBefore : wholeBefore;
3941
3970
  const sum = counted.reduce((a, c) => a + c.px, 0);
3942
3971
  if (sum !== before) {
3943
3972
  problems.push({ code: 'ASSEMBLE_COUNTS_ADD_UP', object: `part "${src}" (config.limbs)`, detail: `opaque px: ${before} before the limbs, ${sum} over their parts; equal is required (a bug in the assembler, not in the inputs)` });
@@ -4379,6 +4408,12 @@ export function assemble(input: AssembleInput): AssembleResult {
4379
4408
  // Issue #490: when generation.control.skeleton is present, split merged arm layers (or refuse when sleeve and drape share one colour).
4380
4409
  const full = input.keySkeleton === undefined ? fullArmSplit : splitMergedArmRuns(fullArmSplit, input.resolution, frame, source.width, source.height, input.keySkeleton);
4381
4410
  const plan = mergedArmSplitPlan(armSplitPlan(input.plan, input.armSplit), full);
4411
+ const cutLayerPlan: PlanEntry[] = input.cuts.flatMap(c => {
4412
+ const tag = input.cutLayers?.get(c.into);
4413
+ const parent = plan.find(([name]) => name === c.from);
4414
+ return tag === undefined || parent === undefined ? [] : [[c.into, parent[1], tag]];
4415
+ });
4416
+ const sourcePlan = plan.flatMap(row => [row, ...cutLayerPlan.filter(([name]) => input.cuts.some(c => c.into === name && c.from === row[0]))]);
4382
4417
  // Issue #492: in two-run mode, check that head:face covers >= 75% of full:face's silhouette on the head canvas
4383
4418
  // (after applying head_face_underfill when declared). Skip only on a single-run subset (a mouth-only or clothes-only alternate).
4384
4419
  const checkHeadFace =
@@ -4390,7 +4425,7 @@ export function assemble(input: AssembleInput): AssembleResult {
4390
4425
  const head = headFacePrep.head;
4391
4426
  const padRecord = singleRunPadRecord(single, source.width, source.height, input.resolution, frame);
4392
4427
  if (single) checkSingleRun(full, plan, extend);
4393
- checkPlanAgainstRuns(plan, extend, full, head);
4428
+ checkPlanAgainstRuns(sourcePlan, extend, full, head);
4394
4429
  const { W, H } = frame;
4395
4430
  const srcr = sourceInRig(source, W, H);
4396
4431
  // Issue #359: a part's hidden-art layer is the under of a cut that names none — and, with one named, a refusal, since
@@ -4433,9 +4468,9 @@ export function assemble(input: AssembleInput): AssembleResult {
4433
4468
  const layers = runLayers(set, input.resolution);
4434
4469
  if (run === 'full') fullTags.push(...layers.filter((l) => l.opaqueRunPx > 0).map((l) => l.tag));
4435
4470
  const rigLayers = layers.map((l) => layerToRig(l.canvas, frame, run));
4436
- const rank = planRanks(layers.map((l) => l.tag), run, plan);
4471
+ const rank = planRanks(layers.map((l) => l.tag), run, sourcePlan);
4437
4472
  const keep = layers.map((l, i): Mask | null => {
4438
- if (input.limbUnderCover !== true || !plan.some(([name, ru, tag]) => limbPlans.has(name) && ru === run && tag === l.tag)) return null;
4473
+ if (input.limbUnderCover !== true || ![...plan, ...cutLayerPlan].some(([name, ru, tag]) => (limbPlans.has(name) || limbSources.has(name)) && ru === run && tag === l.tag)) return null;
4439
4474
  const mask = newMask(W, H);
4440
4475
  const cover = newMask(W, H);
4441
4476
  for (let p = 0; p < W * H; p++) {
@@ -4569,7 +4604,7 @@ export function assemble(input: AssembleInput): AssembleResult {
4569
4604
  }
4570
4605
  return { x0, y0, x1, y1, opaque };
4571
4606
  };
4572
- plan.forEach(([name, run, tag], pi) => {
4607
+ const buildSource = (name: string, run: Run, tag: string, pi: number): Built | null => {
4573
4608
  const key = `${run}:${tag}`;
4574
4609
  const src = rig.get(key) as Raster;
4575
4610
  const r: Raster = { width: W, height: H, data: new Uint8ClampedArray(src.data) };
@@ -4593,9 +4628,16 @@ export function assemble(input: AssembleInput): AssembleResult {
4593
4628
  object: `part "${name}" (${key}, config.assemble.plan[${pi}])`,
4594
4629
  detail: `has 0 pixels with alpha above ${OPAQUE_ALPHA_ABOVE} in the rig (${x1 < 0 ? 'no pixel at all' : 'only fringe below it'}; ${ghost[key]} ghost px removed in the run); a part with at least one opaque pixel is required — drop it from the plan or take the tag from the other run`,
4595
4630
  });
4596
- return;
4631
+ return null;
4597
4632
  }
4598
- built[pi] = { key, r, st, extendKeys, trace, merged, region: null };
4633
+ return { key, r, st, extendKeys, trace, merged, region: null };
4634
+ };
4635
+ plan.forEach(([name, run, tag], pi) => { built[pi] = buildSource(name, run, tag, pi); });
4636
+ // Snapshot independent piece pixels before any parent's subtraction or under fill.
4637
+ const cutSources = cuts.map(c => {
4638
+ const pi = plan.findIndex(([name]) => name === c.from);
4639
+ const row = plan[pi], tag = input.cutLayers?.get(c.into);
4640
+ return tag === undefined ? null : buildSource(c.from, row[1], tag, pi);
4599
4641
  });
4600
4642
  const silhouette = seamRule === 'silhouette' || patches.some((q) => q.alpha === 'silhouette') ? figureSilhouette(srcr) : null;
4601
4643
  const cut = patches.map((q, i) => {
@@ -4729,6 +4771,15 @@ export function assemble(input: AssembleInput): AssembleResult {
4729
4771
  cutCounts.push(c);
4730
4772
  });
4731
4773
  });
4774
+ // Parent partition counts and under use the removed parent art above. Only
4775
+ // the emitted piece (and any limb cut from it) reads this independent source.
4776
+ cutSources.forEach((source, i) => {
4777
+ if (source === null) return;
4778
+ const m = cutMasks[i], r = newRaster(W, H);
4779
+ for (let p = 0; p < W * H; p++) if (m.data[p] === 1) r.data.set(source.r.data.subarray(p * 4, p * 4 + 4), p * 4);
4780
+ if (opaqueOf(r) === 0) empty.push({ code: 'ASSEMBLE_CUT_PIXELS', object: `config.assemble.cuts[${i}] (part "${cuts[i].into}")`, detail: `takes 0 opaque pixels from selected ${source.key}; draw its polygon over that layer's art` });
4781
+ pieces[i] = { ...source, r, region: m, merged: mergedIn(source, m) };
4782
+ });
4732
4783
  refuseIfAny(empty);
4733
4784
  // In cut order, as the config lists them.
4734
4785
  cutCounts.sort((a, b) => cuts.findIndex((q) => q.into === a.into) - cuts.findIndex((q) => q.into === b.into));
@@ -4749,7 +4800,7 @@ export function assemble(input: AssembleInput): AssembleResult {
4749
4800
  const ci = cuts.findIndex((q) => q.into === name);
4750
4801
  return ci >= 0 ? pieces[ci] : null;
4751
4802
  };
4752
- const lim = cutLimbs(input.limbs ?? {}, input.bones ?? [], input.caps ?? new Map(), W, H, limbSource, opaqueOf, mergedIn, count, (name) => hiddenArt.get(name) ?? null, (layer, by) => hiddenUses.get(layer)?.push(by), input.boneTips);
4803
+ const lim = cutLimbs(input.limbs ?? {}, input.bones ?? [], input.caps ?? new Map(), W, H, limbSource, opaqueOf, mergedIn, count, (name) => hiddenArt.get(name) ?? null, (layer, by) => hiddenUses.get(layer)?.push(by), input.boneTips, input.limbSourceGroups);
4753
4804
  // Issue #564: and the cap a run's own layer fills above its upper joint, read once the limbs are cut.
4754
4805
  if (bands !== null) refuseIfAny(limbBands(cuts, pieces, input.limbs ?? {}, input.bones ?? [], W, H, (l, k) => lim.parts.find((q) => q.limb === l && q.segment === k)?.record.cap, input.boneTips).problems);
4755
4806
  const limbPieces = lim.pieces;
@@ -4762,10 +4813,10 @@ export function assemble(input: AssembleInput): AssembleResult {
4762
4813
  const islandKept =
4763
4814
  (input.limbIslands ?? []).length === 0
4764
4815
  ? { counts: [], splits: [], problems: [] }
4765
- : keepJointIslands(input.limbIslands ?? [], input.limbs ?? {}, input.bones ?? [], lim.parts, limbPieces, limbSource, W, H, input.islandFloor ?? ISLAND_FLOOR_SHARE, input.otherLimbs, input.boneTips);
4816
+ : keepJointIslands(input.limbIslands ?? [], input.limbs ?? {}, input.bones ?? [], lim.parts, limbPieces, limbSource, W, H, input.islandFloor ?? ISLAND_FLOOR_SHARE, input.otherLimbs, input.boneTips, input.limbSourceGroups);
4766
4817
  refuseIfAny(islandKept.problems);
4767
4818
  const capAssigned = input.capOwnership === 'source' ? { counts: [], problems: [] }
4768
- : assignCapOwnership(input.limbIslands ?? [], input.limbs ?? {}, input.bones ?? [], lim.parts, limbPieces, limbSource, lim.capFrom, W, H, input.otherLimbs, input.boneTips);
4819
+ : assignCapOwnership(input.limbIslands ?? [], input.limbs ?? {}, input.bones ?? [], lim.parts, limbPieces, limbSource, lim.capFrom, W, H, input.otherLimbs, input.boneTips, input.limbSourceGroups);
4769
4820
  refuseIfAny(capAssigned.problems);
4770
4821
 
4771
4822
 
package/src/build.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { alternateLayerSources, alternateLayerIslands, alternateLayerOthers } from './alternatelayers.ts';
1
2
  /**
2
3
  * The stages as callable units, and `build`, which runs three of them in a row.
3
4
  *
@@ -334,6 +335,7 @@ export function assembleStage(input: AssembleStageInput, outs: AssembleOutputs,
334
335
  full?: string;
335
336
  head?: string;
336
337
  parts?: string[];
338
+ layers?: Record<string, string>;
337
339
  hides?: string[];
338
340
  head_box?: [number, number, number, number];
339
341
  cuts?: Cut[];
@@ -352,6 +354,7 @@ export function assembleStage(input: AssembleStageInput, outs: AssembleOutputs,
352
354
  full: cli?.full ?? (a.full === undefined ? undefined : resolve(configDir, a.full)),
353
355
  head: cli !== undefined ? cli.head : a.head === undefined ? undefined : resolve(configDir, a.head),
354
356
  parts: a.parts,
357
+ layers: a.layers,
355
358
  hides: a.hides,
356
359
  head_box: a.head_box,
357
360
  cuts: a.cuts,
@@ -466,8 +469,8 @@ export function assembleStage(input: AssembleStageInput, outs: AssembleOutputs,
466
469
  const hidesSet = new Set(alt.hides ?? []);
467
470
  const declaredSlots = alt.parts !== undefined ? alt.parts.filter((p) => !hidesSet.has(p)) : baseSlots.filter((p) => !hidesSet.has(p));
468
471
  const coveredSet = new Set(declaredSlots);
469
- const rawCuts = alt.cuts !== undefined ? alt.cuts : fields.cuts.filter((c) => coveredSet.has(c.into) && coveredSet.has(c.from)).map((c) => ({ ...c, under: undefined }));
470
- const altLimbs: Record<string, Limb> = {};
472
+ let rawCuts = alt.cuts !== undefined ? alt.cuts : fields.cuts.filter((c) => coveredSet.has(c.into) && coveredSet.has(c.from)).map((c) => ({ ...c, under: undefined }));
473
+ let altLimbs: Record<string, Limb> = {};
471
474
  if (fields.limbs !== undefined) {
472
475
  for (const [ln, limb] of Object.entries(fields.limbs)) {
473
476
  if (limb.segments.every((sg) => coveredSet.has(sg.part))) {
@@ -485,11 +488,21 @@ export function assembleStage(input: AssembleStageInput, outs: AssembleOutputs,
485
488
  neededPlan.add(name);
486
489
  }
487
490
  }
488
- const altPlan: PlanEntry[] = fields.plan
491
+ let altPlan: PlanEntry[] = fields.plan
489
492
  .filter(([name]) => neededPlan.has(name))
490
493
  .map(([name, run, tag]): PlanEntry => (altRuns.single ? [name, 'full', tag] : [name, run, tag]));
494
+ const originalAltLimbs = altLimbs;
495
+ const selectedLayers = alternateLayerSources(altPlan, rawCuts, altLimbs, coveredSet, alt.layers);
496
+ altPlan = selectedLayers.plan;
497
+ rawCuts = selectedLayers.cuts;
498
+ altLimbs = selectedLayers.limbs;
491
499
  let missingLayer = false;
492
- for (const [name, run, tag] of altPlan) {
500
+ const selectedCutLayers: PlanEntry[] = rawCuts.flatMap(c => {
501
+ const tag = selectedLayers.cutLayers.get(c.into);
502
+ const parent = altPlan.find(([name]) => name === c.from);
503
+ return tag === undefined || parent === undefined ? [] : [[c.into, parent[1], tag]];
504
+ });
505
+ for (const [name, run, tag] of [...altPlan, ...selectedCutLayers]) {
493
506
  const l = altRuns[run].layers.find((x) => x.name === tag);
494
507
  if (l === undefined || l.opaquePx === 0) {
495
508
  altProblems.push({
@@ -520,12 +533,13 @@ export function assembleStage(input: AssembleStageInput, outs: AssembleOutputs,
520
533
  let altDrawnLength: Record<string, number> | undefined;
521
534
  let altRegistration: { offset: [number, number]; scale: number } | undefined;
522
535
  // Issue #588: a subset set that names one limb side keeps, of a layer that holds more than one island, the one its joints fall on.
523
- const altIslands = alt.parts === undefined || input.setIslands === 'all' ? [] : setIslandSources(fields.limbs ?? {}, altLimbs);
536
+ const originalIslands = alt.parts === undefined || input.setIslands === 'all' ? [] : setIslandSources(fields.limbs ?? {}, originalAltLimbs);
537
+ const altIslands = alternateLayerIslands(originalIslands, selectedLayers.groups);
524
538
  // Issue #609: the limbs of those layers the set does not carry — the other leg of a two-leg layer.
525
539
  const otherLimbs: Record<string, Limb> =
526
540
  input.setSplit === 'connectivity'
527
541
  ? {}
528
- : Object.fromEntries(Object.entries(fields.limbs ?? {}).filter(([ln, l]) => !(ln in altLimbs) && l.segments.some((sg) => altIslands.includes(sg.from))));
542
+ : Object.fromEntries(Object.entries(fields.limbs ?? {}).filter(([ln, l]) => !(ln in altLimbs) && l.segments.some((sg) => originalIslands.includes(sg.from))));
529
543
  const otherBones = new Set(Object.values(otherLimbs).flatMap((l) => l.segments.map((sg) => sg.bone)));
530
544
  // The bones the set places: by its skeleton, or by the angles it states; every other bone keeps the base's place unless an ancestor moved.
531
545
  const setPlaced = new Set<string>();
@@ -619,9 +633,11 @@ export function assembleStage(input: AssembleStageInput, outs: AssembleOutputs,
619
633
  headBox: altHeadBox,
620
634
  rigScale: fields.rigScale,
621
635
  plan: altPlan,
636
+ ...(selectedLayers.groups.size === 0 ? {} : { limbSourceGroups: selectedLayers.groups }),
622
637
  extend: altExtend,
623
638
  patches: altPatches,
624
639
  cuts: altCuts,
640
+ ...(selectedLayers.cutLayers.size === 0 ? {} : { cutLayers: selectedLayers.cutLayers }),
625
641
  under: altUnder,
626
642
  ...(Object.keys(altLimbs).length > 0 ? { limbs: altLimbs, bones: altBones } : {}),
627
643
  ...(fields.scene === undefined ? {} : { scene: fields.scene }),
@@ -631,7 +647,7 @@ export function assembleStage(input: AssembleStageInput, outs: AssembleOutputs,
631
647
  projectRule: input.project,
632
648
  ...(altExclude.length === 0 ? {} : { exclude: altExclude }),
633
649
  ...(altIslands.length === 0 ? {} : { limbIslands: altIslands }),
634
- ...(altOthers === undefined ? {} : { otherLimbs: altOthers }),
650
+ ...(altOthers === undefined ? {} : { otherLimbs: alternateLayerOthers(altOthers, selectedLayers.groups) }),
635
651
  });
636
652
  } catch (err) {
637
653
  if (err instanceof PartsError) {
@@ -1721,17 +1737,26 @@ export function sweepCheckLines(line: SweepLine, steps: ReadonlyMap<string, { le
1721
1737
  * read nothing of (its SKIP) or the line could not read. A SKIP with nothing declared prints its reason alone.
1722
1738
  */
1723
1739
  export function motionSeamLines(line: MotionSeamLine, plant: MotionSeamPlant = {}): string[] {
1724
- if (line.worlds === undefined && line.status === 'SKIP' && line.rows.length === 0 && line.pairs.every((p) => p.unread === undefined)) return [`${MOTION_SEAM_LINE}: SKIP — ${String(line.reason)}`];
1740
+ const unmeasured = (line.roots?.unmeasured ?? []).map(root => `root pair for ${root.limb} (${root.part}, bone "${root.bone}", parent "${root.parent}", candidates ${root.candidates.join('/')}): SKIP — ${root.reason}`);
1741
+ const rootStatus = line.roots === undefined ? '' : '; body-root gap-only gate ' + line.roots.status + ' (' + line.roots.pairs.length + ' pair(s)); ghost ownership unavailable' + (line.roots.reason === undefined ? '' : ' — ' + line.roots.reason);
1742
+ if (line.worlds === undefined && line.status === 'SKIP' && line.rows.length === 0 && line.pairs.every((p) => p.unread === undefined)) return [`${MOTION_SEAM_LINE}: SKIP — ${String(line.reason)}${unmeasured.length === 0 ? '' : rootStatus}`, ...unmeasured];
1725
1743
  const read = `${line.pairs.length} declared pair(s) in ${line.animations.length} animation(s) (${line.animations.join(', ')}), read by rigc render --seam at ${line.fps} fps on the build as played`;
1726
1744
  const head =
1727
1745
  line.status === 'SKIP'
1728
- ? `${MOTION_SEAM_LINE}: SKIP — ${String(line.reason)}; ${read}`
1729
- : `${MOTION_SEAM_LINE}: ${line.status} — ${read}: ${line.warnings} warning(s), never a bar; ${line.floor}`;
1746
+ ? `${MOTION_SEAM_LINE}: SKIP — ${String(line.reason)}; ${read}${unmeasured.length === 0 ? '' : rootStatus}`
1747
+ : `${MOTION_SEAM_LINE}: ${line.status} — ${read}: ${line.warnings} warning(s), never a bar${rootStatus}; ${line.floor}`;
1730
1748
  return [
1731
1749
  head,
1750
+ ...unmeasured,
1732
1751
  ...line.pairs.filter((p) => p.unread !== undefined).map((p) => `seam "${p.pair}" (${p.declared.join('; ')}): not read — ${String(p.unread)}`),
1733
1752
  ...line.rows.filter((r) => r.status === 'skip').map((r) => `seam "${r.pair}" in "${r.animation}": SKIP — rigc read no band on any of the ${r.drawn} frame(s) both slots draw, so there is no seam to read`),
1734
- ...(plant.silent === true ? [] : line.rows.filter((r) => r.opens.length > 0).map(motionSeamWarnText)),
1753
+ ...(plant.silent === true ? [] : line.rows.filter((r) => r.opens.length > 0).map(r => line.pairs.some(p => p.pair === r.pair && p.root !== undefined)
1754
+ ? `FAIL seam "${r.pair}" opens on ${r.opens.length} frame(s) ${frameRuns(r.opens)} max ${r.max_px} px in "${r.animation}" — body-root GAP over the one-cell floor (gap-only)`
1755
+ : motionSeamWarnText(r))),
1756
+ ...line.rows.flatMap(r => (r.coverage ?? []).map(h =>
1757
+ `INFO seam "${r.pair}" in "${r.animation}" frame ${h.index}: root GAP raw ${h.px}; whole-box ${h.status} — ${h.reason}${h.status === 'exempt' ? '; not gated' : '; entire original GAP count retained'}${h.evidence === undefined ? '' : '; evidence: ' + h.evidence}; exact GAP partition deferred to rig-c/core#1556`)),
1758
+ ...line.rows.filter(r => r.ghost_info !== undefined && r.ghost_info.frames > 0).map(r =>
1759
+ `INFO seam "${r.pair}" in "${r.animation}": ghost ${r.ghost_info?.max_px} cells on ${r.ghost_info?.frames} frame(s); owner unavailable in this rigc-seam/1 reading; see rig-c/core#1555; not gated (gap-only)`),
1735
1760
  ...line.rows.filter((r) => r.opens.length === 0 && r.under_floor.length > 0).map((r) => `seam "${r.pair}" in "${r.animation}": under the floor — rigc names ${r.under_floor.length} frame(s) open ${frameRuns(r.under_floor)}, each opening one cell thick`),
1736
1761
  ...(line.worlds === undefined ? [] : (['default', 'still'] as const).flatMap(name => {
1737
1762
  const w = line.worlds?.[name];
@@ -1800,6 +1825,7 @@ export function checkStage(input: CheckStageInput, rigc: RigcRunner, bin: string
1800
1825
  ` seam${fig.seam_border === undefined ? '' : ` (config.scene: ${fig.seam_border.frame_px_left_out} frame px on the painting's border rows and columns left out, ${fig.seam_border.px_over_40_left_out} of them over ${SEAM_PX_LEVEL})`}: setup pose at ${r.seamViewport.pixelWidth}x${r.seamViewport.pixelHeight}, scale ${r.seamViewport.scale.toFixed(4)}: mean |d| ${fig.seam_mean} (<= ${SEAM_MEAN_BAR.toFixed(1)}), ` +
1801
1826
  `${fig.seam_px_over_40} px over ${SEAM_PX_LEVEL}, ${fig.seam_frame_scale === null || fig.seam_px_over_40 === null ? '' : seamRigPxText(fig.seam_px_over_40, fig.seam_frame_scale)} rig px (the count / s²; <= ${SEAM_PX_BAR}), ${fig.seam_px_over_80} px over ${SEAM_PX_LEVEL_HIGH} (reported)`,
1802
1827
  );
1828
+ if (fig.seam_scope !== undefined) log(` seam scope: ${fig.seam_scope.mode}, denominator ${fig.seam_scope.denominator_px} source cells; union ${fig.seam_scope.domain?.viewport.pixelWidth}x${fig.seam_scope.domain?.viewport.pixelHeight}, numerator ${fig.seam_scope.domain?.numerator}; auto-frame raw mean ${fig.seam_scope.auto_frame_raw.mean}, ${fig.seam_scope.auto_frame_raw.px_over_40} px over ${SEAM_PX_LEVEL} at scale ${fig.seam_scope.auto_frame_raw.frame_scale} (diagnostic only)`);
1803
1829
  const pairs = fig.seam_pairs ?? [];
1804
1830
  pairs.forEach((row, i) => log(` seam pair ${i + 1} of ${pairs.length}: ${seamPairText(row)}`));
1805
1831
  if (fig.sets !== undefined) {
@@ -1808,6 +1834,11 @@ export function checkStage(input: CheckStageInput, rigc: RigcRunner, bin: string
1808
1834
  ` seam (${setName})${setFig.seam_border === undefined ? '' : ` (config.scene: ${setFig.seam_border.frame_px_left_out} frame px on the painting's border rows and columns left out, ${setFig.seam_border.px_over_40_left_out} of them over ${SEAM_PX_LEVEL})`}: setup pose at ${setFig.render_px}, scale ${setFig.seam_frame_scale.toFixed(4)}: mean |d| ${setFig.seam_mean} (<= ${SEAM_MEAN_BAR.toFixed(1)}), ` +
1809
1835
  `${setFig.seam_px_over_40} px over ${SEAM_PX_LEVEL}, ${seamRigPxText(setFig.seam_px_over_40, setFig.seam_frame_scale)} rig px (the count / s²; <= ${SEAM_PX_BAR}), ${setFig.seam_px_over_80} px over ${SEAM_PX_LEVEL_HIGH} (reported)`,
1810
1836
  );
1837
+ if (setFig.seam_scope !== undefined) {
1838
+ const scope = setFig.seam_scope;
1839
+ log(` seam scope (${setName}): ${scope.mode}, denominator ${scope.denominator_px} base source cells; union ${scope.domain?.viewport.pixelWidth}x${scope.domain?.viewport.pixelHeight}, numerator ${scope.domain?.numerator}; whole canonical ${scope.whole.px_over_40} px over ${SEAM_PX_LEVEL}, mean ${scope.whole.mean}; auto-frame raw ${scope.auto_frame_raw.px_over_40} at scale ${scope.auto_frame_raw.frame_scale} (diagnostic only); effects ${JSON.stringify(scope.effects)}, changes ${JSON.stringify(scope.changes)}${scope.unavailable === undefined ? '' : `; ${JSON.stringify(scope.unavailable)}`}`);
1840
+ for (const pair of scope.pairs ?? []) log(` seam inheritance (${setName}): ${JSON.stringify(pair.parts)}, whole ${pair.whole_px_over_40}, affected ${pair.affected_px_over_40}, inherited from base ${pair.inherited_px_over_40} px over ${SEAM_PX_LEVEL}`);
1841
+ }
1811
1842
  const setPairs = setFig.seam_pairs ?? [];
1812
1843
  setPairs.forEach((row, i) => log(` seam pair (${setName}) ${i + 1} of ${setPairs.length}: ${seamPairText(row)}`));
1813
1844
  }