@rig-c/parts 2.44.0 → 2.46.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/rig.ts CHANGED
@@ -137,7 +137,7 @@ import { explicitAttachment, type ExplicitMeshReport } from './explicitmesh.ts';
137
137
  * touches the disk, and the same inputs give the same bytes (key order is the
138
138
  * order the objects are built in, and every number is rounded by `pyRound`).
139
139
  */
140
- import { type AutoSpec, type BoneEntry, type InfluenceMeshSpec, type WeightRule, type CharacterConfig, type ConfigConstraint, type ConfigStop, CONSTRAINT_FOLLOWS, constraintForRig, contourRegionsOf, type ContourSpec, DEFAULT_BUST_BONE_L, DEFAULT_BUST_BONE_R, type Point, type RibsSpec, ROOT_BONE, stopForRig, turnRidersByBone, weightsABone } from './config.ts';
140
+ import { type AutoSpec, type BoneEntry, type InfluenceMeshSpec, type WeightRule, type CharacterConfig, type MeshSpec, type ConfigConstraint, type ConfigStop, CONSTRAINT_FOLLOWS, constraintForRig, contourRegionsOf, type ContourSpec, DEFAULT_BUST_BONE_L, DEFAULT_BUST_BONE_R, type Point, type RibsSpec, ROOT_BONE, stopForRig, turnRidersByBone, weightsABone } from './config.ts';
141
141
  import { RUNTIME_PI } from '@rig-c/core/core';
142
142
  import { type BoneTransform, computeExactFrameTransforms, computeWorldTransforms, cropToSpineY, normaliseDegrees, paintingToSetupPoint, setupToPaintingPoint, toBoneLocal, toWorld } from './coords.ts';
143
143
  import { foldName, type Problem, refuseIfAny, PartsError } from './errors.ts';
@@ -895,6 +895,71 @@ export function influenceReach(points: ReadonlyArray<readonly [number, number]>,
895
895
  return best;
896
896
  }
897
897
 
898
+ /** Hold the complete triangle wherever its interior crosses the cloth root row. */
899
+ function fixedTriangleRow(
900
+ row: number,
901
+ oy: number,
902
+ vertices: ReadonlyArray<readonly [number, number]>,
903
+ triangles: readonly number[],
904
+ ): number {
905
+ let held = row;
906
+ for (let i = 0; i < triangles.length; i += 3) {
907
+ const a = vertices[triangles[i]][1] + oy;
908
+ const b = vertices[triangles[i + 1]][1] + oy;
909
+ const c = vertices[triangles[i + 2]][1] + oy;
910
+ if (Math.min(a, b, c) < row) held = Math.max(held, a, b, c);
911
+ }
912
+ return held;
913
+ }
914
+
915
+ function rasterAlpha(img: Raster): Uint8Array {
916
+ const alpha = new Uint8Array(img.width * img.height);
917
+ for (let i = 0; i < alpha.length; i++) alpha[i] = img.data[i * 4 + 3];
918
+ return alpha;
919
+ }
920
+
921
+ function influenceLattice(img: Raster, alpha: Uint8Array, cell: number): SegmentsLattice {
922
+ return buildSegmentsLattice({ mask: { width: img.width, height: img.height, alpha }, threshold: INFLUENCE_THRESHOLD, cell });
923
+ }
924
+
925
+ function rigContour(p: PartsFile['parts'][number], img: Raster, spec: ContourSpec, ribs: ContourChainRibs[]) {
926
+ const ox = p.x - PAD;
927
+ const oy = p.y - PAD;
928
+ const regions: ContourRegion[] = contourRegionsOf(spec).map((rg) =>
929
+ rg.shape === 'circle'
930
+ ? { name: rg.name, shape: 'circle', cx: rg.cx - ox, cy: rg.cy - oy, r: rg.r, spacing: rg.spacing, band: rg.band }
931
+ : { name: rg.name, shape: 'polygon', points: rg.points.map(([x, y]) => [x - ox, y - oy]), spacing: rg.spacing, band: rg.band },
932
+ );
933
+ return contourMesh(p.name, { width: img.width, height: img.height, alpha: rasterAlpha(img) }, {
934
+ threshold: ART_ALPHA, tolerance: spec.tolerance, margin: spec.margin, spacing: spec.spacing,
935
+ ...(spec.maxEdge === undefined ? {} : { maxEdge: spec.maxEdge }), budget: spec.budget, stray: spec.stray,
936
+ ...(spec.bridges === undefined ? {} : { bridges: spec.bridges }), regions, ...(ribs.length === 0 ? {} : { ribs }),
937
+ });
938
+ }
939
+
940
+ /** The transition the same topology will need when rig binds the proposed mesh. */
941
+ export function draftClothHoldRow(p: PartsFile['parts'][number], image: Raster, mesh: MeshSpec, row: number): number | null {
942
+ const img = pad(image, PAD, PAD, PAD, PAD, [0, 0, 0, 0]);
943
+ const oy = p.y - PAD;
944
+ if ('influence' in mesh) {
945
+ try {
946
+ const m = influenceLattice(img, rasterAlpha(img), mesh.influence.cell);
947
+ return fixedTriangleRow(row, oy, m.points, m.triangles);
948
+ } catch {
949
+ return null;
950
+ }
951
+ }
952
+ if ('contour' in mesh) {
953
+ const m = rigContour(p, img, mesh.contour, []);
954
+ return Array.isArray(m) ? null : fixedTriangleRow(row, oy, m.vertices, m.triangles);
955
+ }
956
+ if ('grid' in mesh) {
957
+ const m = latticeMesh(p.name, alphaAbove(img, ART_ALPHA), mesh.grid);
958
+ return 'code' in m ? null : fixedTriangleRow(row, oy, m.vertices, m.triangles);
959
+ }
960
+ return null;
961
+ }
962
+
898
963
  /**
899
964
  * Issue #518: the figure {@link influenceReach} holds an influence mesh's radius above, measured as the rig stage
900
965
  * measures it — rig-c's segments lattice at `cell` over the part padded by {@link PAD} (alpha above
@@ -904,11 +969,9 @@ export function influenceReach(points: ReadonlyArray<readonly [number, number]>,
904
969
  */
905
970
  export function influenceFarthest(img: Raster, x: number, y: number, segs: readonly Segment[], cell: number): number | null {
906
971
  const padded = pad(img, PAD, PAD, PAD, PAD, [0, 0, 0, 0]);
907
- const alpha = new Uint8Array(padded.width * padded.height);
908
- for (let i = 0; i < alpha.length; i++) alpha[i] = padded.data[i * 4 + 3];
909
972
  let lattice: SegmentsLattice;
910
973
  try {
911
- lattice = buildSegmentsLattice({ mask: { width: padded.width, height: padded.height, alpha }, threshold: INFLUENCE_THRESHOLD, cell });
974
+ lattice = influenceLattice(padded, rasterAlpha(padded), cell);
912
975
  } catch {
913
976
  return null;
914
977
  }
@@ -1995,7 +2058,13 @@ export function buildWaistPairSource(
1995
2058
  if (cur === 'hip') hipChainLinks.add(l);
1996
2059
  }
1997
2060
  }
1998
- const dressSegsAt = (p: PartsFile['parts'][number], segs: Segment[]): ((wy: number) => Segment[]) => {
2061
+ const dressSegsAt = (p: PartsFile['parts'][number], segs: Segment[], heldRow?: number): ((wy: number) => Segment[]) => {
2062
+ const fixed = cfg.meshes[p.name]?.fixed_above;
2063
+ const hold = fixed === undefined ? null : segs.filter((s) => fixed.bones.includes(s.bone));
2064
+ const legacy = legacyDressSegsAt(p, segs);
2065
+ return (wy) => fixed !== undefined && hold !== null && wy <= (heldRow ?? fixed.row) ? hold : legacy(wy);
2066
+ };
2067
+ const legacyDressSegsAt = (p: PartsFile['parts'][number], segs: Segment[]): ((wy: number) => Segment[]) => {
1999
2068
  const hipBone = B.get('hip');
2000
2069
  if (hipBone === undefined) return () => segs;
2001
2070
  const isDress =
@@ -2033,16 +2102,9 @@ export function buildWaistPairSource(
2033
2102
  const oy = p.y - PAD;
2034
2103
  const w = img.width;
2035
2104
  const h = img.height;
2036
- const alpha = new Uint8Array(w * h);
2037
- for (let i = 0; i < alpha.length; i++) alpha[i] = img.data[i * 4 + 3];
2038
2105
  const regions = contourRegionsOf(spec);
2039
- const inPart: ContourRegion[] = regions.map((rg) =>
2040
- rg.shape === 'circle'
2041
- ? { name: rg.name, shape: 'circle', cx: rg.cx - ox, cy: rg.cy - oy, r: rg.r, spacing: rg.spacing, band: rg.band }
2042
- : { name: rg.name, shape: 'polygon', points: rg.points.map(([x, y]) => [x - ox, y - oy] as [number, number]), spacing: rg.spacing, band: rg.band },
2043
- );
2044
2106
  const ribs = chainRibs(ribSpec.segments, ribSpec.ribs, ox, oy);
2045
- const cm = contourMesh(p.name, { width: w, height: h, alpha }, { threshold: ART_ALPHA, tolerance: spec.tolerance, margin: spec.margin, spacing: spec.spacing, ...(spec.maxEdge === undefined ? {} : { maxEdge: spec.maxEdge }), budget: spec.budget, stray: spec.stray, ...(spec.bridges === undefined ? {} : { bridges: spec.bridges }), regions: inPart, ...(ribs.length === 0 ? {} : { ribs }) });
2107
+ const cm = rigContour(p, img, spec, ribs);
2046
2108
  if (Array.isArray(cm)) {
2047
2109
  out.push(...cm);
2048
2110
  return null;
@@ -2054,7 +2116,9 @@ export function buildWaistPairSource(
2054
2116
  out.push(...heat);
2055
2117
  return null;
2056
2118
  }
2057
- const segsAt = dressSegsAt(p, segs);
2119
+ const fixed = cfg.meshes[p.name]?.fixed_above;
2120
+ const heldRow = fixed === undefined ? undefined : fixedTriangleRow(fixed.row, oy, cm.vertices, cm.triangles);
2121
+ const segsAt = dressSegsAt(p, segs, heldRow);
2058
2122
  const weights: WeightEntry[][] = [];
2059
2123
  const reached = regions.map(() => 0);
2060
2124
  const whole = regions.map(() => 0);
@@ -2165,11 +2229,10 @@ export function buildWaistPairSource(
2165
2229
  const w = img.width;
2166
2230
  const h = img.height;
2167
2231
  const at = `config.meshes.${p.name}.influence`;
2168
- const alpha = new Uint8Array(w * h);
2169
- for (let i = 0; i < alpha.length; i++) alpha[i] = img.data[i * 4 + 3];
2232
+ const alpha = rasterAlpha(img);
2170
2233
  let lattice: SegmentsLattice;
2171
2234
  try {
2172
- lattice = buildSegmentsLattice({ mask: { width: w, height: h, alpha }, threshold: INFLUENCE_THRESHOLD, cell: spec.influence.cell });
2235
+ lattice = influenceLattice(img, alpha, spec.influence.cell);
2173
2236
  } catch (err) {
2174
2237
  out.push({ code: 'RIG_INFLUENCE_LATTICE', object: `${at}.cell`, detail: `rig-c's segments lattice refused part "${p.name}" at cell ${spec.influence.cell}: ${(err as Error).message}` });
2175
2238
  return null;
@@ -2201,10 +2264,16 @@ export function buildWaistPairSource(
2201
2264
  // Issue #615: `hold_tip: true`, declared on the mesh (propose writes it from the recipe's `split.hold_tip`), smooths
2202
2265
  // the pulled shares by the lattice's held-fork passes, capped at the declared `max`; absent, the shares are rig-c's.
2203
2266
  const shares = spec.influence.hold_tip === true ? smoothForkShares(pulled, lattice.triangles, spec.influence.max) : pulled;
2267
+ const fixed = cfg.meshes[p.name]?.fixed_above;
2268
+ const heldRow = fixed === undefined ? undefined : fixedTriangleRow(fixed.row, oy, lattice.points, lattice.triangles);
2269
+ const segsAt = dressSegsAt(p, [...segs], heldRow);
2204
2270
  for (const [vi, [x, y]] of lattice.points.entries()) {
2205
2271
  const wx = x + ox;
2206
2272
  const wy = y + oy;
2207
- const ent: WeightEntry[] = shares[vi].map(({ bone, weight }) => {
2273
+ const row = heldRow !== undefined && wy <= heldRow
2274
+ ? roundShares(influences([wx, wy], segsAt(wy), spec.influence.cell, { maxInfluences: spec.influence.max, minWeight: 0 }))
2275
+ : shares[vi];
2276
+ const ent: WeightEntry[] = row.map(({ bone, weight }) => {
2208
2277
  const [bx, by] = toBoneLocal(world.get(bone) as BoneTransform, spineX(wx), spineY(wy));
2209
2278
  return { bone, x: places(bx), y: places(by), weight };
2210
2279
  });
@@ -2648,7 +2717,9 @@ export function buildWaistPairSource(
2648
2717
  let maxInfl = 0;
2649
2718
  // issue #284: the mesh's declared cap and floor form, or DEFAULT_LIMITS itself when it declares none.
2650
2719
  const limits: InfluenceLimits = meshLimits(mesh.influences);
2651
- const segsAt = dressSegsAt(p, segs);
2720
+ const fixed = mesh.fixed_above;
2721
+ const heldRow = fixed === undefined ? undefined : fixedTriangleRow(fixed.row, oy, lm.vertices, lm.triangles);
2722
+ const segsAt = dressSegsAt(p, segs, heldRow);
2652
2723
  let emptied: { vertex: number; at: Point; capped: Influence[] } | null = null;
2653
2724
  let emptiedMore = 0;
2654
2725
  const rawShares: Influence[][] = [];
@@ -2685,7 +2756,8 @@ export function buildWaistPairSource(
2685
2756
  for (const [vi, [vx0, vy0]] of lm.vertices.entries()) {
2686
2757
  const wx = vx0 + ox;
2687
2758
  const wy = vy0 + oy;
2688
- const ent: WeightEntry[] = finalShares[vi].map(({ bone, weight }) => {
2759
+ const row = heldRow !== undefined && wy <= heldRow ? rawShares[vi] : finalShares[vi];
2760
+ const ent: WeightEntry[] = row.map(({ bone, weight }) => {
2689
2761
  const [x, y] = toBoneLocal(world.get(bone) as BoneTransform, spineX(wx), spineY(wy));
2690
2762
  return { bone, x: places(x), y: places(y), weight };
2691
2763
  });
@@ -2943,7 +3015,9 @@ export function buildWaistPairSource(
2943
3015
  const w = img.width;
2944
3016
  const h = img.height;
2945
3017
  const limits: InfluenceLimits = meshLimits('influences' in mesh ? mesh.influences : undefined);
2946
- const segsAt = dressSegsAt(p, segs);
3018
+ const fixed = mesh.fixed_above;
3019
+ const heldRow = fixed === undefined ? undefined : fixedTriangleRow(fixed.row, oy, lm.vertices, lm.triangles);
3020
+ const segsAt = dressSegsAt(p, segs, heldRow);
2947
3021
  const exponent = ('exponent' in mesh ? mesh.exponent : undefined) ?? DISTANCE_EXPONENT;
2948
3022
  let touchesArt: boolean[] | null = null;
2949
3023
  if (band === null && drawn !== undefined && limits.maxInfluences === 1) {
package/src/scene.ts CHANGED
@@ -96,7 +96,7 @@ import { existsSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync }
96
96
  import { dirname, join, resolve } from 'node:path';
97
97
  import type { RigStop } from '@rig-c/core/rig';
98
98
  import { checkStage, gateThroughRigc, type Log } from './build.ts';
99
- import { ACCEPTABLE_BARS, barsNotMet, type CheckReport, DEFAULT_PACK_SHAPE, DEFAULT_PAGE_EDGES, type PackMode, parsePageSize, requirementsNotPass, type RigcRunner } from './check.ts';
99
+ import { ACCEPTABLE_BARS, barsNotMet, CHECK_SPEC, type CheckReport, DEFAULT_PACK_SHAPE, DEFAULT_PAGE_EDGES, type PackMode, parsePageSize, requirementsNotPass, type RigcRunner } from './check.ts';
100
100
  import { CONSTRAINT_BONE_FIELDS, editorReceiptProblems, ROOT_BONE } from './config.ts';
101
101
  import { cropToSpineY } from './coords.ts';
102
102
  import { failLine, PartsError, type Problem, refuseIfAny } from './errors.ts';
@@ -497,6 +497,22 @@ function readJson(path: string, what: string, problems: Problem[], consumed: (by
497
497
  }
498
498
  }
499
499
 
500
+ /**
501
+ * The bars a character's `check/check.json` says failed: on a versioned
502
+ * {@link CHECK_SPEC} report, the declared `bar_outcomes` ids whose outcome
503
+ * status is `'FAIL'` in the report's order (issue #1373); on a report without
504
+ * that spec, {@link barsNotMet}'s legacy figure reading.
505
+ */
506
+ export function checkBarsFailed(ck: Readonly<Record<string, unknown>>): string[] {
507
+ if (ck.spec === CHECK_SPEC) {
508
+ const outcomes = isRecord(ck.bar_outcomes) ? ck.bar_outcomes : {};
509
+ return Object.entries(outcomes)
510
+ .filter(([, outcome]) => isRecord(outcome) && outcome.status === 'FAIL')
511
+ .map(([id]) => id);
512
+ }
513
+ return barsNotMet(ck);
514
+ }
515
+
500
516
  /**
501
517
  * Read one character's build, collecting every problem: the files `build`
502
518
  * writes (`SCENE_BUILD_PRESENT`), its own check green (`SCENE_BUILD_GREEN`:
@@ -507,8 +523,11 @@ function readJson(path: string, what: string, problems: Problem[], consumed: (by
507
523
  * `accept` (issue #203) is `compose --accept`, joined with the character's own
508
524
  * `accept`: a check that is not green is taken when every bar it failed is
509
525
  * named in that join, its gate green and every declared requirement PASS;
510
- * otherwise it is `SCENE_BUILD_GREEN`, naming the bars not accepted. Without
511
- * an accept list the refusal reads as it always did.
526
+ * otherwise it is `SCENE_BUILD_GREEN`, naming the bars not accepted. When the
527
+ * report declares `spec: "rig-parts-check/1"`, the failing bars are read from
528
+ * `bar_outcomes` ({@link checkBarsFailed}, issue #1373); without that spec,
529
+ * from {@link barsNotMet}. Without an accept list the refusal reads as it
530
+ * always did.
512
531
  */
513
532
  export function readCharacterBuild(c: SceneCharacter, problems: Problem[], accept: readonly string[] = []): CharacterBuild | null {
514
533
  const before = problems.length;
@@ -529,7 +548,7 @@ export function readCharacterBuild(c: SceneCharacter, problems: Problem[], accep
529
548
  if (check !== undefined) {
530
549
  const ck = isRecord(check) ? check : {};
531
550
  if ((ck.PASS !== true || ck.gate_spine_html_green !== true) && joined.size > 0) {
532
- const failed = barsNotMet(ck);
551
+ const failed = checkBarsFailed(ck);
533
552
  const reqs = requirementsNotPass(ck);
534
553
  const not = failed.filter((b) => !joined.has(b));
535
554
  if (not.length === 0 && reqs.length === 0 && failed.length > 0) accepted = failed;
@@ -1085,10 +1104,17 @@ export function composeScene(
1085
1104
  ...b.rig.slots.map(x => prefixed(b.id, x.name)),
1086
1105
  ...Object.keys(b.motion.animations).map(n => prefixed(b.id, n)),
1087
1106
  ])]);
1107
+ const refusedLayerNames = new Set<string>();
1088
1108
  layers.forEach((p, i) => {
1089
1109
  const where = `scene.plates[${i}] (${show(p.name)})`;
1090
- if (reserved.has(p.name)) fail('SCENE_PLATE_NAME_FREE', `${where}.name`, `is ${show(p.name)}, reserved by the shared root, legacy plate, character id, bone, slot or animation; a distinct name is required`);
1091
- if (layers.findIndex(q => q.name === p.name) !== i) fail('SCENE_PLATE_NAME_UNIQUE', `${where}.name`, `is ${show(p.name)}, already declared; every plate has one name`);
1110
+ if (reserved.has(p.name)) {
1111
+ refusedLayerNames.add(p.name);
1112
+ fail('SCENE_PLATE_NAME_FREE', `${where}.name`, `is ${show(p.name)}, reserved by the shared root, legacy plate, character id, bone, slot or animation; a distinct name is required`);
1113
+ }
1114
+ if (layers.findIndex(q => q.name === p.name) !== i) {
1115
+ refusedLayerNames.add(p.name);
1116
+ fail('SCENE_PLATE_NAME_UNIQUE', `${where}.name`, `is ${show(p.name)}, already declared; every plate has one name`);
1117
+ }
1092
1118
  if (!(Array.isArray(p.at) && p.at.length === 2 && p.at.every(v => Number.isFinite(v) && Number.isInteger(v)))) fail('SCENE_PLATE_AT', `${where}.at`, `is ${show(p.at)}; two finite integers of canvas pixels locating the image top-left are required`);
1093
1119
  const img = plateLayers[i];
1094
1120
  if (img === undefined || img === null) {
@@ -1163,7 +1189,8 @@ export function composeScene(
1163
1189
  const layerAt = new Map<string, number>();
1164
1190
  scene.order.forEach((e, i) => {
1165
1191
  const at = `scene.order[${i}]`;
1166
- if (layerNames.has(e)) {
1192
+ const isCharOrSlot = ids.includes(e) || (e.includes(PREFIX_SEP) && ids.includes(e.slice(0, e.indexOf(PREFIX_SEP))));
1193
+ if (layerNames.has(e) && !(refusedLayerNames.has(e) && isCharOrSlot)) {
1167
1194
  const first = layerAt.get(e);
1168
1195
  if (first !== undefined) fail('SCENE_ORDER_ONCE', at, `names the plate ${show(e)} again (first at scene.order[${first}]); every plate slot is drawn exactly once`);
1169
1196
  else layerAt.set(e, i);
@@ -1204,7 +1231,7 @@ export function composeScene(
1204
1231
  fail('SCENE_ORDER_COMPLETE', `scene.order (character "${id}")`, `names ${missing.length} of the ${own.length} slot(s) of "${id}" nowhere: ${missing.map((s) => `"${prefixed(id, s)}"`).join(', ')}; every slot is drawn exactly once — name "${id}" (its remaining slots, in its own order) or each slot`);
1205
1232
  }
1206
1233
  }
1207
- for (const p of layers) if (!layerAt.has(p.name)) fail('SCENE_ORDER_COMPLETE', 'scene.order', `names plate ${show(p.name)} nowhere; every plate slot is drawn exactly once`);
1234
+ for (const p of layers) if (!refusedLayerNames.has(p.name) && !layerAt.has(p.name)) fail('SCENE_ORDER_COMPLETE', 'scene.order', `names plate ${show(p.name)} nowhere; every plate slot is drawn exactly once`);
1208
1235
  const drawn: string[] = [];
1209
1236
  for (const e of scene.order) {
1210
1237
  if (layerNames.has(e)) { drawn.push(e); continue; }
@@ -1821,7 +1848,16 @@ export function composeStage(input: ComposeInput, run: ComposeRunners, log: Log)
1821
1848
  }
1822
1849
  const r = composed.report;
1823
1850
  r.scene = input.scene;
1824
- say(`${r.characters.length} character(s) on a ${r.canvas.width}x${r.canvas.height} canvas, rig "${r.rig_name}"${r.plate === null ? ', no plate' : `, plate ${r.plate.image} (provenance ${r.plate.provenance}, judged by nothing)`}`);
1851
+ const namedPlates = r.plates ?? [];
1852
+ const plateClause =
1853
+ r.plate !== null && namedPlates.length > 0
1854
+ ? `, plate ${r.plate.image} (provenance ${r.plate.provenance}, judged by nothing), ${namedPlates.length} named plate(s): ${namedPlates.map((p) => p.name).join(', ')}`
1855
+ : r.plate !== null
1856
+ ? `, plate ${r.plate.image} (provenance ${r.plate.provenance}, judged by nothing)`
1857
+ : namedPlates.length > 0
1858
+ ? `, ${namedPlates.length} named plate(s): ${namedPlates.map((p) => p.name).join(', ')}`
1859
+ : ', no plate';
1860
+ say(`${r.characters.length} character(s) on a ${r.canvas.width}x${r.canvas.height} canvas, rig "${r.rig_name}"${plateClause}`);
1825
1861
  for (const c of r.characters) {
1826
1862
  say(` ${c.id}: ${c.build} at offset [${c.offset.join(', ')}], scale ${c.scale ?? 1}, bounds [${c.bounds.join(', ')}], shift [${c.shift.join(', ')}] on ${c.shifted.bones.length} first-level bone(s), ${c.shifted.root_regions.length} region(s) on root and ${c.shifted.root_weights} weight(s) bound to root; ${c.bones} bone(s), ${c.slots} slot(s), ${c.tracks} track(s), ${c.constraints} constraint(s), rig_scale ${c.rig_scale}, idle ${c.idle_duration} s${c.accepted === undefined ? '' : `; its own check FAILED ${c.accepted.join(', ')}, accepted — the scene is for looking, not shipping`}`);
1827
1863
  }
package/src/sceneclips.ts CHANGED
@@ -104,6 +104,60 @@ export function scenePoseState(pose: RawPose): string {
104
104
  return JSON.stringify({ bones: pose.bones, slots: pose.slots, drawOrder: pose.drawOrder, drawn: pose.drawn, clips: pose.clips, clipped: pose.clipped });
105
105
  }
106
106
 
107
+ interface PoseDifference {
108
+ path: Array<string | number>;
109
+ start: unknown;
110
+ end: unknown;
111
+ }
112
+
113
+ /** Walk the same JSON values the closure gate compares, in producer field/array order.
114
+ * No rounding or epsilon: the existing numeric tolerance is exactly zero.
115
+ */
116
+ function firstPoseDifference(start: unknown, end: unknown, path: Array<string | number> = []): PoseDifference | null {
117
+ if (JSON.stringify(start) === JSON.stringify(end)) return null;
118
+ if (Array.isArray(start) && Array.isArray(end)) {
119
+ for (let i = 0; i < Math.max(start.length, end.length); i++) {
120
+ const difference = firstPoseDifference(start[i], end[i], [...path, i]);
121
+ if (difference !== null) return difference;
122
+ }
123
+ } else if (start !== null && end !== null && typeof start === 'object' && typeof end === 'object') {
124
+ const a = start as Record<string, unknown>, b = end as Record<string, unknown>;
125
+ for (const key of new Set([...Object.keys(a), ...Object.keys(b)])) {
126
+ const difference = firstPoseDifference(a[key], b[key], [...path, key]);
127
+ if (difference !== null) return difference;
128
+ }
129
+ }
130
+ return { path, start, end };
131
+ }
132
+
133
+ /** Name geometry-only differences too, including invisible slots and clipping. */
134
+ function poseDifferenceDetail(start: RawPose, end: RawPose): string {
135
+ const difference = firstPoseDifference(JSON.parse(scenePoseState(start)), JSON.parse(scenePoseState(end)));
136
+ if (difference === null) return 'endpoint sample clocks differ';
137
+ const [family, index, ...fields] = difference.path;
138
+ const i = typeof index === 'number' ? index : -1;
139
+ let object = 'pose', channel = difference.path.map(String).join('.');
140
+ if (family === 'bones') {
141
+ object = `bone ${JSON.stringify(start.bones[i]?.name ?? end.bones[i]?.name)}`;
142
+ channel = fields.map(String).join('.') || 'presence';
143
+ } else if (family === 'slots') {
144
+ object = `slot ${JSON.stringify(start.slots[i]?.[0] ?? end.slots[i]?.[0])}`;
145
+ const [field, ...rest] = fields;
146
+ const channels = ['name', 'attachment', 'r', 'g', 'b', 'a', 'dark', 'path', 'blend'];
147
+ channel = [typeof field === 'number' ? channels[field] : 'presence', ...rest].join('.');
148
+ } else if (family === 'drawOrder') {
149
+ object = `slot ${JSON.stringify(start.drawOrder[i] ?? end.drawOrder[i])}`;
150
+ channel = `drawOrder[${i}]`;
151
+ } else if (family === 'drawn' || family === 'clips' || family === 'clipped') {
152
+ const a = start[family][i], b = end[family][i];
153
+ const slot = (row: typeof a) => row === undefined ? undefined : Array.isArray(row) ? row[0] : row.slot;
154
+ object = `slot ${JSON.stringify(slot(a) ?? slot(b))}`;
155
+ channel = `${family}.${fields.map(String).join('.') || 'presence'}`;
156
+ }
157
+ const value = (v: unknown) => v === undefined ? 'absent' : JSON.stringify(v);
158
+ return `${object} channel ${channel}: start ${value(difference.start)} at t=0; end ${value(difference.end)} at t=${end.trackTime}; tolerance 0 (exact equality)`;
159
+ }
160
+
107
161
  /** A throwaway keyed-pose view; simulation is retained in the emitted document. */
108
162
  export function sceneKeyedModel(modelText: string) {
109
163
  const raw = JSON.parse(modelText) as Record<string, unknown>;
@@ -128,7 +182,12 @@ export function sceneClipLoopProblems(modelText: string, clips: SceneAnimations)
128
182
  for (const [name, clip] of Object.entries(clips)) {
129
183
  const poses = poseRawAnimation(doc, name, [clip.duration]);
130
184
  if (poses.length !== 2 || poses[0].animationTime !== 0 || poses[1].trackTime !== clip.duration || scenePoseState(poses[0]) !== scenePoseState(poses[1])) {
131
- problems.push({ code: 'SCENE_ANIMATION_LOOP_CLOSES', object: `scene.animations.${name}`, detail: `posed samples at t=0 and t=${clip.duration} differ; identical endpoint poses are required (physics left out: ${physics.join(', ') || 'none'})` });
185
+ const difference = poses.length !== 2
186
+ ? `pose sample count ${poses.length}; required 2 at t=0 and t=${clip.duration}`
187
+ : poses[0].animationTime !== 0 || poses[1].trackTime !== clip.duration
188
+ ? `pose sample clocks start ${poses[0].animationTime}, end ${poses[1].trackTime}; required 0 and ${clip.duration}; tolerance 0 (exact equality)`
189
+ : poseDifferenceDetail(poses[0], poses[1]);
190
+ problems.push({ code: 'SCENE_ANIMATION_LOOP_CLOSES', object: `scene.animations.${name}`, detail: `${difference}; identical endpoint poses are required (physics left out: ${physics.join(', ') || 'none'})` });
132
191
  }
133
192
  }
134
193
  return problems;
package/src/turn.ts CHANGED
@@ -28,6 +28,7 @@
28
28
  * that the depth maps do not carry relief inside a layer, so a part moves as
29
29
  * one piece. Pure: no file, no clock.
30
30
  */
31
+ import { boundaryDepthSamplers, type BoundaryDepths } from './boundarydepth.ts';
31
32
  import { computeWorldTransforms, setupToPaintingPoint, toBoneLocalVector, toWorld, type BoneTransform } from './coords.ts';
32
33
  import { extendDepthSilhouette, sampleDepthFloat, type PartDepthReference } from './depthsheets.ts';
33
34
  import { type Problem, refuseIfAny } from './errors.ts';
@@ -265,6 +266,7 @@ export interface TurnBodySpec {
265
266
  counter?: number;
266
267
  grid?: [number, number] | Record<string, [number, number]>;
267
268
  unitDepths?: Record<string, number>;
269
+ boundaryDepths?: BoundaryDepths;
268
270
  }
269
271
 
270
272
  /** `config.turn`: either the legacy `{ pivot, depths }` turn spec or the 2.5D depth-sampled `{ roles, body?, pivot?, counter?, grid?, unitDepths?, band? }` spec (#763, #787). */
@@ -276,6 +278,7 @@ export interface TurnSpec {
276
278
  counter?: number;
277
279
  grid?: [number, number] | Record<string, [number, number]>;
278
280
  unitDepths?: Record<string, number>;
281
+ boundaryDepths?: BoundaryDepths;
279
282
  head?: { pivot?: number; radius?: number };
280
283
  surface?: { radius?: number };
281
284
  radius?: number;
@@ -1516,6 +1519,7 @@ interface Depth25DGroupSpec {
1516
1519
  pivot: number;
1517
1520
  counter: number;
1518
1521
  unitDepths?: Record<string, number>;
1522
+ boundaryDepths?: BoundaryDepths;
1519
1523
  carrierBone: string;
1520
1524
  rearCarrierBone: string;
1521
1525
  unitGroupName: string;
@@ -1629,6 +1633,11 @@ function buildDepth25DTurnGroup(
1629
1633
  if (primarySurface !== undefined) {
1630
1634
  for (const sheet of surfaceSheets.values()) sheet.zRef = primarySurface.zRef;
1631
1635
  }
1636
+ // Resolve on original sheets AFTER choosing the original shared anchor.
1637
+ const boundary = boundaryDepthSamplers(group.boundaryDepths, opts.parts, opts.images, group.roles, group.fieldPrefix);
1638
+ problems.push(...boundary.problems);
1639
+ if (problems.length > startProblems) return;
1640
+ const boundarySamples = boundary.samplers;
1632
1641
  const pivot = pyRound(group.pivot, 4);
1633
1642
  const counter = group.counter;
1634
1643
  const rearDepth = pyRound(-counter * pivot, 4);
@@ -1865,7 +1874,14 @@ function buildDepth25DTurnGroup(
1865
1874
  }>;
1866
1875
  }> = [];
1867
1876
  for (const [part, { rec, ext, zRef }] of surfaceSheets) {
1877
+ const boundarySample = boundarySamples.get(part);
1868
1878
  const authored = opts.surfaceMeshes?.filter((m) => m.part === part) ?? [];
1879
+ // Core grids already expose their exact topology as neighbour support.
1880
+ // Only an opted-in grid needs explicit offsets; legacy transforms stay intact.
1881
+ if (boundarySample !== undefined && authored.length === 0) {
1882
+ authored.push(...(opts.neighbourMeshes?.filter(m => m.part === part && m.gridSamples !== undefined) ?? []));
1883
+ if (authored.length === 0) problems.push({ code: 'RIG_TURN_BOUNDARY_DEPTH', object: `${group.fieldPrefix}.boundaryDepths.${part}`, detail: 'has no resolved grid sampling topology; supply the generated grid support' });
1884
+ }
1869
1885
  if (authored.length > 0) {
1870
1886
  const setup = surfaceSetupGraph(rig);
1871
1887
  const world = computeWorldTransforms(setup.bones);
@@ -1884,7 +1900,7 @@ function buildDepth25DTurnGroup(
1884
1900
  }
1885
1901
  // A unit/rear mesh sharing this root would move our bindings too.
1886
1902
  let ancestor = setup.bones.find((b) => b.name === setup.resolve(w.bone));
1887
- while (ancestor !== undefined) {
1903
+ while (ancestor !== undefined && mesh.gridSamples === undefined) {
1888
1904
  if ([FACESHIFT_BONE, REAR_SHIFT_BONE, BODYSHIFT_BONE, BODY_REAR_SHIFT_BONE].includes(ancestor.name)) {
1889
1905
  problems.push({ code: 'RIG_TURN_SURFACE_MESH_BINDINGS', object: `${group.fieldPrefix}.roles.${part}`, detail: `binds "${w.bone}" through turn carrier "${ancestor.name}" shared with another role; surface mesh bindings must retain their authored frame` });
1890
1906
  break;
@@ -1898,8 +1914,11 @@ function buildDepth25DTurnGroup(
1898
1914
  problems.push({ code: 'RIG_TURN_SURFACE_MESH_BINDINGS', object: `surface mesh "${mesh.slot}/${mesh.attachment}" vertex ${index}`, detail: `has influence sum ${total}; weights closing at 1 are required to sample a setup position` });
1899
1915
  }
1900
1916
  const [cx, cy] = setupToPaintingPoint([wx, wy], mesh.canvas, mesh.canvas);
1901
- const z = levelToDepthZ(sampleDepthFloat(ext, cx - rec.x, cy - rec.y), rec.depth);
1902
- return { row, depth: pivot + z - zRef };
1917
+ const point = mesh.gridSamples?.[index] ?? [cx, cy];
1918
+ const level = boundarySample?.(point[0], point[1]) ?? sampleDepthFloat(ext, point[0] - rec.x, point[1] - rec.y);
1919
+ const z = levelToDepthZ(level, rec.depth);
1920
+ // Grid carrier tracks already contribute pivot-zRef once.
1921
+ return { row, depth: mesh.gridSamples === undefined ? pivot + z - zRef : z };
1903
1922
  });
1904
1923
  if (problems.length > startProblems || !active) continue;
1905
1924
  deform.push({
@@ -2183,6 +2202,7 @@ export function buildDepth25DTurn(
2183
2202
  pivot: opts.turn.pivot ?? DEFAULT_TURN_PIVOT_25D,
2184
2203
  counter: opts.turn.counter ?? DEFAULT_TURN_COUNTER_25D,
2185
2204
  unitDepths: opts.turn.unitDepths,
2205
+ boundaryDepths: opts.turn.boundaryDepths,
2186
2206
  carrierBone: FACESHIFT_BONE,
2187
2207
  rearCarrierBone: REAR_SHIFT_BONE,
2188
2208
  unitGroupName: 'turn_units',
@@ -2210,6 +2230,7 @@ export function buildDepth25DTurn(
2210
2230
  pivot: body.pivot ?? opts.turn.pivot ?? DEFAULT_TURN_PIVOT_25D,
2211
2231
  counter: body.counter ?? opts.turn.counter ?? DEFAULT_TURN_COUNTER_25D,
2212
2232
  unitDepths: body.unitDepths ?? opts.turn.unitDepths,
2233
+ boundaryDepths: body.boundaryDepths,
2213
2234
  carrierBone: BODYSHIFT_BONE,
2214
2235
  rearCarrierBone: BODY_REAR_SHIFT_BONE,
2215
2236
  unitGroupName: 'body_turn_units',
@@ -108,26 +108,35 @@ function unchanged(target: ConfigWriteTarget): void {
108
108
  } catch { /* Removal is also a change, never a reason to create a new config. */ }
109
109
  if (!same) refusal('CONFIG_WRITE_CHANGED', target.path, 'changed after it was read; nothing was replaced — rerun against the current config');
110
110
  }
111
+
112
+ function configWriteDoor(patch: ConfigWritePatch, receiptDoor: 'full' | 'assemble'): 'layers' | 'assemble' | 'full' {
113
+ if (patch.kind === 'head-box') return 'layers';
114
+ if (patch.kind === 'assemble-plan') return 'assemble';
115
+ return patch.kind === 'edited-part-receipt' ? receiptDoor : 'full';
116
+ }
117
+
111
118
  /** One file-writing adapter for all --write-config modes. Existing-file ownership
112
119
  * produces whole-value edits for splicedEdits, the engine clothConfigEdits uses.
113
120
  * Fresh cloth text already passed writtenClothConfig's splice check: it is never
114
121
  * sent through a full loader that would reject an intentional partial config.
115
122
  */
116
- export function stageConfigWrite(target: ConfigWriteTarget | FreshConfigWrite, patch?: ConfigWritePatch, files: ConfigWriteFiles = {}): StagedConfigWrite {
123
+ export function stageConfigWrite(target: ConfigWriteTarget | FreshConfigWrite, patch?: ConfigWritePatch, files: ConfigWriteFiles = {}, receiptDoor: 'full' | 'assemble' = 'full'): StagedConfigWrite {
117
124
  const fresh = 'kind' in target;
118
125
  const path = resolve(target.path);
119
126
  let text: string;
120
127
  let changes: readonly ConfigWriteChange[];
128
+ let door: ReturnType<typeof configWriteDoor> | undefined;
121
129
  if (fresh) {
122
130
  text = target.text;
123
131
  changes = [];
124
132
  } else {
125
133
  if (patch === undefined) return refusal('CONFIG_FIELD_TYPE', path, 'has no config patch; a supported proposal operation is required');
126
- const merged = mergeConfigProposal(target.raw, patch);
134
+ const merged = mergeConfigProposal(target.raw, patch, receiptDoor);
127
135
  const spliced = merged.changes.length === 0 ? { text: target.original, moved: null } : splicedEdits(target.original, merged.edits);
128
136
  if (spliced.moved !== null) return refusal('CONFIG_WRITE_FAILED', path, `spliced proposal values moved ${spliced.moved}; the original was not replaced`);
129
137
  text = spliced.text;
130
138
  changes = merged.changes;
139
+ door = configWriteDoor(patch, receiptDoor);
131
140
  }
132
141
  const freshAbsent = (): void => {
133
142
  try { lstatSync(path); }
@@ -155,11 +164,9 @@ export function stageConfigWrite(target: ConfigWriteTarget | FreshConfigWrite, p
155
164
  if (!fresh) fchmodSync(fd, target.mode);
156
165
  closeSync(fd);
157
166
  fd = undefined;
158
- if (!fresh) {
159
- if (patch?.kind === 'head-box') loadEarlyConfig(temp, 'layers');
160
- else if (patch?.kind === 'assemble-plan') loadEarlyConfig(temp, 'assemble');
161
- else loadConfigAndAnimations(temp);
162
- }
167
+ if (door === 'layers') loadEarlyConfig(temp, 'layers');
168
+ else if (door === 'assemble') loadEarlyConfig(temp, 'assemble');
169
+ else if (door === 'full') loadConfigAndAnimations(temp);
163
170
  } catch (error) {
164
171
  if (fd !== undefined) {
165
172
  try { closeSync(fd); }
@@ -204,7 +211,7 @@ export function configWriteLines(target: ConfigWriteTarget, changes: readonly Co
204
211
  return changes.length === 0 ? [`config ${target.path}: unchanged`] : changes.map((c) => `config ${target.path}: ${c.kind} ${c.path}${c.value === undefined ? '' : ` ${c.value}`}`);
205
212
  }
206
213
 
207
- export interface ConfigWriteRequest { target: ConfigWriteTarget; patch: ConfigWritePatch }
214
+ export interface ConfigWriteRequest { target: ConfigWriteTarget; patch: ConfigWritePatch; receiptDoor?: 'full' | 'assemble' }
208
215
  export interface StagedConfigWriteBatch {
209
216
  writes: ReadonlyArray<{ target: ConfigWriteTarget; changes: readonly ConfigWriteChange[] }>;
210
217
  commit(): void;
@@ -231,14 +238,15 @@ export function stageConfigWriteBatch(requests: readonly ConfigWriteRequest[], f
231
238
  }
232
239
  // Candidate shape refusals precede even temporary writes. The existing
233
240
  // stage loader then validates each real same-directory staged file, including
234
- // relative sidecars. Edited receipts are full-config updates, not early drafts.
235
- for (const { target, patch } of requests) {
236
- const candidate = mergeConfigProposal(target.raw, patch).config;
237
- if (patch.kind === 'head-box') parseEarlyConfig(candidate, 'layers');
238
- else if (patch.kind === 'assemble-plan') parseEarlyConfig(candidate, 'assemble');
241
+ // relative sidecars.
242
+ for (const { target, patch, receiptDoor = 'full' } of requests) {
243
+ const candidate = mergeConfigProposal(target.raw, patch, receiptDoor).config;
244
+ const door = configWriteDoor(patch, receiptDoor);
245
+ if (door === 'layers') parseEarlyConfig(candidate, 'layers');
246
+ else if (door === 'assemble') parseEarlyConfig(candidate, 'assemble');
239
247
  else parseConfig(candidate);
240
248
  }
241
- for (const { target, patch } of requests) entries.push({ target, staged: stageConfigWrite(target, patch, files), backup: null, committed: false, restoreFailed: false });
249
+ for (const { target, patch, receiptDoor } of requests) entries.push({ target, staged: stageConfigWrite(target, patch, files, receiptDoor), backup: null, committed: false, restoreFailed: false });
242
250
  } catch (error) {
243
251
  throw new PartsError([...problemsOf(error, 'config batch', 'staging configs failed'), ...cancelAll()]);
244
252
  }