@rig-c/parts 1.75.0 → 1.77.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/assemble.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { AUTOMATIC_WRITERS as AW, compactValueBaseline, pixelProvenance, rgbaEqual, type ValueBaseline } from './provenance.ts';
1
2
  import { bindDepthRun, copyDepthMaterial, registerDepthRun, transportPartDepth, type DepthConfig, type RegisteredDepth } from './depthsheets.ts';
2
3
  /**
3
4
  * The assemble stage: two See-through runs over one painting — a FULL-body run
@@ -2257,7 +2258,7 @@ export function pixelOwners(rigLayers: readonly Raster[], rank: readonly number[
2257
2258
  * masks mark own-layer art under a subset set's actual cover (alpha above 8);
2258
2259
  * those pixels are occluded, outside every projection core, and never recoloured.
2259
2260
  */
2260
- export function projectSource(rigLayers: Raster[], srcr: Raster, frame: Frame, run: Run, rule: ProjectRule = DEFAULT_PROJECT_RULE, rank: readonly number[] | null = null, keep: ReadonlyArray<Mask | null> | null = null): ProjectionStats[] {
2261
+ export function projectSource(rigLayers: Raster[], srcr: Raster, frame: Frame, run: Run, rule: ProjectRule = DEFAULT_PROJECT_RULE, rank: readonly number[] | null = null, keep: ReadonlyArray<Mask | null> | null = null, changed?: (layer: number, rigPixel: number) => void): ProjectionStats[] {
2261
2262
  const { W, H } = frame;
2262
2263
  const owner = pixelOwners(rigLayers, rank);
2263
2264
  const inFront = (o: number, i: number): boolean => frontOf(o, i, rank);
@@ -2320,10 +2321,14 @@ export function projectSource(rigLayers: Raster[], srcr: Raster, frame: Frame, r
2320
2321
  if (core.data[p] === 0) continue;
2321
2322
  const w = blurred.data[p];
2322
2323
  const rest = f32(1 - w);
2324
+ let different = false;
2323
2325
  for (let c = 0; c < 3; c++) {
2324
2326
  const v = f32(f32(w * srcr.data[p * 4 + c]) + f32(rest * r.data[p * 4 + c]));
2325
- r.data[p * 4 + c] = Math.trunc(v < 0 ? 0 : v > 255 ? 255 : v);
2327
+ const next = Math.trunc(v < 0 ? 0 : v > 255 ? 255 : v);
2328
+ different ||= next !== r.data[p * 4 + c];
2329
+ r.data[p * 4 + c] = next;
2326
2330
  }
2331
+ if (different) changed?.(i, p);
2327
2332
  }
2328
2333
  return { core: coreN, taken, refused, clear, takenMask, coreMask: core, refusedMask };
2329
2334
  });
@@ -2437,7 +2442,7 @@ export function growRim(part: Raster, sel: Mask, srcr: Raster, front: Mask | nul
2437
2442
  * overwriting an earlier one — the layer whose run says whether the pixel is
2438
2443
  * visible — and `trace.ring` set when the last write was the ring's.
2439
2444
  */
2440
- export function mergeBelowCrop(part: Raster, extras: Raster[], front: Mask, srcr: Raster, headBottom: number, trace?: MergeTrace): number {
2445
+ export function mergeBelowCrop(part: Raster, extras: Raster[], front: Mask, srcr: Raster, headBottom: number, trace?: MergeTrace, changed?: (rigPixel: number, stage: 'extend' | 'growRim') => void): number {
2441
2446
  let merged = 0;
2442
2447
  extras.forEach((extra, e) => {
2443
2448
  const sel = belowCrop(part, extra, headBottom);
@@ -2445,6 +2450,7 @@ export function mergeBelowCrop(part: Raster, extras: Raster[], front: Mask, srcr
2445
2450
  for (let p = 0; p < sel.data.length; p++) {
2446
2451
  if (sel.data[p] === 0) continue;
2447
2452
  copied++;
2453
+ if (!rgbaEqual(part.data, p * 4, extra.data, p * 4)) changed?.(p, 'extend');
2448
2454
  part.data.set(extra.data.subarray(p * 4, p * 4 + 4), p * 4);
2449
2455
  if (trace !== undefined) {
2450
2456
  trace.from[p] = e;
@@ -2458,6 +2464,7 @@ export function mergeBelowCrop(part: Raster, extras: Raster[], front: Mask, srcr
2458
2464
  trace.lastRing = ring;
2459
2465
  for (let p = 0; p < ring.data.length; p++) {
2460
2466
  if (ring.data[p] === 1) {
2467
+ changed?.(p, 'growRim');
2461
2468
  trace.from[p] = e;
2462
2469
  trace.ring.data[p] = 1;
2463
2470
  }
@@ -2805,6 +2812,7 @@ export function pushBackFringe(
2805
2812
  feathered: ReadonlyArray<Mask | null> | null = null,
2806
2813
  keep: ReadonlyArray<Mask | null> | null = null,
2807
2814
  turnMovingPair: ((a: string, b: string) => boolean) | null = null,
2815
+ restored?: (part: number, rigPixel: number) => void,
2808
2816
  ): FringePushed[][] {
2809
2817
  const { width: W } = srcr;
2810
2818
  const { holder, cand } = seamCandidates(parts, srcr, rule, silhouette);
@@ -2840,7 +2848,10 @@ export function pushBackFringe(
2840
2848
  }));
2841
2849
  const counts: Array<Map<number, number>> = parts.map(() => new Map());
2842
2850
  cleared.forEach((list, i) => {
2843
- for (const c of list) if (c.on) counts[i].set(c.h, (counts[i].get(c.h) ?? 0) + 1);
2851
+ for (const c of list) {
2852
+ if (c.on) counts[i].set(c.h, (counts[i].get(c.h) ?? 0) + 1);
2853
+ else restored?.(i, (parts[i].record.y + Math.floor(c.q / parts[i].record.w)) * W + parts[i].record.x + c.q % parts[i].record.w);
2854
+ }
2844
2855
  });
2845
2856
  return counts.map((m) =>
2846
2857
  [...m.entries()]
@@ -2878,6 +2889,7 @@ export function seamOverride(
2878
2889
  silhouette: Mask | null,
2879
2890
  keep: ReadonlyArray<Mask | null> | null = null,
2880
2891
  turnMovingPair: ((a: string, b: string) => boolean) | null = null,
2892
+ written?: (part: number, rigPixel: number) => void,
2881
2893
  ): void {
2882
2894
  const { width: W } = srcr;
2883
2895
  const { top, cand } = seamCandidates(parts, srcr, rule, silhouette);
@@ -2913,9 +2925,11 @@ export function seamOverride(
2913
2925
  ) {
2914
2926
  continue;
2915
2927
  }
2928
+ const different = image.data[s] !== srcr.data[d * 4] || image.data[s + 1] !== srcr.data[d * 4 + 1] || image.data[s + 2] !== srcr.data[d * 4 + 2];
2916
2929
  image.data[s] = srcr.data[d * 4];
2917
2930
  image.data[s + 1] = srcr.data[d * 4 + 1];
2918
2931
  image.data[s + 2] = srcr.data[d * 4 + 2];
2932
+ if (different) written?.(i, d);
2919
2933
  n++;
2920
2934
  }
2921
2935
  }
@@ -3415,6 +3429,8 @@ export interface CutCount {
3415
3429
  band: number;
3416
3430
  /** With `under` only (issue #193): the base pixels filled from the under image (`fillUnder`); absent without it. */
3417
3431
  under?: number;
3432
+ /** Filled pixels with final alpha above the opaque threshold (report-only). */
3433
+ underOpaque?: number;
3418
3434
  /** With `under` only: the removed pixels the image left empty (its alpha below the alpha removed); `under + underEmpty` is the removed count. */
3419
3435
  underEmpty?: number;
3420
3436
  /** With `under_fill: "colour"` only (issue #360): the `under` pixels took the image's colour at the alpha the cut removed; absent without it. */
@@ -3518,6 +3534,8 @@ export function cutBand(polygonMask: Mask, overlap: number): Mask {
3518
3534
 
3519
3535
  /** One layer's part as the stage builds it, before it is placed: its key, pixels, projection figures, merge trace and, when the layer is cut, the rig pixels it owns. */
3520
3536
  interface Built {
3537
+ /** Report-only last writer at each rig coordinate; never read by raster arithmetic. */
3538
+ writers?: Int32Array;
3521
3539
  key: string;
3522
3540
  r: Raster;
3523
3541
  st: ProjectionStats;
@@ -4031,7 +4049,8 @@ function cutLimbs(
4031
4049
  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)` });
4032
4050
  }
4033
4051
  for (const { q, i } of shares) {
4034
- pieces[i] = { ...b, r: rasters[i], region: regions[i], merged: mergedIn(b, regions[i]) };
4052
+ const writers = b.writers?.slice();
4053
+ pieces[i] = { ...b, writers, r: rasters[i], region: regions[i], merged: mergedIn(b, regions[i]) };
4035
4054
  if (count(regions[i], regions[i]) === 0 && opaqueOf(rasters[i]) === 0) {
4036
4055
  problems.push({
4037
4056
  code: 'ASSEMBLE_LIMB_PIXELS',
@@ -4125,6 +4144,10 @@ function cutLimbs(
4125
4144
  return;
4126
4145
  }
4127
4146
  const lower = rasters[at];
4147
+ const capWrite = (p: number, data: Uint8ClampedArray, offset: number): void => {
4148
+ const ids = (pieces[at] as Built).writers;
4149
+ if (ids !== undefined && !rgbaEqual(lower.data, p * 4, data, offset)) ids[p] = AW.limbCap;
4150
+ };
4128
4151
  const lowerSrc = builtOf(sg.from) as Built;
4129
4152
  // Issue #360 (cut_band): the cap's pixels are the disc's on the upper side of the cut, wherever it was placed.
4130
4153
  const cut = (cutLines.get(l) as Array<JointLine | null>)[k] as JointLine;
@@ -4147,6 +4170,7 @@ function cutLimbs(
4147
4170
  const from: CapFrom = { box, codes: new Uint8Array(Math.max(0, box[2]) * Math.max(0, box[3])) };
4148
4171
  const mark = (x: number, y: number, code: number): void => {
4149
4172
  from.codes[(y - box[1]) * box[2] + (x - box[0])] = code;
4173
+
4150
4174
  };
4151
4175
  for (let y = Math.max(0, box[1]); y < Math.min(H, box[1] + box[3]); y++) {
4152
4176
  for (let x = Math.max(0, box[0]); x < Math.min(W, box[0] + box[2]); x++) {
@@ -4161,6 +4185,7 @@ function cutLimbs(
4161
4185
  lowerKept++;
4162
4186
  mark(x, y, CAP_FROM_LOWER_KEPT);
4163
4187
  } else if (img !== null && img.data[u + 3] > 0) {
4188
+ capWrite(p, img.data, u);
4164
4189
  lower.data.set(img.data.subarray(u, u + 4), p * 4);
4165
4190
  lowerPx++;
4166
4191
  mark(x, y, CAP_FROM_LOWER);
@@ -4173,10 +4198,12 @@ function cutLimbs(
4173
4198
  continue;
4174
4199
  }
4175
4200
  if (img !== null && img.data[u + 3] > 0) {
4176
- lower.data.set(img.data.subarray(u, u + 4), p * 4);
4201
+ capWrite(p, img.data, u);
4202
+ lower.data.set(img.data.subarray(u, u + 4), p * 4);
4177
4203
  imagePx++;
4178
4204
  mark(x, y, CAP_FROM_IMAGE);
4179
4205
  } else if (ownLower[p] === li && lowerSrc.r.data[p * 4 + 3] > 0) {
4206
+ capWrite(p, lowerSrc.r.data, p * 4);
4180
4207
  lower.data.set(lowerSrc.r.data.subarray(p * 4, p * 4 + 4), p * 4);
4181
4208
  layerPx++;
4182
4209
  mark(x, y, CAP_FROM_LAYER);
@@ -4184,6 +4211,7 @@ function cutLimbs(
4184
4211
  // Issue #360: the disc is filled from the art — the upper segment's, where the lower's layer has none.
4185
4212
  // Issue #557: under either shape — the half-disc too takes the neighbouring segment's pixels, so a cap is
4186
4213
  // short only where no layer of the limb gives a pixel.
4214
+ capWrite(p, upper.data, p * 4);
4187
4215
  lower.data.set(upper.data.subarray(p * 4, p * 4 + 4), p * 4);
4188
4216
  upperPx++;
4189
4217
  mark(x, y, CAP_FROM_UPPER);
@@ -4230,6 +4258,7 @@ function cutLimbs(
4230
4258
  // piece's region and its remaining ramp is marked feathered so pushBackFringe does not clear the fade.
4231
4259
  if (na <= OPAQUE_ALPHA_ABOVE) upperRegion.data[p] = 0;
4232
4260
  else featheredMask.data[p] = 1;
4261
+ if (upPiece.writers !== undefined) upPiece.writers[p] = AW.limbFeather;
4233
4262
  featheredPx++;
4234
4263
  }
4235
4264
  }
@@ -4334,7 +4363,8 @@ function cutLimbs(
4334
4363
  base.hybrid = { part: sg.hybrid.part, ...geometry };
4335
4364
  capFrom[loAt] = null;
4336
4365
  parts.push({ limb: l, segment: k, part: sg.hybrid.part, of: sg.from, record: { name: l, segment: k, of: base.of, bone: sg.bone, joint: sg.joint, band: geometry } });
4337
- pieces.push({ ...source, r, region, merged: mergedIn(source, region) });
4366
+ const writers = source.writers?.slice();
4367
+ pieces.push({ ...source, writers, r, region, merged: mergedIn(source, region) });
4338
4368
  capFrom.push(null);
4339
4369
  // Existing piece objects refer to the same raster and mask.
4340
4370
  for (const i of [upAt, loAt]) (pieces[i] as Built).merged = mergedIn(pieces[i] as Built, regions[i]);
@@ -4621,6 +4651,19 @@ export function assemble(input: AssembleInput): AssembleResult {
4621
4651
  const coverFootprints = new Map<string, Mask>();
4622
4652
  const limbSources = new Set(Object.values(input.limbs ?? {}).flatMap((l) => l.segments.map((sg) => sg.from)));
4623
4653
  const limbPlans = new Set([...limbSources, ...cuts.filter((c) => limbSources.has(c.into)).map((c) => c.from)]);
4654
+ const editNames: string[] = [];
4655
+ const editId = (name: string): number => {
4656
+ const old = editNames.indexOf(name);
4657
+ if (old >= 0) return old + 1;
4658
+ editNames.push(name);
4659
+ return editNames.length;
4660
+ };
4661
+ const cutIds = cuts.map((_, i) => editId(`cuts[${i}]`));
4662
+ const patchIds = patches.map((_, i) => editId(`patches[${i}]`));
4663
+ const layerWriters = new Map<string, Int32Array>();
4664
+ const valueBaselines = new Map<string, ValueBaseline | null>();
4665
+ // Extend-only rasters are still projected/merged, but are never emitted as own sources.
4666
+ const readKeys = new Set(sourcePlan.map(([, run, tag]) => `${run}:${tag}`));
4624
4667
  const rig = new Map<string, Raster>();
4625
4668
  const stats = new Map<string, ProjectionStats>();
4626
4669
  const ghost: Record<string, number> = {};
@@ -4645,7 +4688,59 @@ export function assemble(input: AssembleInput): AssembleResult {
4645
4688
  coverFootprints.set(`${run}:${l.tag}`, cover);
4646
4689
  return mask;
4647
4690
  });
4648
- const st = projectSource(rigLayers, srcr, frame, run, projectRule, rank, keep);
4691
+ // Normalize the unedited input to the same rig grid. Cleanup effects on
4692
+ // retained samples are named; split/underfill outputs are prepared writes.
4693
+ const writes = layers.map((l, i): Int32Array | null => {
4694
+ const key = `${run}:${l.tag}`;
4695
+ if (!readKeys.has(key)) return null;
4696
+ const ids = new Int32Array(W * H);
4697
+ const originalSet = run === 'full' ? fullPadded : depthHeadInput;
4698
+ const original = originalSet.layers.find(q => q.name === l.tag);
4699
+ const prepared = set.layers.find(q => q.name === l.tag);
4700
+ let preparedWriter = 0;
4701
+ if (run === 'head' && prepared?.pixels !== original?.pixels) preparedWriter = AW.headFaceUnderfill;
4702
+ if (run === 'full') {
4703
+ const arm = fullArmSplit.layers.find(q => q.name === l.tag);
4704
+ if (prepared?.pixels !== arm?.pixels || arm?.pixels !== original?.pixels) preparedWriter = AW.armSplit;
4705
+ }
4706
+ const author = l.tag.startsWith('author:') ? editId(key) : 0;
4707
+ // Split-generated tags retain their actual original run contributors,
4708
+ // never the prepared/split raster as their baseline. arm_split copies
4709
+ // hand layers in input order; the merged-arm split inherits that source.
4710
+ const splitTag = /^(handwear|drape|hand)-[rl]$/.test(l.tag);
4711
+ const parentTag = l.tag.replace(/^(drape|hand)-/, 'handwear-');
4712
+ const sourceLayers = run === 'full' && splitTag && preparedWriter === AW.armSplit
4713
+ ? input.armSplit === undefined ? fullPadded.layers.filter(q => q.name === parentTag) : fullPadded.layers.filter(q => q.name === 'handwear-r' || q.name === 'handwear-l')
4714
+ : original === undefined ? [] : [original];
4715
+ let raw: Raster | null = null;
4716
+ if (author === 0 && sourceLayers.length > 0) {
4717
+ // A sole layer needs no composite copy: layerToRig premultiplies,
4718
+ // so discarded RGB at alpha 0 has exactly the same float32 input.
4719
+ const canvas = sourceLayers.length === 1 ? placeLayer(sourceLayers[0], input.resolution) : newRaster(input.resolution, input.resolution);
4720
+ if (sourceLayers.length > 1) for (const originalLayer of sourceLayers) {
4721
+ const sourceCanvas = placeLayer(originalLayer, input.resolution);
4722
+ for (let p = 0; p < input.resolution * input.resolution; p++) if (sourceCanvas.data[p * 4 + 3] > 0) canvas.data.set(sourceCanvas.data.subarray(p * 4, p * 4 + 4), p * 4);
4723
+ }
4724
+ raw = layerToRig(canvas, frame, run);
4725
+ }
4726
+ // Reuse only a proved identical placed input, never wrapper identity.
4727
+ const samePlacedSource = raw !== null && sourceLayers.length === 1 && prepared !== undefined &&
4728
+ sourceLayers[0].pixels === prepared.pixels && sourceLayers[0].left === prepared.left && sourceLayers[0].top === prepared.top;
4729
+ const preparedRig = samePlacedSource ? raw : prepared === undefined ? null : layerToRig(placeLayer(prepared, input.resolution), frame, run);
4730
+ for (let p = 0; p < W * H; p++) {
4731
+ if (rigLayers[i].data[p * 4 + 3] === 0) continue;
4732
+ ids[p] = author;
4733
+ if (preparedWriter !== 0 && (raw === null || preparedRig !== null && !rgbaEqual(raw.data, p * 4, preparedRig.data, p * 4))) ids[p] = preparedWriter;
4734
+ if (preparedRig !== null && !rgbaEqual(preparedRig.data, p * 4, rigLayers[i].data, p * 4)) ids[p] = AW.ghostCleanup;
4735
+ }
4736
+ // Keep only samples that could equal a final opaque pixel; full raw and
4737
+ // prepared normalization temporaries end with this layer's callback.
4738
+ valueBaselines.set(key, raw === null ? null : compactValueBaseline(raw));
4739
+ return ids;
4740
+ });
4741
+ const st = projectSource(rigLayers, srcr, frame, run, projectRule, rank, keep, (i, p) => { if (writes[i] !== null) (writes[i] as Int32Array)[p] = AW.sourceProjection; });
4742
+ writes.forEach((ids, i) => { if (ids !== null) layerWriters.set(`${run}:${layers[i].tag}`, ids); });
4743
+ writes.length = 0;
4649
4744
  layers.forEach((l, i) => {
4650
4745
  rig.set(`${run}:${l.tag}`, rigLayers[i]);
4651
4746
  stats.set(`${run}:${l.tag}`, st[i]);
@@ -4775,6 +4870,7 @@ export function assemble(input: AssembleInput): AssembleResult {
4775
4870
  const extendKeys = extend.filter((e) => e.part === name).map((e) => `${e.run}:${e.tag}`);
4776
4871
  const extras = extendKeys.map((k) => rig.get(k) as Raster);
4777
4872
  let merged = 0;
4873
+ const writers = (layerWriters.get(key) as Int32Array).slice();
4778
4874
  const trace: MergeTrace = { from: new Int32Array(W * H).fill(-1), ring: newMask(W, H) };
4779
4875
  if (extras.length > 0) {
4780
4876
  const front = newMask(W, H);
@@ -4782,7 +4878,7 @@ export function assemble(input: AssembleInput): AssembleResult {
4782
4878
  const f = rig.get(`${run2}:${tag2}`) as Raster;
4783
4879
  for (let p = 0; p < W * H; p++) if (f.data[p * 4 + 3] >= FRONT_ALPHA) front.data[p] = 1;
4784
4880
  }
4785
- merged = mergeBelowCrop(r, extras, front, srcr, frame.headBottom, trace);
4881
+ merged = mergeBelowCrop(r, extras, front, srcr, frame.headBottom, trace, (p, stage) => { writers[p] = AW[stage]; });
4786
4882
  }
4787
4883
  const { x1, opaque } = measureBox(r);
4788
4884
  if (opaque === 0) {
@@ -4793,7 +4889,7 @@ export function assemble(input: AssembleInput): AssembleResult {
4793
4889
  });
4794
4890
  return null;
4795
4891
  }
4796
- return { key, r, st, extendKeys, trace, merged, region: null };
4892
+ return { key, r, st, extendKeys, trace, merged, region: null, writers };
4797
4893
  };
4798
4894
  plan.forEach(([name, run, tag], pi) => { built[pi] = buildSource(name, run, tag, pi); });
4799
4895
  // Snapshot independent piece pixels before any parent's subtraction or under fill.
@@ -4802,6 +4898,9 @@ export function assemble(input: AssembleInput): AssembleResult {
4802
4898
  const row = plan[pi], tag = input.cutLayers?.get(c.into);
4803
4899
  return tag === undefined ? null : buildSource(c.from, row[1], tag, pi);
4804
4900
  });
4901
+ // Every Built owns its writer slice. No source-map lookup follows this
4902
+ // last cut-layer build; drop originals before cut/limb working sets grow.
4903
+ layerWriters.clear();
4805
4904
  const silhouette = seamRule === 'silhouette' || patches.some((q) => q.alpha === 'silhouette') ? figureSilhouette(srcr) : null;
4806
4905
  const cut = patches.map((q, i) => {
4807
4906
  const c = cutPatch(q, srcr, silhouette);
@@ -4863,7 +4962,9 @@ export function assemble(input: AssembleInput): AssembleResult {
4863
4962
  if (band.data[p] === 1) nb++;
4864
4963
  }
4865
4964
  }
4866
- pieces[i] = { ...b, r, region: m, merged: mergedIn(b, m) };
4965
+ const writers = (b.writers as Int32Array).slice();
4966
+ // A retained base band is not written: it keeps its earlier writer.
4967
+ pieces[i] = { ...b, r, writers, region: m, merged: mergedIn(b, m) };
4867
4968
  bands.push(nb);
4868
4969
  return n;
4869
4970
  });
@@ -4912,6 +5013,10 @@ export function assemble(input: AssembleInput): AssembleResult {
4912
5013
  // Filled where the image is at least as opaque as the layer was; left empty elsewhere (`fillUnder`).
4913
5014
  // With under_fill "colour" (issue #360) a filled pixel keeps the alpha the cut removed and takes the image's colour only.
4914
5015
  const f = fillUnder(b.r, (pieces[i] as Built).r, cutBand(cutMasks[i], cuts[i].overlap), u, underBox(cuts[i].polygon), cuts[i].under_fill);
5016
+ const band = cutBand(cutMasks[i], cuts[i].overlap);
5017
+ let opaqueFilled = 0;
5018
+ // The under operation wrote only removed pixels it actually filled.
5019
+ for (let p = 0; p < W * H; p++) if (cutMasks[i].data[p] === 1 && band.data[p] === 0 && (pieces[i] as Built).r.data[p * 4 + 3] > 0 && b.r.data[p * 4 + 3] > 0) { (b.writers as Int32Array)[p] = cutIds[i]; if (b.r.data[p * 4 + 3] > OPAQUE_ALPHA_ABOVE) opaqueFilled++; }
4915
5020
  // A hidden-art layer (issue #359) is the whole layer's covered art, read by every cut of its part: a cut it holds nothing
4916
5021
  // under fills 0, which the cut line counts, and is not refused as a file made for this one cut would be.
4917
5022
  if (f.filled === 0 && input.cuts[i].under !== undefined) {
@@ -4921,13 +5026,14 @@ export function assemble(input: AssembleInput): AssembleResult {
4921
5026
  detail: `${cuts[i].under} fills 0 of the ${f.empty} pixel(s) the cut removed from "${name}": at every one its alpha is below the alpha removed (an all-transparent image, or another file); an image that fills at least one is required — to leave the whole hole, drop under`,
4922
5027
  });
4923
5028
  }
4924
- return f;
5029
+ return { ...f, opaqueFilled };
4925
5030
  });
4926
5031
  mine.forEach((i, k) => {
4927
5032
  const c: CutCount = { from: name, into: cuts[i].into, before, kept, taken: taken[k], band: bands[k] };
4928
5033
  const f = filled[k];
4929
5034
  if (f !== undefined) {
4930
5035
  c.under = f.filled;
5036
+ c.underOpaque = f.opaqueFilled;
4931
5037
  c.underEmpty = f.empty;
4932
5038
  if (cuts[i].under_fill === 'colour') c.underFill = 'colour';
4933
5039
  }
@@ -4941,7 +5047,8 @@ export function assemble(input: AssembleInput): AssembleResult {
4941
5047
  const m = cutMasks[i], r = newRaster(W, H);
4942
5048
  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);
4943
5049
  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` });
4944
- pieces[i] = { ...source, r, region: m, merged: mergedIn(source, m) };
5050
+ const writers = (source.writers as Int32Array).slice();
5051
+ pieces[i] = { ...source, r, writers, region: m, merged: mergedIn(source, m) };
4945
5052
  });
4946
5053
  refuseIfAny(empty);
4947
5054
  // In cut order, as the config lists them.
@@ -5064,7 +5171,9 @@ export function assemble(input: AssembleInput): AssembleResult {
5064
5171
  });
5065
5172
  const featheredInOrder: Array<Mask | null> = order.map((d) => ('patch' in d ? null : (pieceAt(d).b.feathered ?? null)));
5066
5173
  const keepInOrder = order.map((d) => ('limb' in d ? limbKeep[d.limb] : null));
5067
- const pushedBy = pushBackFringe(stack, srcr, seamRule, seamRule === 'silhouette' ? silhouette : null, featheredInOrder, keepInOrder, input.turnMovingPair ?? null);
5174
+ const patchWriters = patches.map((_, i) => new Int32Array(W * H).fill(patchIds[i]));
5175
+ const writersInOrder = order.map(d => 'patch' in d ? patchWriters[d.patch] : pieceAt(d).b.writers as Int32Array);
5176
+ const pushedBy = pushBackFringe(stack, srcr, seamRule, seamRule === 'silhouette' ? silhouette : null, featheredInOrder, keepInOrder, input.turnMovingPair ?? null, (i, p) => { writersInOrder[i][p] = AW.fringeRestore; });
5068
5177
  // Issue #255: a part's drift refusals in a body, and who holds the body in the draw order (the push-back clears
5069
5178
  // only fringe below CORE_ALPHA; these are the holders before the opt-in yield, and the seam override only recolours).
5070
5179
  const holderAt = new Int32Array(W * H).fill(-1);
@@ -5242,7 +5351,14 @@ export function assemble(input: AssembleInput): AssembleResult {
5242
5351
  for (const p of placed) if (p.record.depth !== undefined && artFiles.has(p.record.depth.image)) refuseIfAny([{ code: 'DEPTH_SHEET_UNAMBIGUOUS', object: p.record.depth.image, detail: 'collides with a part artwork filename; choose noncolliding part names before sheet emission' }]);
5243
5352
 
5244
5353
 
5245
- seamOverride(placed, srcr, seamRule, seamRule === 'silhouette' ? silhouette : null, keepInOrder, input.turnMovingPair ?? null);
5354
+ seamOverride(placed, srcr, seamRule, seamRule === 'silhouette' ? silhouette : null, keepInOrder, input.turnMovingPair ?? null, (i, p) => { writersInOrder[i][p] = AW.seamOverride; });
5355
+ placed.forEach((p, i) => { p.record.provenance = pixelProvenance(p.image, p.record.x, p.record.y, W, writersInOrder[i], editNames, 0, valueBaselines.get(p.record.from) ?? null); });
5356
+ // Provenance is now numbers/labels only. No later raster/figure operation
5357
+ // reads report buffers; release all aliases before recomposite/error work.
5358
+ valueBaselines.clear();
5359
+ writersInOrder.length = 0;
5360
+ patchWriters.length = 0;
5361
+ for (const group of [built, pieces, cutSources, limbPieces]) for (const b of group) if (b !== null) b.writers = undefined;
5246
5362
  const can = recomposite(placed, W, H);
5247
5363
  // Issue #242: on a scene painting the figure is read off the full run, and every recomposite figure inside it.
5248
5364
  const inside = input.scene === true ? sceneFigure([...rig.entries()].filter(([k]) => k.startsWith('full:')).map(([, r]) => r), W, H) : null;
@@ -5272,6 +5388,9 @@ export function assemble(input: AssembleInput): AssembleResult {
5272
5388
  scale_rig_per_source: frame.S,
5273
5389
  ...(input.motion_seams === undefined ? {} : { motion_seams: input.motion_seams.map(({ part, neighbour }) => ({ part, neighbour })) }),
5274
5390
  parts: placed.map((p) => p.record),
5391
+ ...(cutCounts.length === 0 ? {} : { cut_ownership: cutCounts.map((c, i) => ({ edit: `cuts[${i}]`, from: c.from, into: c.into, moved_in_opaque_px: c.taken,
5392
+ retained_band_opaque_px: c.band, cleared_opaque_px: c.taken - c.band, under_filled_px: c.under ?? 0,
5393
+ under_filled_opaque_px: c.underOpaque ?? 0, net_cleared_opaque_px: c.taken - c.band - (c.underOpaque ?? 0) })) }),
5275
5394
  ghost_px: ghost,
5276
5395
  recomposite: recompositeRecord(figures),
5277
5396
  ...(sceneRecord === null ? {} : { scene: sceneRecord }),
@@ -5797,6 +5916,42 @@ function fmt0(v: number): string {
5797
5916
  * before; each gains one such note per tag left out (demo 6, scarf 9,
5798
5917
  * reference-demo 7, reference-sample 9).
5799
5918
  */
5919
+ /** Source alpha intersection, not an art classifier. One opaque texel can carry a second contour. */
5920
+ export interface HeadGarmentOverlap { part: string; layer: string; px: number; box: [number, number, number, number] }
5921
+
5922
+ /** #812: register full garments onto the declared crop; count only planned source pairs. */
5923
+ export function headGarmentOverlaps(full: LayerSet, head: LayerSet, g: Geometry, plan: readonly PlanEntry[]): HeadGarmentOverlap[] {
5924
+ if (g.single === true) return [];
5925
+ const frame = checkGeometry(g, { full, head });
5926
+ const garments = plan.filter(([, run, tag]) => run === 'full' && ['topwear', 'neckwear', 'collar'].includes(tag));
5927
+ const out: HeadGarmentOverlap[] = [];
5928
+ for (const [part, run, tag] of plan) {
5929
+ if (run !== 'head') continue;
5930
+ const layer = head.layers.find(l => l.name === tag);
5931
+ if (layer === undefined) continue;
5932
+ const a = placeLayer(layer, g.resolution);
5933
+ for (const [, , name] of garments) {
5934
+ const garment = full.layers.find(l => l.name === name);
5935
+ if (garment === undefined) continue;
5936
+ const b = fullLayerToHead(placeLayer(garment, g.resolution), frame, g.resolution);
5937
+ let px = 0, left = g.resolution, top = g.resolution, right = 0, bottom = 0;
5938
+ for (let y = 0; y < g.resolution; y++) for (let x = 0; x < g.resolution; x++) {
5939
+ const k = (y * g.resolution + x) * 4 + 3;
5940
+ if (a.data[k] < CORE_ALPHA || b.data[k] < CORE_ALPHA) continue;
5941
+ px++; left = Math.min(left, x); top = Math.min(top, y); right = Math.max(right, x + 1); bottom = Math.max(bottom, y + 1);
5942
+ }
5943
+ if (px > 0) out.push({ part, layer: name, px, box: [left, top, right, bottom] });
5944
+ }
5945
+ }
5946
+ return out;
5947
+ }
5948
+
5949
+ export const HEAD_GARMENT_WARNING = 'PLAN_HEAD_GARMENT_OVERLAP';
5950
+
5951
+ export function headGarmentWarning(w: HeadGarmentOverlap): string {
5952
+ return `WARN ${HEAD_GARMENT_WARNING}: part "${w.part}" (head run) overlaps full-run layer "${w.layer}" — ${w.px} opaque crop px (alpha >= ${CORE_ALPHA}), box [${w.box.join(', ')}] (right/bottom exclusive, head-canvas px); take this part from the full run, then inspect the source and rebuild (AUTHORING: A neck that moves on its own)`;
5953
+ }
5954
+
5800
5955
  export function proposePlan(full0: LayerSet, head0: LayerSet, g: Geometry, minPx = PROPOSE_MIN_PX): PlanProposal {
5801
5956
  const frame = checkGeometry(g, { full: full0, head: head0 });
5802
5957
  // Issue #366: one run's file, padded to the resolution square as the stage pads it.
@@ -5936,7 +6091,7 @@ export function proposePlan(full0: LayerSet, head0: LayerSet, g: Geometry, minPx
5936
6091
  const bodyNotes = left.map((u) => uncoveredNote(u, plan, minBody));
5937
6092
  const unplanned = unplannedNotes(runs, plan, extend, noted, figures, minPx, (run, tag) => (find(run, tag)?.opaqueRunPx ?? 0) * (run === 'head' ? headArea : fullArea), new Set(left.map((u) => u.tag)));
5938
6093
  // The reference's notes, then the uncovered bodies, then the layers in no row (issue #308), then the plausibility drops — a drop note is last, as it was.
5939
- return { plan, extend_below_crop: extend, notes: [...notes, ...bodyNotes, ...unplanned, ...dropNotes] };
6094
+ return { plan, extend_below_crop: extend, notes: [...notes, ...bodyNotes, ...unplanned, ...dropNotes, ...headGarmentOverlaps(full, head, g, plan).map(headGarmentWarning)] };
5940
6095
  }
5941
6096
 
5942
6097
  /**
package/src/build.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { ownershipLines, provenanceLines } from './provenance.ts';
1
2
  import { readSourceDepth } from './depthsheets.ts';
2
3
  import { orderedBaseAnchor } from './baseanchor.ts';
3
4
  import { alternateLayerSources, alternateLayerIslands, alternateLayerOthers } from './alternatelayers.ts';
@@ -705,6 +706,7 @@ export function assembleStage(input: AssembleStageInput, outs: AssembleOutputs,
705
706
  ...(altFront.size === 0 ? {} : { front: [...altFront] }),
706
707
  slots,
707
708
  records: keptRecords,
709
+ ...(altRes.parts.cut_ownership === undefined ? {} : { cut_ownership: altRes.parts.cut_ownership }),
708
710
  ghost_px: altRes.parts.ghost_px,
709
711
  recomposite: altRecomposite,
710
712
  ...(altRes.parts.scene === undefined ? {} : { scene: altRes.parts.scene }),
@@ -782,6 +784,9 @@ export function assembleStage(input: AssembleStageInput, outs: AssembleOutputs,
782
784
  `unproj=${String(p.visible_not_projected_px).padStart(5)} drift=${String(p.refused_drift_px).padStart(5)} ${driftShare(p.refused_drift_px, p.projected_core_px)} merged=${p.merged_px} seam=${p.seam_override_px}${underfillSuffix}`,
783
785
  );
784
786
  }
787
+ for (const line of provenanceLines(result.parts.parts)) log(line);
788
+ for (const line of ownershipLines(result.parts.cut_ownership ?? [])) log(line);
789
+ 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()}`);
785
790
  // Issue #256: one line per part from an author-made layer, so it never reads as See-through's. None without one.
786
791
  for (const l of authorPartLines(result.parts.parts)) log(l);
787
792
  // One line per plan part an assemble.cuts entry cut, before the fringe lines: the cut is made first. None without cuts.
package/src/config.ts CHANGED
@@ -1794,6 +1794,14 @@ export function controlSkeletonOf(cfg: object): ControlSkeleton | undefined {
1794
1794
  return resolveControlSkeleton(gen, null);
1795
1795
  }
1796
1796
 
1797
+ /** Clone a config and its already resolved control pose, without reading a relative file again. */
1798
+ export function cloneConfig<T extends object>(cfg: T): T {
1799
+ const clone = structuredClone(cfg);
1800
+ const skeleton = controlSkeletonOf(cfg);
1801
+ if (skeleton !== undefined) controlSkeletons.set(clone, structuredClone(skeleton));
1802
+ return clone;
1803
+ }
1804
+
1797
1805
  /** The pose file a checked `generation` block's control names, read relative to `base`; null for a built-in, an absent control, or a block already refused. */
1798
1806
  function poseBeside(c: Check, gen: Json, base: string): ControlPose | null {
1799
1807
  if (!isPlainObject(gen) || !isPlainObject(gen.control)) return null;
@@ -10,6 +10,7 @@
10
10
  */
11
11
  import type { PlanProposal } from './assemble.ts';
12
12
  import type { HeadBoxProposal } from './headbox.ts';
13
+ import type { CharacterConfig } from './config.ts';
13
14
  import type { Proposal, PROPOSAL_CONFIG_SECTIONS } from './propose.ts';
14
15
  import { PartsError } from './errors.ts';
15
16
  import { parseProposalSections } from './config.ts';
@@ -18,6 +19,7 @@ import type { ConfigEdit } from './meshdraft.ts';
18
19
  export type ConfigJson = null | boolean | number | string | ConfigJson[] | ConfigObject;
19
20
  export interface ConfigObject { [key: string]: ConfigJson }
20
21
  export type ConfigWritePatch =
22
+ | { kind: 'neck-unit'; config: CharacterConfig }
21
23
  | { kind: 'head-box'; head_box: HeadBoxProposal['head_box'] }
22
24
  | { kind: 'assemble-plan'; plan: PlanProposal['plan']; extend_below_crop: PlanProposal['extend_below_crop'] }
23
25
  | { kind: 'proposal'; proposal: Proposal; sections: typeof PROPOSAL_CONFIG_SECTIONS }
@@ -91,6 +93,18 @@ export function mergeConfigProposal(raw: unknown, patch: ConfigWritePatch): Conf
91
93
  const config = clone(before, 'config') as ConfigObject;
92
94
  const edits: ConfigEdit[] = [];
93
95
  switch (patch.kind) {
96
+ case 'neck-unit': {
97
+ const values = { bones: patch.config.bones, meshes: patch.config.meshes, regions: patch.config.regions, turn: patch.config.turn };
98
+ for (const [key, value] of Object.entries(values)) {
99
+ config[key] = clone(value, `neck.${key}`);
100
+ if (!equal(before[key], config[key])) edits.push({ path: [key], value: config[key] });
101
+ }
102
+ if (!object(config.assemble)) return refuse('config.assemble', 'must be an object before drafting the neck source');
103
+ config.assemble.plan = clone(patch.config.assemble.plan, 'neck.plan');
104
+ if (!equal((before.assemble as ConfigObject).plan, config.assemble.plan)) edits.push({ path: ['assemble', 'plan'], value: config.assemble.plan });
105
+ break;
106
+ }
107
+
94
108
  case 'head-box': {
95
109
  if (!object(config.seethrough)) return refuse('config.seethrough', 'is absent or not an object; the existing See-through settings are required before writing head_box');
96
110
  const previous = config.seethrough.head_box;
@@ -0,0 +1,82 @@
1
+ /** #812: source-first drafting into an explicitly authored sampled body turn. */
2
+ import { assemble, checkGeometry, fullLayerToHead, headGarmentOverlaps, headGarmentWarning, placeLayer, stageFields, type AssembleResult, type AssembleInput } from './assemble.ts';
3
+ import { cloneConfig, type CharacterConfig } from './config.ts';
4
+ import { type LayerSet } from './layers.ts';
5
+ import { PartsError } from './errors.ts';
6
+ import { extendDepthSilhouette } from './depthsheets.ts';
7
+ import { type PartsFile } from './parts.ts';
8
+ import type { Raster } from './raster/types.ts';
9
+ import { sampleUnitPartDepth } from './turn.ts';
10
+ import { pyRound } from './round.ts';
11
+ import { partGrid } from './propose.ts';
12
+
13
+ function refuse(code: string, object: string, detail: string): never { throw new PartsError([{ code, object, detail }]); }
14
+ export interface NeckDraft { config: CharacterConfig; assembled: AssembleResult; notes: string[] }
15
+
16
+ /** No inference of a body turn, depth units, source art or anatomical endpoints. */
17
+ export function draftIndependentNeck(input: { config: CharacterConfig; source: Raster; full: LayerSet; head: LayerSet; base: string; under?: AssembleInput['under']; caps?: AssembleInput['caps']; previous?: { parts: PartsFile; images: ReadonlyMap<string, Raster> } }): NeckDraft {
18
+ const cfg = cloneConfig(input.config), body = cfg.turn?.body;
19
+ if (body === undefined) return refuse('PROPOSE_NECK_BODY_TURN', 'config.turn.body', 'is absent; declare the sampled body turn before drafting an independent neck');
20
+ // Body overrides the entire fallback map; snapshot before removing the legacy neck entry.
21
+ const unitDepths = { ...(body.unitDepths ?? cfg.turn?.unitDepths) };
22
+ const rows = cfg.assemble.plan.filter(([, , tag]) => tag === 'neck');
23
+ if (rows.length !== 1) return refuse('PROPOSE_NECK_PLAN', 'config.assemble.plan', `has ${rows.length} neck rows; one unambiguous neck source is required`);
24
+ const [part] = rows[0];
25
+ const fullNeck = input.full.layers.find(l => l.name === 'neck');
26
+ if (fullNeck === undefined) return refuse('PROPOSE_NECK_FULL_SOURCE', `part "${part}"`, 'full-run neck layer is missing; supply --full with a clean neck layer, then rerun propose');
27
+ const fields = stageFields(cfg), g = { ...fields, sourceW: input.source.width, sourceH: input.source.height };
28
+ const frame = checkGeometry(g, input);
29
+ const notes = headGarmentOverlaps(input.full, input.head, g, cfg.assemble.plan).map(headGarmentWarning);
30
+ const projected = fullLayerToHead(placeLayer(fullNeck, fields.resolution), frame, fields.resolution);
31
+ notes.push('neck source: full-run provenance avoids the head-crop warning; opaque overlap alone does not identify collar line art or distinguish normal seam underlap. Inspect the full source and rendered setup/extremes before accepting the draft');
32
+ const pivot = body.pivot ?? cfg.turn?.pivot;
33
+ if (pivot === undefined) return refuse('PROPOSE_NECK_DEPTH_INPUT', 'config.turn.body.pivot', 'and config.turn.pivot are absent; declare the body pivot in the existing depth world units');
34
+ const neck = cfg.bones.find(b => 'name' in b && b.name === 'neck');
35
+ const head = cfg.bones.find(b => 'name' in b && b.name === 'head');
36
+ const carrier = body.bone ?? (cfg.bones.some(b => 'name' in b && b.name === 'chest') ? 'chest' : 'hip');
37
+ if (neck === undefined || !('at' in neck) || head === undefined || !('at' in head) || !cfg.bones.some(b => 'name' in b && b.name === carrier)) return refuse('PROPOSE_NECK_CARRIER', `part "${part}"`, `neck/head landmarks or body carrier "${carrier}" are missing; declare their named bones and coordinates`);
38
+ // This path changes a source, not structural cuts/alternate sets that require their own readers.
39
+ if (cfg.assemble.cuts?.some(c => c.from === part || c.into === part) || cfg.assemble.alternates?.length || Object.values(cfg.limbs ?? {}).some(l => l.segments.some(s => s.from === part)) || cfg.assemble.extend_below_crop?.some(e => e.part === part)) return refuse('PROPOSE_NECK_REASSEMBLY', `part "${part}"`, 'this neck has a cut, limb split or extension, or the config has alternate sets; first assemble the clean full-run neck with the existing assemble command and draft its base config without those neck operations or alternate sets');
40
+ cfg.assemble.plan = cfg.assemble.plan.map(row => row[0] === part ? [part, 'full', 'neck'] : row);
41
+ const unit = `${part}_part`;
42
+ const found = cfg.bones.find(b => 'name' in b && b.name === unit);
43
+ if (found !== undefined && (!('at' in found) || found.parent !== carrier || JSON.stringify(found.at) !== JSON.stringify(neck.at))) return refuse('PROPOSE_NECK_BONE_UNIQUE', unit, 'already names a different bone; rename that bone before drafting the neck unit');
44
+ if (found === undefined) cfg.bones.splice(cfg.bones.indexOf(neck) + 1, 0, { name: unit, parent: carrier, at: [...neck.at] });
45
+ const current = cfg.meshes[part];
46
+ const [grid, r] = partGrid(input.previous?.parts.parts.find(p => p.name === part) ?? { w: projected.width, h: projected.height });
47
+ cfg.meshes[part] = { grid: current !== undefined && 'grid' in current ? current.grid : grid, r: current !== undefined && 'r' in current ? current.r : r, segments: [[unit, [...neck.at], [...head.at]]] };
48
+ delete cfg.regions[part];
49
+ if (cfg.turn!.roles !== undefined) delete cfg.turn!.roles[part];
50
+ if (cfg.turn!.unitDepths !== undefined) delete cfg.turn!.unitDepths[part];
51
+ body.roles[part] = 'unit';
52
+ // Stage fields now see the new role before any color/fringe ownership operation.
53
+ const assembled = assemble({ source: input.source, full: input.full, head: input.head, ...stageFields(cfg), under: input.under, caps: input.caps, seamRule: 'near-white', projectRule: 'core', depth: cfg.depth, depthBase: input.base });
54
+ const rec = assembled.parts.parts.find(p => p.name === part)!;
55
+ const image = assembled.images.find(p => p.record.name === part)!.image;
56
+ const own = assembled.images.find(p => p.record.name === part)!;
57
+ let ref = rec.depth, scalar = own.depthImage, art = image, population = 'new full-run opaque neck texels';
58
+ if (ref === undefined || scalar === undefined) {
59
+ const old = input.previous?.parts.parts.find(p => p.name === part);
60
+ const oldSheet = old?.depth === undefined ? undefined : input.previous?.images.get(old.depth.image);
61
+ if (old?.depth === undefined || oldSheet === undefined) return refuse('PROPOSE_NECK_DEPTH_INPUT', `part "${part}"`, 'full-run scalar depth sheet and previous parts.json neck depth sheet are missing; supply config.depth with near/zScale and the source sheet, or reassemble parts with its existing scalar depth input');
62
+ ref = old.depth; scalar = oldSheet; art = { ...oldSheet, data: new Uint8ClampedArray(oldSheet.width * oldSheet.height * 4) };
63
+ let n = 0;
64
+ for (let y = 0; y < image.height; y++) for (let x = 0; x < image.width; x++) {
65
+ const ox = rec.x + x - old.x, oy = rec.y + y - old.y;
66
+ if (image.data[(y * image.width + x) * 4 + 3] < 128 || ox < 0 || oy < 0 || ox >= old.w || oy >= old.h) continue;
67
+ art.data[(oy * old.w + ox) * 4 + 3] = 255; n++;
68
+ }
69
+ if (n === 0) return refuse('PROPOSE_NECK_DEPTH_INPUT', `part "${part}"`, 'new art has no opaque overlap with the previous scalar sheet; supply a registered full-run neck scalar sheet');
70
+ population = `${n} new-art opaque texels overlapping previous registered neck sheet`;
71
+ }
72
+ const surface = Object.entries(body.roles).find(([, role]) => role === 'surface')?.[0];
73
+ const surf = assembled.images.find(p => p.record.name === surface);
74
+ if (surf?.record.depth === undefined || surf.depthImage === undefined) return refuse('PROPOSE_NECK_DEPTH_INPUT', `turn.body surface "${surface ?? '(none)'}"`, 'the first declared body surface or its scalar depth sheet is missing; declare a body surface and assemble its config.depth input');
75
+ const zNeck = sampleUnitPartDepth(scalar, art, ref);
76
+ const zRef = sampleUnitPartDepth(extendDepthSilhouette(surf.depthImage, surf.image), surf.image, surf.record.depth);
77
+ const value = pyRound(pivot + zNeck - zRef, 4);
78
+ body.unitDepths = { ...unitDepths, [part]: value };
79
+ notes.push(`neck: "${part}" takes full:neck; sibling bone "${unit}" under "${carrier}", one rigid segment from neck to head; reassembled with the CLI defaults seam=near-white/project=core (source rules are not recorded in parts.json); turn.body.roles.${part} = unit (no head role)`);
80
+ notes.push(`neck depth: turn.body.unitDepths.${part} = ${value} = round4(body pivot ${pivot} + neck world median ${zNeck} - first body surface "${surface}" world median ${zRef}); median over ${population}, sheet "${ref.image}", near=${ref.near}, zScale=${ref.zScale}; levelToDepthZ applies the declared polarity, not depth_median`);
81
+ return { config: cfg, assembled, notes };
82
+ }