rig-parts 2.58.0 → 2.59.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/README.md CHANGED
@@ -278,6 +278,7 @@ Command details and config saving are in the [command reference](docs/AUTHORING.
278
278
  | `diff-components` | [List every place the stacked parts differ from the painting](docs/AUTHORING.md#whole-figure-difference-inventory) |
279
279
  | `diff-drafts` | [Compare two assemble outputs](docs/AUTHORING.md#command-reference) |
280
280
  | `depth-prepare` | [Write one depth-model input image per part](docs/DEPTH.md#1-prepare-one-inference-image-per-part) |
281
+ | `depth-map` | [Convert a NumPy array to a depth or normals map](docs/DEPTH.md#convert-a-numpy-array) |
281
282
  | `depth-bind` | [Bind a depth map to its prepared input](docs/DEPTH.md#3-bind-every-map-to-its-prepared-input) |
282
283
  | `depth-apply` | [Apply depth maps to the parts as depth sheets](docs/DEPTH.md#4-apply-the-maps-as-depth-sheets) |
283
284
  | `edited-part` | [Record an edited part receipt](docs/AUTHORING.md#edited-rig-space-parts-assembleedited_parts-issue-1278) |
package/cli.ts CHANGED
@@ -4,6 +4,8 @@ import { diffComponentsCommand } from './src/diffcomponents.ts';
4
4
  import { DIFF_DRAFTS_SPEC, diffDraftsCommand } from './src/diffdrafts.ts';
5
5
  import { applyTakenLayers } from './src/takelayers.ts';
6
6
  import { applyDepth, bindDepthMap, prepareDepth } from './src/depthworkflow.ts';
7
+ import { depthMapFail } from './src/depthmaps.ts';
8
+ import { modelArrayMap, serializeModelArrayMap } from './src/modelarray.ts';
7
9
  import { externalReceipt } from './src/externalreceipt.ts';
8
10
  import { BUST_LANDMARKS_ACT_SCHEMA, BUST_LANDMARKS_COMMENT_ACT_SCHEMA, BUST_LANDMARKS_PROVENANCE_SPEC, BUST_LANDMARKS_PROVENANCE_SUFFIX, BUST_POINT_SHAPE_FIELDS, bustShapeClause, type BustSidecar, effectiveBustShape, planBustLandmarks, readBustSidecar, stageBustLandmarks, stageReplacements, type StagedBustLandmarks } from './src/bustlandmarks.ts';
9
11
  import { writeEditedPart } from './tools/edited-part-cli.ts';
@@ -21,7 +23,7 @@ import { writeEditedPart } from './tools/edited-part-cli.ts';
21
23
  */
22
24
  import { spawnSync } from 'node:child_process';
23
25
  import { runBuildProcess, processRigcRunner as rigcRunner } from './tools/build-process.ts';
24
- import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, statSync, writeFileSync } from 'node:fs';
26
+ import { existsSync, linkSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, statSync, writeFileSync } from 'node:fs';
25
27
  import { tmpdir } from 'node:os';
26
28
  import { basename, dirname, extname, join, resolve } from 'node:path';
27
29
  import { DEFAULT_PROJECT_RULE, DEFAULT_SEAM_RULE, headGarmentOverlaps, headGarmentWarning, HOLES_LISTED, PROJECT_RULES, type ProjectRule, proposeFields, proposePlan, proposeSinglePlan, SEAM_RULES, type SeamRule } from './src/assemble.ts';
@@ -51,7 +53,7 @@ import { chainsLeftBehind, clothConfigEdits, editPaths, plainCount, previousCoun
51
53
  import { INPUT_CHECK_FILE, INPUT_CHECK_SPEC, PROVENANCE_FILE, REMESH_SPEC, remeshStage } from './src/remesh.ts';
52
54
  import { RETUNE_FILE, RETUNE_SPEC, retuneStage } from './src/retune.ts';
53
55
  import { checkPainting, DEFAULT_PAINTING_FORM, isPaintingForm, PAINTING_FORMS, paintingFormOf } from './src/paintcheck.ts';
54
- import { readPng, writePng } from './src/raster/png.ts';
56
+ import { decodePngBytes, readPng, writePng } from './src/raster/png.ts';
55
57
  import { REQUIREMENTS_SENTENCE } from './src/requirements.ts';
56
58
  import { composeStage, IMAGE_SEP, PLATE, PROVENANCES, SCENE_REPORT_FILE, SCENE_REPORT_SPEC, SCENE_SPEC } from './src/scene.ts';
57
59
  import { buildSheet, defaultCaption, type Tile, tilesFrom } from './src/sheet.ts';
@@ -100,6 +102,12 @@ usage:
100
102
  Write per-part inference PNGs on neutral gray, upscaled and padded as
101
103
  declared, plus a source-hashed manifest. No model is bundled or called.
102
104
 
105
+ rig-parts depth-map --array <file.npy> --input <prepared.png> --kind <depth|normals>
106
+ --part <name> --out <map.json> [--padding LEFT,TOP,RIGHT,BOTTOM]
107
+ Convert little-endian float32/float64 C-order NumPy values to rig-parts-map/1.
108
+ Crop declared array padding before integer box pooling to the prepared PNG
109
+ size. Normalize signed XYZ normals after pooling. Print the depth-bind command.
110
+
103
111
  rig-parts depth-bind --map <numeric-map.json> --input <prepared.png> --part <name>
104
112
  Write <map>.binding.json with both file hashes; never overwrite a receipt.
105
113
  Attests the current files, not that inference used this input.
@@ -1260,6 +1268,7 @@ const TAKES = {
1260
1268
  'bust-landmarks': { valued: ['--from-act', '--parts', '--config', '--out'], switches: ['--write-config', '--help'] },
1261
1269
  'diff-components': { valued: ['--stack', '--painting', '--parts', '--figure', '--floor', '--threshold', '--out', '--verify'], switches: ['--owners', '--help'] },
1262
1270
  'diff-drafts': { valued: ['--left', '--right', '--out'], switches: ['--help'] },
1271
+ 'depth-map': { valued: ['--array', '--input', '--kind', '--part', '--out', '--padding'], switches: ['--help'] },
1263
1272
  'depth-bind': { valued: ['--map', '--input', '--part'], switches: ['--help'] },
1264
1273
  'depth-prepare': { valued: ['--parts', '--config', '--out'], switches: ['--help'] },
1265
1274
  'depth-apply': { valued: ['--parts', '--manifest', '--config', '--rig-config', '--out', '--groups'], switches: ['--help'] },
@@ -2950,6 +2959,60 @@ function cmdBustLandmarks(args: string[]): number {
2950
2959
  } catch (error) { return printRefusal(error); }
2951
2960
  }
2952
2961
 
2962
+ function readDepthMapInput(file: string): Uint8Array {
2963
+ try {
2964
+ if (!statSync(file).isFile()) throw new Error('found a nonregular file');
2965
+ return readFileSync(file);
2966
+ } catch (error) {
2967
+ return depthMapFail('DEPTH_INPUT_PRESENT', JSON.stringify(file),
2968
+ `read failed (${JSON.stringify(error instanceof Error ? error.message : String(error))}); required a readable regular file`);
2969
+ }
2970
+ }
2971
+
2972
+ function writeDepthMapFile(out: string, contents: string): void {
2973
+ try {
2974
+ const stage = mkdtempSync(join(realpathSync(dirname(out)), '.depth-map-'));
2975
+ try {
2976
+ const candidate = join(stage, 'map.json');
2977
+ writeFileSync(candidate, contents, { flag: 'wx' });
2978
+ // Publish complete bytes exclusively, including when two writers race for --out.
2979
+ linkSync(candidate, out);
2980
+ } finally {
2981
+ rmSync(stage, { recursive: true, force: true });
2982
+ }
2983
+ } catch (error) {
2984
+ const code = error !== null && typeof error === 'object' && 'code' in error ? String(error.code) : 'unknown error';
2985
+ return depthMapFail('DEPTH_OUTPUT_EMPTY', JSON.stringify(out),
2986
+ `map write failed (${code}); required an absent output file in a writable directory`);
2987
+ }
2988
+ }
2989
+
2990
+ function cmdDepthMap(args: string[]): number {
2991
+ const f = flags(args, 'depth-map', ['--array', '--input', '--kind', '--part', '--out']);
2992
+ if (typeof f === 'string') return usage(f);
2993
+ const array = f.get('--array')!, input = f.get('--input')!, part = f.get('--part')!, out = f.get('--out')!;
2994
+ try {
2995
+ // Match depth-bind's accepted part names so the printed command can use the same name.
2996
+ if (!part || part.startsWith('.') || /[\\/]/.test(part) || part.includes('\0')) {
2997
+ return depthMapFail('DEPTH_MAP_BINDING', 'depth-map --part',
2998
+ `found ${JSON.stringify(part)}; required a nonempty plain part filename accepted by depth-bind`);
2999
+ }
3000
+ const raw = readDepthMapInput(array), png = readDepthMapInput(input);
3001
+ let image: ReturnType<typeof decodePngBytes>;
3002
+ try { image = decodePngBytes(png, JSON.stringify(input)); }
3003
+ catch (error) {
3004
+ return depthMapFail('DEPTH_INPUT_PRESENT', JSON.stringify(input),
3005
+ `decode failed (${JSON.stringify(error instanceof Error ? error.message : String(error))}); required a decodable prepared PNG`);
3006
+ }
3007
+ const map = modelArrayMap(raw, image, f.get('--kind')!, f.get('--padding'), JSON.stringify(array));
3008
+ writeDepthMapFile(out, serializeModelArrayMap(map));
3009
+ const quote = (value: string): string => "'" + value.replaceAll("'", "'\"'\"'") + "'";
3010
+ console.log(`depth-map: wrote ${JSON.stringify(out)} (${map.width}x${map.height}, ${map.channels} channel(s))`);
3011
+ console.log(`rig-parts depth-bind --map ${quote(out)} --input ${quote(input)} --part ${quote(part)}`);
3012
+ return EXIT_OK;
3013
+ } catch (error) { return printRefusal(error); }
3014
+ }
3015
+
2953
3016
  function cmdDepthBind(args: string[]): number {
2954
3017
  const f = flags(args, 'depth-bind', ['--map', '--input', '--part']);
2955
3018
  if (typeof f === 'string') return usage(f);
@@ -2991,6 +3054,7 @@ function main(argv: string[]): number | Promise<number> {
2991
3054
  if (command === 'diff-drafts') return cmdDiffDrafts(rest);
2992
3055
  if (command === 'layers') return cmdLayers(rest);
2993
3056
  if (command === 'depth-prepare') return cmdDepthPrepare(rest);
3057
+ if (command === 'depth-map') return cmdDepthMap(rest);
2994
3058
  if (command === 'edited-part') return cmdEditedPart(rest);
2995
3059
  if (command === 'external-receipt') return cmdExternalReceipt(rest);
2996
3060
  if (command === 'bust-landmarks') return cmdBustLandmarks(rest);
package/docs/AUTHORING.md CHANGED
@@ -4045,14 +4045,18 @@ assemble/config step; this bounded draft names that refusal. Reassembly uses the
4045
4045
  CLI defaults `seam=near-white` and `project=core`, explicitly stated in its note
4046
4046
  because `parts.json` does not record the source command's selected rules.
4047
4047
 
4048
- The `note:` line derives `turn.body.unitDepths.<part>` as
4049
- `round4(bodyPivot + neckWorldMedian - firstBodySurfaceWorldMedian)`, using the
4050
- existing scalar sheet, declared `near` polarity and `zScale`. If the new source
4048
+ The draft writes the neck's world median to `turn.body.unitDepths.<part>`,
4049
+ using the existing scalar sheet, declared `near` polarity and `zScale`.
4050
+ The note also reports the projected depth the rig stage computes as
4051
+ `round4(bodyPivot + neckWorldMedian - firstBodySurfaceWorldMedian)`.
4052
+ If the new source
4051
4053
  has no sheet, only new opaque art overlapping the previous registered neck
4052
4054
  sheet is sampled. An absent sheet, empty overlap, missing body reference or
4053
4055
  missing pivot is refused by name; legacy `depth_median` is never converted to
4054
4056
  world units. Other proposal modes (`--keypoints`, `--compare`, `--grid-rule`,
4055
4057
  `--only-missing`) must run separately and are refused in this mode.
4058
+ For a config drafted before #1575, copy the neck world median from the original
4059
+ draft note into its body unit depth, or draft again from the same source.
4056
4060
 
4057
4061
  **The chest on such a config (issue #1436).** With `--bust-landmarks <file>` or
4058
4062
  `--no-bust "<reason>"` and without `--full` and `--head`, `propose --write-config`
@@ -7245,8 +7249,9 @@ and stay absent).
7245
7249
  | <a id="RIG_TURN_GRID_BUDGET"></a>`RIG_TURN_GRID_BUDGET` | a `"surface"` grid exceeds 2,400 triangles on one slot or 4,000 triangles across all `"surface"` slots | lower `config.turn.grid` / `config.turn.body.grid` `[cols, rows]` within the per-slot and total budgets |
7246
7250
  | <a id="RIG_TURN_HEAD_BONE"></a>`RIG_TURN_HEAD_BONE` | `buildRig` found no `"head"` (or body turn root) bone when emitting 2.5D turn carriers | declare `"head"` (or the body turn root bone) in `config.bones` |
7247
7251
  | <a id="RIG_TURN_BOUNDARY_DEPTH"></a>`RIG_TURN_BOUNDARY_DEPTH` | boundary names or sheets do not resolve; surfaces are not different, abutting without overlap in one group with common units; band is empty/outside/not boundary-reaching; declarations cycle; or grid support is missing | use exact existing parts, different abutting surfaces in one group with common near/zScale, a contained nonempty band reaching their boundary, acyclic declarations and the generated grid support |
7248
- | <a id="RIG_TURN_SHARED_DEPTH_SCALE"></a>`RIG_TURN_SHARED_DEPTH_SCALE` | `"surface"` parts bound to one head or body turn declare different `near` polarities or `zScale` values | use one shared `near` and `zScale` across all `"surface"` parts in the turn group |
7252
+ | <a id="RIG_TURN_SHARED_DEPTH_SCALE"></a>`RIG_TURN_SHARED_DEPTH_SCALE` | `"surface"` parts bound to one head or body turn declare different `near` polarities or `zScale` values | use one shared `near` and `zScale` across all `"surface"` parts in the turn group. The check runs separately for the head and body role sets, so if a surface belongs to both, use the larger required `zScale` in both groups. |
7249
7253
  | <a id="RIG_TURN_UNIT_DEPTH_REQUIRED"></a>`RIG_TURN_UNIT_DEPTH_REQUIRED` | a `"unit"` bone has neither a `unitDepths` entry nor a readable `"surface"` depth sheet | provide a `"surface"` depth sheet or an explicit `unitDepths.<part>` value |
7254
+ | <a id="RIG_TURN_BODY_UNIT_CARRIER"></a>`RIG_TURN_BODY_UNIT_CARRIER` | an explicit body unit depth has no movable carrier for its binding, or a shared carrier needs incompatible depths | bind the unit to a movable body branch and use independent branches for different depths |
7250
7255
  | <a id="RIG_TURN_UNIT_DEPTH_SUPPORT"></a>`RIG_TURN_UNIT_DEPTH_SUPPORT` | WARN only: an implicit unit depth sample is outside the source surface pixel-index bounds or its sampled art alpha is below 255 | author an explicit calibrated `unitDepths.<part>` value when this cross-part extrapolation is unintended; existing scalar sampling and refusal behavior are retained |
7251
7256
  | <a id="RIG_TURN_EAR_DEPTH_BEHIND_CHEEK"></a>`RIG_TURN_EAR_DEPTH_BEHIND_CHEEK` | an ear bone in `config.turn.roles` has a calibrated depth at or in front of the cheek surface depth | place the ear behind the cheek surface (for example via `config.turn.unitDepths`) |
7252
7257
 
@@ -9972,20 +9977,36 @@ re-run depth for these inputs, then call
9972
9977
  `rig-parts depth-bind --map <numeric-map.json> --input <prepared.png> --part <name>`. Malformed
9973
9978
  present receipts also refuse. Symlinked receipts, including dangling links, are
9974
9979
  refused; a regular file is required. Preparing again never rebinds a map.
9975
- Under the compatibility policy dated **2026-11-16**, a missing receipt preserves
9976
- legacy output bytes and exits, with one `DEPTH_MAP_BINDING_ABSENT` WARN per
9977
- selected map on stderr. This is unverified inference-input identity, not a
9980
+ Under the compatibility policy dated **2026-11-16**, an otherwise valid recipe
9981
+ can use a map with a missing receipt. This adds one `DEPTH_MAP_BINDING_ABSENT`
9982
+ WARN per selected map on stderr. This is unverified inference-input identity, not a
9978
9983
  binding pass. The provider flow calls the writer when producing a map. The writer binds these
9979
9984
  files at invocation; it cannot prove the map was inferred from that input.
9980
9985
  Parts does not run inference or invent provenance.
9981
9986
 
9982
- Apply computes `u=(raw-median(raw))/(p95-p5)` inside original alpha >=128,
9983
- using linear percentiles, then `Z=median+relief*u`. A flat map requires explicit
9984
- relief 0. Encode `Z/zScale` for near white, `1-Z/zScale` for near black, clip to
9985
- [0,1], and round to the nearest 8-bit level with even ties. Extend every
9986
- non-support pixel with the Euclidean nearest support value, with row-major ties.
9987
+ Apply computes `u=(raw-median(raw))/(p95-p5)` on original part pixels with
9988
+ alpha >= 128, using linear percentiles, then `z=median+relief*u`. A flat map
9989
+ requires explicit relief 0 and uses a zero relief offset. Every supported pixel
9990
+ must satisfy `0 < z < zScale` before encoding. `DEPTH_APPLY_CLIPPED` refuses
9991
+ any nonzero clip fraction before writing outputs. The fraction counts supported
9992
+ pixels with `z <= 0` or `z >= zScale` divided by all supported pixels.
9993
+
9994
+ For upper clipping, the refusal gives the smallest binary64 group `zScale`
9995
+ strictly above the maximum original supported depth in the group. For each part
9996
+ with lower clipping, it gives the minimum authored `median`, the next binary64
9997
+ value above the maximum of `-(relief*u)` across that part's supported pixels.
9998
+ It also gives the difference between that target and the previous authored
9999
+ median in rig pixels. Both remedies are reported when both boundaries clip.
10000
+ If no finite scale clears the upper boundary, revise the median or relief.
10001
+ If no finite median clears the lower boundary, reduce the relief.
10002
+ Recompute the group scale if changing medians changes the maximum supported
10003
+ depth, then prepare the revised recipe again.
10004
+
10005
+ Encode `z/zScale` for near white or `1-z/zScale` for near black and round to
10006
+ the nearest 8-bit level with even ties. Extend every non-support pixel with the
10007
+ Euclidean nearest support value, with row-major ties.
9987
10008
  The resulting opaque gray sheet carries no background cliff. The report names
9988
- levels, clip fraction (Z <=0 or >=zScale on support), declared relief in rig
10009
+ levels, clip fraction (zero on success), declared relief in rig
9989
10010
  pixels, group pivot, sign, raw median/p5/p95 and source/input/map/sheet hashes.
9990
10011
  It reports measurements, not a depth-quality pass mark. `rig` still runs Core's
9991
10012
  gate; apply writes parts and configuration, never a skeleton or a gate verdict.
@@ -10033,10 +10054,9 @@ same medians, group pivot and `zScale`; only the declared relief changes.
10033
10054
  Read each named report row's `relief`, `zScale` and `clipFraction` before
10034
10055
  judging its render. The clipping denominator is every original part pixel
10035
10056
  with alpha >=128, including boundary support, never the padded input area.
10036
- A low clipped fraction does not establish shape quality. Inspect setup,
10037
- both yaw endpoints and their difference at native scale, then enlarge the
10038
- same pixels with nearest-neighbour sampling. Neither clipping nor agreement
10039
- with a reference map substitutes for that inspection.
10057
+ Use those readings to confirm the calibration. To judge shape quality, inspect
10058
+ setup, both yaw endpoints and their difference at native scale, then enlarge
10059
+ the same pixels with nearest-neighbour sampling.
10040
10060
 
10041
10061
  The owner's preference for per-part volume is subjective provenance, not an
10042
10062
  automated quality conclusion. Model licence posture remains the owner's choice.
@@ -10052,17 +10072,25 @@ by `rig`, so their output requires no alternate compiler or dependency pin.
10052
10072
  | --- | --- | --- |
10053
10073
  | <a id="DEPTH_RECIPE"></a>`DEPTH_RECIPE` | unknown, absent or wrongly typed recipe field, group, source or frame | use the documented explicit recipe schema; no guessed field |
10054
10074
  | <a id="DEPTH_RECIPE_NUMBER"></a>`DEPTH_RECIPE_NUMBER` | missing/nonfinite median, relief, near-scale pivot or prepare number; invalid range/integer | declare every numeric field in its documented units and range |
10055
- | <a id="DEPTH_INPUT_PRESENT"></a>`DEPTH_INPUT_PRESENT` | declared JSON input missing or not a file | restore the named file |
10075
+ | <a id="DEPTH_INPUT_PRESENT"></a>`DEPTH_INPUT_PRESENT` | declared input missing or not a file, or `depth-map` input unreadable or prepared PNG undecodable | restore the named readable input file in its expected format |
10056
10076
  | <a id="DEPTH_INPUT_JSON"></a>`DEPTH_INPUT_JSON` | malformed numeric or configuration JSON | write valid finite JSON |
10057
10077
  | <a id="DEPTH_PART_RESOLVES"></a>`DEPTH_PART_RESOLVES` | selected or cleared name absent from parts.json | use the assembled part name |
10058
- | <a id="DEPTH_OUTPUT_EMPTY"></a>`DEPTH_OUTPUT_EMPTY` | nonempty output or output containing an input | choose a separate absent or empty directory |
10059
- | <a id="DEPTH_MAP_BINDING"></a>`DEPTH_MAP_BINDING` | malformed present map receipt, wrong part, map hash or inference-input hash | re-run depth for these inputs, then `rig-parts depth-bind --map <numeric-map.json> --input <prepared.png> --part <name>` |
10060
- | <a id="DEPTH_MAP_BINDING_ABSENT"></a>`DEPTH_MAP_BINDING_ABSENT` | WARN only: no receipt, compatibility policy dated 2026-11-16 | legacy behavior is retained; re-run depth for these inputs, then `rig-parts depth-bind --map <numeric-map.json> --input <prepared.png> --part <name>` |
10078
+ | <a id="DEPTH_OUTPUT_EMPTY"></a>`DEPTH_OUTPUT_EMPTY` | nonempty output directory or output containing an input, or `depth-map` cannot create its output exclusively | choose a separate absent or empty output directory, or for `depth-map` an absent output file in a writable directory |
10079
+ | <a id="DEPTH_MAP_BINDING"></a>`DEPTH_MAP_BINDING` | invalid part name for `depth-map` or `depth-bind`, or malformed present map receipt, wrong part, map hash or inference-input hash | use a nonempty plain part filename for the command, or re-run depth for the affected receipt and call `rig-parts depth-bind --map <numeric-map.json> --input <prepared.png> --part <name>` |
10080
+ | <a id="DEPTH_MAP_BINDING_ABSENT"></a>`DEPTH_MAP_BINDING_ABSENT` | WARN only: no receipt, compatibility policy dated 2026-11-16 | re-run depth for these inputs, then `rig-parts depth-bind --map <numeric-map.json> --input <prepared.png> --part <name>` |
10061
10081
  | <a id="DEPTH_INPUT_BINDING"></a>`DEPTH_INPUT_BINDING` | changed recipe, art, part record, crop, padding or inference PNG | prepare again for these exact inputs |
10082
+ | <a id="DEPTH_ARRAY_FORMAT"></a>`DEPTH_ARRAY_FORMAT` | unsupported NumPy version, malformed header, wrong dtype or order, or payload byte count does not match the header | export `.npy` v1.0, v2.0 or v3.0 as little-endian float32 or float64 in C order |
10083
+ | <a id="DEPTH_ARRAY_KIND"></a>`DEPTH_ARRAY_KIND` | unknown `depth-map --kind` | declare `depth` or `normals` |
10084
+ | <a id="DEPTH_ARRAY_SHAPE"></a>`DEPTH_ARRAY_SHAPE` | rank, dimension or channel count does not match the declared kind | export `(H,W)` or `(H,W,1)` for depth and `(H,W,3)` for normals, with positive safe integer dimensions |
10085
+ | <a id="DEPTH_ARRAY_PADDING"></a>`DEPTH_ARRAY_PADDING` | malformed padding or padding removes the entire extent on either axis | declare four nonnegative safe integers in left, top, right, bottom order that leave a nonempty crop |
10086
+ | <a id="DEPTH_ARRAY_SIZE"></a>`DEPTH_ARRAY_SIZE` | cropped dimensions are not positive integer multiples of the prepared PNG dimensions on both axes | check the input PNG and declare the raw array's actual padding, or re-export at a supported size |
10087
+ | <a id="DEPTH_ARRAY_NONFINITE"></a>`DEPTH_ARRAY_NONFINITE` | retained raw depth pixel contains `NaN` or an infinity | export finite depth values at the named raw pixel |
10088
+ | <a id="DEPTH_ARRAY_NORMAL"></a>`DEPTH_ARRAY_NORMAL` | retained raw normal is zero or nonfinite, or a pooled normal cancels to zero | export finite nonzero signed XYZ normals in image axes and inspect the named raw or output pixel |
10062
10089
  | <a id="DEPTH_MAP_FORMAT"></a>`DEPTH_MAP_FORMAT` | wrong numeric schema, channels, shape, count, unknown field or nonfinite element | provide the declared float JSON map, not a preview |
10063
10090
  | <a id="DEPTH_MAP_SIZE"></a>`DEPTH_MAP_SIZE` | map dimensions differ from its explicit frame | use the registered part, enlarged art or padded input grid |
10064
10091
  | <a id="DEPTH_MAP_SUPPORT"></a>`DEPTH_MAP_SUPPORT` | no alpha>=128 support | provide a supported part |
10065
10092
  | <a id="DEPTH_MAP_SPREAD"></a>`DEPTH_MAP_SPREAD` | p5=p95 with nonzero relief | supply a nonflat map or declare relief 0 |
10093
+ | <a id="DEPTH_APPLY_CLIPPED"></a>`DEPTH_APPLY_CLIPPED` | a pixel with original alpha >= 128 has pre-encoding depth `z <= 0` or `z >= zScale` | use the reported minimum median for each low-clipped part and the reported minimum group scale for upper clipping. The rig checks the head and body role sets separately, so if a surface belongs to both, use the larger required `zScale` in both groups. Recompute the group scale after median edits if the maximum changes, then prepare again. |
10066
10094
  | <a id="DEPTH_NORMAL_ISLANDS"></a>`DEPTH_NORMAL_ISLANDS` | zero/multiple connected components at native or integration resolution | scalar source, or a larger registered normal input that preserves one island |
10067
10095
  | <a id="DEPTH_NORMAL_VECTOR"></a>`DEPTH_NORMAL_VECTOR` | a sampled support normal is zero | provide nonzero signed XYZ normals |
10068
10096
  | <a id="DEPTH_NORMAL_CONVEXITY"></a>`DEPTH_NORMAL_CONVEXITY` | core/rim or its convexity sign is unresolved | larger closed convex mask or scalar source |
@@ -10093,6 +10121,15 @@ For each carried unit bone, the existing producer resolves depth in this order:
10093
10121
  landmarks or a mesh sampling position. No documented configuration is
10094
10122
  provided here to bypass primary sampling and select the own sheet instead.
10095
10123
 
10124
+ An explicit body unit value is the world depth `z`. At body yaw angle `a`,
10125
+ its rigid horizontal displacement is `-(pivot + z - zRef) * sin(a)`, using
10126
+ the same primary surface reference `zRef` as the body's surface projection.
10127
+ A region bound to a torso root gets its own mover under `bodyshift`; a
10128
+ region farther down a body branch uses the branch directly under
10129
+ `bodyshift`. Each blink-still piece resolves its binding independently.
10130
+ When the binding cannot be moved at the declared depth, the rig stage
10131
+ refuses with [`RIG_TURN_BODY_UNIT_CARRIER`](#RIG_TURN_BODY_UNIT_CARRIER).
10132
+
10096
10133
  Outside or nonopaque primary support produces
10097
10134
  [`RIG_TURN_UNIT_DEPTH_SUPPORT`](#RIG_TURN_UNIT_DEPTH_SUPPORT), retains the
10098
10135
  extended primary sample, and does not select the own sheet. Removing all
package/docs/DEPTH.md CHANGED
@@ -136,14 +136,16 @@ belong to these parts and nothing moved in between.
136
136
 
137
137
  ### 2. Run your depth model
138
138
 
139
- This is your step, with your model, on your machine or wherever you run it.
140
- Read `inference/<part>.png`, write one numeric map per part as JSON
141
- (`rig-parts-map/1`: width, height, channels, and the raw floating-point values
142
- row by row), the same size as the image you read. `"frame": "input"` in the
143
- recipe is what says so, and the manifest binds it, so choose it before you
144
- prepare. Scalar depth is one channel; the face's normals are three signed
145
- channels in image axes. Save the model's actual numbers — a greyscale preview
146
- has already thrown away the normalisation the next stage needs.
139
+ Run your model on `inference/<part>.png` and save its numeric output. The
140
+ recipe above declares `"frame": "input"`, so each JSON map must match the
141
+ size of the prepared PNG, including its grey margin. Choose the frame before
142
+ preparing because the manifest binds the recipe.
143
+
144
+ You can write the JSON directly as before. Use `rig-parts-map/1` with `width`,
145
+ `height`, `channels`, and a flat `data` array of finite floating-point values
146
+ in row order. Scalar depth has one channel and normals have three signed XYZ
147
+ channels in image axes (X right, Y down). A greyscale or RGB preview loses
148
+ the numeric values needed by the next stage.
147
149
 
148
150
  What we used: Depth Anything for the parts (V2 Large, and Depth Anything 3's
149
151
  monocular model), and Lotus's normal model for the face. Any model that
@@ -152,6 +154,35 @@ which one you ran. Model licences are the model's own and are not this
152
154
  package's to restate — the site's [licensing page](https://rig-c.org/docs/licensing/)
153
155
  says where each kind of term sits.
154
156
 
157
+ #### Convert a NumPy array
158
+
159
+ If the model exports a NumPy array, convert it to an input-frame map at the
160
+ recipe's map path. Use the same prepared PNG you supplied to the model:
161
+
162
+ ```sh
163
+ rig-parts depth-map --array face.npy --input inference/face.png --kind normals --part face --out face.json
164
+ ```
165
+
166
+ The array must be a C-order `.npy` file (format 1.0, 2.0, or 3.0) with
167
+ little-endian `float32` or `float64` values. Use `--kind depth` for `(H, W)`
168
+ or `(H, W, 1)` and `--kind normals` for `(H, W, 3)` signed XYZ in image axes.
169
+
170
+ If the model added padding to its output array, pass
171
+ `--padding LEFT,TOP,RIGHT,BOTTOM` in array pixels. The values are nonnegative
172
+ integers and default to zero. Keep the prepared PNG's own grey margin in the
173
+ map. After cropping the declared padding, each array dimension must be a
174
+ positive integer multiple of the corresponding PNG dimension. Each output
175
+ pixel is the mean of its corresponding rectangular block, with independent
176
+ horizontal and vertical factors. For normals, average each component and
177
+ normalize the resulting vector to unit length. A retained nonfinite sample,
178
+ a retained zero normal, or a pooled zero normal is refused with its pixel
179
+ coordinates.
180
+
181
+ `--out` must name a new file in an existing writable directory. `depth-map`
182
+ writes only the `rig-parts-map/1` JSON and prints the next `depth-bind`
183
+ command with the map path, prepared PNG path and part name quoted for a POSIX
184
+ shell.
185
+
155
186
  ### 3. Bind every map to its prepared input
156
187
 
157
188
  After the model writes each numeric map, bind those exact bytes to the input
@@ -169,8 +200,8 @@ it does not prove the model inferred one from the other. Use each recipe map
169
200
  path and its matching prepared image, retain the receipts with the maps, then
170
201
  apply them. Existing receipts are never overwritten. If a map changes, retain
171
202
  the old map and receipt and bind the new map at a new path; update the recipe
172
- and prepare again so its manifest binds that recipe. `depth-apply` refuses
173
- missing, stale or mismatched bindings before emission.
203
+ and prepare again so its manifest binds that recipe. `depth-apply` warns when
204
+ a binding is absent and refuses stale or mismatched bindings before emission.
174
205
 
175
206
  ### 4. Apply the maps as depth sheets
176
207
 
@@ -189,12 +220,34 @@ depth-apply: face levels=30 clip=0 reliefRigPixels=10 sign=1
189
220
  depth-apply: wrote registered parts, config.json and depth-report.json; run rig for the core gate
190
221
  ```
191
222
 
192
- `levels` is how many distinct grey levels the sheet uses, `clip` the share of
193
- pixels that fell outside the group's scale (keep it at or near zero), and
194
- `sign` the convexity sign the face integration chose. `mapped/` is a complete
195
- assembled directory: the art unchanged, a `<part>_depth.png` beside each mapped
196
- part, `parts.json` pointing at them, a copy of your config with the group
197
- pivots written in, and `depth-report.json` with every number and hash. Nothing
223
+ `levels` is how many distinct grey levels the sheet uses, and `sign` is the
224
+ convexity sign the face integration chose. `clip` (`clipFraction` in
225
+ `depth-report.json`) is the share of original part pixels with alpha >= 128
226
+ whose depth is at or beyond either boundary before encoding. Every supported
227
+ depth must satisfy `0 < z < zScale`. A nonzero fraction triggers
228
+ `DEPTH_APPLY_CLIPPED` before any output is written.
229
+
230
+ For clipping at the upper boundary, the refusal gives the smallest binary64
231
+ group `zScale` strictly greater than the largest original supported depth in
232
+ the group. For each part that clips at the lower boundary, it gives the
233
+ minimum authored `median` and how far it is above the previous median in rig
234
+ pixels. The minimum is the next binary64 value above the greatest negated
235
+ relief offset among that part's supported pixels. A group that clips at both
236
+ boundaries gets both remedies across its affected parts. If a required value
237
+ has no finite binary64 representation, revise the calibration as directed by
238
+ the refusal. A median rise can increase the group's maximum depth, so
239
+ recompute the required group scale after changing the median. After
240
+ editing the recipe, run `depth-prepare` again to bind the revised recipe, then
241
+ rerun `depth-apply` with the matching manifest.
242
+
243
+ The bound covers the newly mapped parts in each applied recipe group. At the
244
+ rig stage, each turn group checks its member sheets for one scale and polarity.
245
+ A surface shared by both turn groups must satisfy both groups' checks.
246
+
247
+ On success, `mapped/` is a complete assembled directory with the original
248
+ art, a `<part>_depth.png` beside each mapped part, `parts.json` pointing at
249
+ the sheets, a copy of your config with the group pivots written in, and
250
+ `depth-report.json` with every number and hash. Nothing
198
251
  in `work/rig` or your original config is touched. Any mismatch — a recipe edited
199
252
  after prepare, a part that moved, a map of the wrong size, a part your
200
253
  `turn.roles` does not name — is refused by name before a byte is written.
@@ -272,14 +325,13 @@ judge from a sweep or from the `turn` animation played straight through. Put
272
325
  the build in a page where the pointer drives both dials; the adapters' look
273
326
  example shows [how to bind a pointer to declared sliders](https://github.com/rig-c/adapters/blob/main/examples/look/README.md).
274
327
  Separately, render the setup pose and both yaw endpoints and look at their
275
- difference at native scale: that is where a tear, a clipped sheet or a feature
276
- sliding off the face shows, and it is a check for defects, not for volume.
328
+ difference at native scale to find tears or features sliding off the face.
277
329
 
278
330
  **Read the report before you read the render.** `depth-report.json` names each
279
- part's relief, scale and clip fraction. A high clip fraction means the declared
280
- numbers do not fit the group's scale; fix the recipe, not the render. Small
281
- units — eyes, mouth, brows, ears — usually look best following the face surface
282
- rather than carrying a sheet of their own: list them under `clear`, or give
331
+ part's relief, scale and clip fraction. A zero clip fraction confirms the
332
+ supported depths fit the declared range. Inspect the render for shape quality.
333
+ Small units — eyes, mouth, brows, ears — usually look best following the face
334
+ surface rather than carrying a sheet of their own: list them under `clear`, or give
283
335
  them an explicit depth under the group's `unitDepths`. Which depth a unit ends
284
336
  up using is spelled out in
285
337
  [Unit depth precedence](AUTHORING.md#unit-depth-precedence).
package/docs/STABILITY.md CHANGED
@@ -579,6 +579,7 @@ and do not certify visibility. See the
579
579
  | `diff-components` | `--stack`, `--painting`, `--parts`, `--floor`; optional `--threshold`, `--figure`, `--owners`, `--help` (`-h`); exactly one of `--out`, `--verify` (issues #1005, #1291; exhaustive native error inventory, `rig-parts-diff-components/1` by default and `rig-parts-diff-components/2` with `--owners`, and byte-bound reader for both) |
580
580
  | `diff-drafts` | `--left`, `--right`, `--out`; optional `--help` (`-h`) (issue #1369; draft-to-draft assemble comparison, `rig-parts-draft-diff/1`) |
581
581
  | `depth-prepare` | `--parts`, `--config`, `--out`; optional `--help` (`-h`) (issue #897; separate numeric-depth recipe) |
582
+ | `depth-map` | `--array`, `--input`, `--kind` (`depth` or `normals`), `--part`, `--out`; optional `--padding` (`LEFT,TOP,RIGHT,BOTTOM`), `--help` (`-h`) (issue #1573; NumPy array to input-frame numeric map) |
582
583
  | `depth-bind` | `--map`, `--input`, `--part`; optional `--help` (`-h`) (issue #1284; exclusive receipt creation from current file bytes) |
583
584
  | `depth-apply` | `--parts`, `--manifest`, `--config`, `--rig-config`, `--out`; optional `--groups` (a comma-separated list of the recipe's groups to apply, issue #1449), `--help` (`-h`) (issue #897; original character config is read-only) |
584
585
  | `layers` | one positional path: a wrapper directory, a `layers.json` or a `.psd` (a file literally named `-h` is reached as `./-h`); with it, optional `--export` (a directory to write the wrapper form into, issue #359); or `--template` with `--canvas` and no path; or a positional head run with `--full`, `--source`, `--config` together for `PLAN_HEAD_GARMENT_OVERLAP` (issue #826); or `--help` (`-h`) |
@@ -790,7 +791,7 @@ part name, `[i]` an entry of a list):
790
791
  - **turn.unitDepths.&lt;part&gt;** — a calibrated world depth in rig pixels (issue #763)
791
792
  - **turn.body**, when an object — required: `roles`, `pivot` (when `turn.pivot` is absent); optional: `bone`, `slider`, `counter`, `grid`, `unitDepths`, `boundaryDepths` (issue #787)
792
793
  - **turn.body.roles.&lt;part&gt;** — `"surface"`, `"unit"` or `"rear"` (issue #787)
793
- - **turn.body.unitDepths.&lt;part&gt;** — a calibrated world depth in rig pixels (issue #787)
794
+ - **turn.body.unitDepths.&lt;part&gt;** — a calibrated world depth in rig pixels; body yaw uses `-(pivot + z - zRef) * sin(a)` ([Unit depth precedence](AUTHORING.md#unit-depth-precedence))
794
795
  - **turn.deform.&lt;key&gt;** — a per-degree fraction or coupling share (FACE_DEFORM_FRACTIONS, issue #436)
795
796
  - **turn.band**, when an object — optional: `yaw`, `pitch` (issue #472)
796
797
  - **turn.surface**, when an object — optional: `radius` (issue #479)
@@ -2246,9 +2247,40 @@ field is absent without the flag, so those reports keep their bytes, and
2246
2247
  `relief` is an explicit rig-pixel value, not an implicit width multiplier.
2247
2248
  Part-width and head-referenced calibrations are authored recipe choices;
2248
2249
  changing a calibration requires preparing its recipe again. Compare the same
2249
- provider maps and preserve their provenance. Each report row names the part,
2250
- declared relief, group `zScale` and clipping over original alpha>=128 support;
2251
- it remains a measurement rather than a shape-quality gate.
2250
+ provider maps and preserve their provenance. The additive `DEPTH_APPLY_CLIPPED`
2251
+ refusal applies before any output write, including for previously accepted
2252
+ clipped recipes, regardless of map binding receipt presence. Every original
2253
+ part pixel with alpha >= 128 must satisfy
2254
+ `0 < z < zScale` before encoding. The clip fraction divides the number of
2255
+ supported pixels at or beyond either boundary by the total supported pixel
2256
+ count.
2257
+
2258
+ For upper clipping the refusal gives the smallest binary64 group `zScale`
2259
+ strictly above the maximum original supported depth in the group. For each
2260
+ part with lower clipping it gives the minimum authored median (the next
2261
+ binary64 value above the maximum negated relief offset over that part's
2262
+ support) and its difference from the previous authored median. When both
2263
+ boundaries clip, the refusal includes both remedies. If a required value has
2264
+ no finite binary64 representation, the refusal directs the author to revise
2265
+ the calibration. A median adjustment may require recomputing the group scale.
2266
+
2267
+ `rig-parts-depth-report/1` keeps its existing keys. Each successful row names
2268
+ the part, declared relief, group `zScale` and a zero `clipFraction` over the
2269
+ original alpha >= 128 support. Shape quality is assessed separately.
2270
+
2271
+ `depth-map` (issue #1573) is an additive minor-version command. It accepts
2272
+ C-order NumPy `.npy` 1.0, 2.0, and 3.0 arrays with little-endian `float32` or
2273
+ `float64` data. Depth accepts `(H, W)` or `(H, W, 1)`. Normals accept
2274
+ `(H, W, 3)` with signed XYZ components in image axes (X right, Y down).
2275
+ Declared array-edge padding is cropped before mean pooling with independent
2276
+ positive integral X and Y factors derived from the prepared PNG dimensions.
2277
+ Pooled normals are normalized to unit length. The command refuses retained
2278
+ nonfinite samples, retained zero normals, and pooled zero normals by pixel.
2279
+ `--out` must name a new file in an existing writable directory. The command
2280
+ writes only the `rig-parts-map/1` JSON at the PNG dimensions and prints the
2281
+ next `depth-bind` command with its arguments quoted for a POSIX shell.
2282
+ Hand-authored `rig-parts-map/1` maps continue through
2283
+ the same bind and apply stages. See [Convert a NumPy array](DEPTH.md#convert-a-numpy-array).
2252
2284
 
2253
2285
  The requirements file's `fps` becomes optional when no declared measurement
2254
2286
  reads that rate (issue #965, additive for readers). Measurements in
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "rig-parts",
3
- "version": "2.58.0",
3
+ "version": "2.59.0",
4
4
  "description": "AI-authored 2D character parts from one anime painting and its See-through layer decomposition: measured parts, weighted-mesh rig specs, verified through rig-c before anything is written. A CLI for agents that cannot see the image.",
5
5
  "type": "module",
6
6
  "exports": {
@@ -75,7 +75,7 @@
75
75
  },
76
76
  "dependencies": {
77
77
  "ag-psd": "^31.0.2",
78
- "@rig-c/core": "3.9.1"
78
+ "@rig-c/core": "3.9.2"
79
79
  },
80
80
  "devDependencies": {
81
81
  "@esotericsoftware/spine-core": "4.3.13",
package/src/depthmaps.ts CHANGED
@@ -149,7 +149,9 @@ export function integrateNormals(map: NumericMap, art: Raster, at: string): Norm
149
149
  }
150
150
 
151
151
  export interface MapSheetReading { levels: number; clipFraction: number; reliefRigPixels: number; rawMedian: number; rawP5: number; rawP95: number }
152
- export function mapToSheet(data: ArrayLike<number>, art: Raster, median: number, relief: number, near: 'black' | 'white', zScale: number, at: string): { sheet: Raster; reading: MapSheetReading } {
152
+ export function mapToSheet(data: ArrayLike<number>, art: Raster, median: number, relief: number, near: 'black' | 'white', zScale: number, at: string): {
153
+ sheet: Raster; reading: MapSheetReading; maxZ: number; minOffset: number; clipsLow: boolean;
154
+ } {
153
155
  const support = alphaSupport(art), values: number[] = [];
154
156
  for (let i = 0; i < support.length; i++) if (support[i]) values.push(data[i]);
155
157
  if (!values.length) return depthMapFail('DEPTH_MAP_SUPPORT', at, 'has no alpha>=128 pixels; a part with declared support is required');
@@ -158,13 +160,21 @@ export function mapToSheet(data: ArrayLike<number>, art: Raster, median: number,
158
160
  if (![med, lo, hi, spread].every(Number.isFinite)) return depthMapFail('DEPTH_MAP_FORMAT', at, 'normalization overflows finite arithmetic; provide finite representable median and percentile spread');
159
161
  if (spread === 0 && relief !== 0) return depthMapFail('DEPTH_MAP_SPREAD', at, `p5=p95=${lo} but relief=${relief}; a nonflat map or explicit relief 0 is required`);
160
162
  const sheet = newRaster(art.width, art.height), seeds = newRaster(art.width, art.height), levels = new Set<number>(); let clipped = 0;
163
+ let maxZ = -Infinity, minOffset = Infinity, clipsLow = false;
161
164
  for (let i = 0; i < support.length; i++) {
162
- const z = median + relief * (spread === 0 ? 0 : (data[i] - med) / spread), unit = Math.max(0, Math.min(1, near === 'white' ? z / zScale : 1 - z / zScale));
165
+ const offset = relief * (spread === 0 ? 0 : (data[i] - med) / spread);
166
+ const z = median + offset, unit = Math.max(0, Math.min(1, near === 'white' ? z / zScale : 1 - z / zScale));
163
167
  if (!Number.isFinite(z) && support[i]) return depthMapFail('DEPTH_MAP_FORMAT', at, `world depth at support pixel ${i} overflows; declare representable median/relief and raw numbers`);
164
168
  // Uint8ClampedArray implements ties-to-even, as numpy.round does.
165
169
  sheet.data[i * 4] = unit * 255; sheet.data[i * 4 + 1] = sheet.data[i * 4 + 2] = sheet.data[i * 4]; sheet.data[i * 4 + 3] = 255;
166
170
  seeds.data[i * 4 + 3] = support[i] ? 255 : 0;
167
- if (support[i]) { levels.add(sheet.data[i * 4]); if (z <= 0 || z >= zScale) clipped++; }
171
+ if (support[i]) {
172
+ levels.add(sheet.data[i * 4]);
173
+ maxZ = Math.max(maxZ, z);
174
+ minOffset = Math.min(minOffset, offset);
175
+ if (z <= 0) clipsLow = true;
176
+ if (z <= 0 || z >= zScale) clipped++;
177
+ }
168
178
  }
169
- return { sheet: extendDepthSilhouette(sheet, seeds), reading: { levels: levels.size, clipFraction: clipped / values.length, reliefRigPixels: relief, rawMedian: med, rawP5: lo, rawP95: hi } };
179
+ return { sheet: extendDepthSilhouette(sheet, seeds), reading: { levels: levels.size, clipFraction: clipped / values.length, reliefRigPixels: relief, rawMedian: med, rawP5: lo, rawP95: hi }, maxZ, minOffset, clipsLow };
170
180
  }
@@ -28,6 +28,14 @@ interface PreparedPart { part: string; crop: number[]; sourceSha256: string; inp
28
28
  interface Prepared { spec: 'rig-parts-depth-inputs/1'; partsSha256: string; recipeSha256: string; background: number; alpha: number; parts: PreparedPart[] }
29
29
  const hash = (bytes: Uint8Array | string): string => createHash('sha256').update(bytes).digest('hex');
30
30
  const text = (raw: unknown): string => JSON.stringify(raw, null, 2) + '\n';
31
+ /** The next binary64 value above a finite, nonnegative depth bound. */
32
+ function aboveDepthBound(bound: number): number {
33
+ if (bound === 0) return Number.MIN_VALUE;
34
+ const bits = new DataView(new ArrayBuffer(8));
35
+ bits.setFloat64(0, bound);
36
+ bits.setBigUint64(0, bits.getBigUint64(0) + 1n);
37
+ return bits.getFloat64(0);
38
+ }
31
39
  function object(raw: unknown, at: string): Obj {
32
40
  if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) return fail('DEPTH_RECIPE', at, 'requires an object with the documented fields');
33
41
  return raw as Obj;
@@ -272,6 +280,8 @@ export function applyDepth(input: { parts: string; manifest: string; config: str
272
280
  refuseStaleAssembly(outConfig, file, relocatedConfig);
273
281
  const warnings: string[] = [];
274
282
  const writes = new Map<string, Uint8Array>(), rows: Obj[] = [], recs = rawParts.parts as Obj[];
283
+ const groupMaxZ = new Map<string, number>();
284
+ const clipped: { name: string; group: string; fraction: number; clipsHigh: boolean; median: number; minMedian?: number }[] = [];
275
285
  // Retain auxiliary art (including alternate sets) and diagnostics byte-for-byte.
276
286
  // Symlink inputs would obscure ownership and can escape this assembled directory.
277
287
  const retained = new Map<string, Uint8Array>();
@@ -314,13 +324,32 @@ export function applyDepth(input: { parts: string; manifest: string; config: str
314
324
  if (map.channels !== 1) fail('DEPTH_MAP_FORMAT', name, 'depth requires one floating-point channel');
315
325
  values = floatBox(map.data, map.width, map.height, art.width, art.height);
316
326
  }
317
- const { sheet, reading } = mapToSheet(values, art, declaration.median, declaration.relief, g.near, g.zScale, name), image = `${name}_depth.png`, sheetBytes = encodePngBytes(sheet);
327
+ const { sheet, reading, maxZ, minOffset, clipsLow } = mapToSheet(values, art, declaration.median, declaration.relief, g.near, g.zScale, name);
328
+ groupMaxZ.set(declaration.group, Math.max(groupMaxZ.get(declaration.group) ?? -Infinity, maxZ));
329
+ if (reading.clipFraction > 0) {
330
+ clipped.push({ name, group: declaration.group, fraction: reading.clipFraction, clipsHigh: maxZ >= g.zScale, median: declaration.median,
331
+ ...(clipsLow ? { minMedian: aboveDepthBound(-minOffset) } : {}) });
332
+ continue;
333
+ }
334
+ const image = `${name}_depth.png`, sheetBytes = encodePngBytes(sheet);
318
335
  if (file.parts.some(p => `${p.name}.png` === image)) fail('DEPTH_GROUP_BINDING', name, `sheet filename ${image} collides with artwork; use noncolliding part names`);
319
336
  writes.set(image, sheetBytes);
320
337
  if (p.depth !== undefined) retained.delete(depthImageReference(p.depth).path);
321
338
  rec.depth = { image, near: g.near, zScale: g.zScale, sources: [{ from: p.from, image: basename(declaration.map), sha256: hash(mapBytes), crop: [0, 0, art.width, art.height], reading: depthReading(sheet, art, null) }] };
322
339
  rows.push({ part: name, group: declaration.group, source: declaration.source, frame: declaration.frame, sourceSha256: prepared.sourceSha256, mapSha256: hash(mapBytes), inputSha256: prepared.inputSha256, sheetSha256: hash(sheetBytes), median: declaration.median, relief: declaration.relief, near: g.near, zScale: g.zScale, pivot: g.pivot, ...reading, sign: normal?.sign ?? 1, ...(normal === undefined ? {} : { integration: { stride: 2, iterations: normal.iterations, residual: normal.residual, coreMinusRim: normal.coreMinusRim, maxIterations: 3000, atol: 1e-6, btol: 1e-6 } }) });
323
340
  }
341
+ if (clipped.length) throw new PartsError(clipped.map(({ name, group, fraction, clipsHigh, median, minMedian }) => {
342
+ const details = [`clip=${fraction} in group "${group}"`];
343
+ if (clipsHigh) {
344
+ const maxZ = groupMaxZ.get(group)!;
345
+ const required = aboveDepthBound(maxZ);
346
+ details.push(Number.isFinite(required) ? `required zScale=${required} (group max z=${maxZ})` : `no finite zScale exceeds group max z=${maxZ}; revise median or relief`);
347
+ }
348
+ if (minMedian !== undefined) {
349
+ details.push(Number.isFinite(minMedian) ? `required median=${minMedian} (rise ${minMedian - median} rig px)` : 'no finite median clears z<=0; reduce relief');
350
+ }
351
+ return { code: 'DEPTH_APPLY_CLIPPED', object: `part "${name}"`, detail: details.join('; ') };
352
+ }));
324
353
  // A replacement must share near/zScale with every retained part in its actual group.
325
354
  for (const [name, g] of Object.entries(recipe.groups)) {
326
355
  if (!applied(name)) continue;
@@ -0,0 +1,206 @@
1
+ /** Convert a raw NumPy model array to the prepared image's numeric map grid. */
2
+ import { depthMapFail as fail, type NumericMap } from './depthmaps.ts';
3
+
4
+ const MAGIC = [0x93, 0x4e, 0x55, 0x4d, 0x50, 0x59]; // \x93NUMPY
5
+
6
+ function readHeader(header: string, at: string): { shape: number[]; itemBytes: 4 | 8 } {
7
+ const malformed = (): never => fail('DEPTH_ARRAY_FORMAT', at,
8
+ 'malformed NumPy header; required a dictionary with exactly descr, fortran_order and shape, followed by a newline');
9
+ if (!header.endsWith('\n')) return malformed();
10
+ const body = header.slice(0, -1);
11
+ let offset = 0;
12
+ const skipSpace = (): void => {
13
+ while (body[offset] === ' ' || body[offset] === '\t') offset++;
14
+ };
15
+ const take = (token: RegExp): RegExpExecArray | null => {
16
+ skipSpace();
17
+ token.lastIndex = offset;
18
+ const match = token.exec(body);
19
+ if (match !== null) offset = token.lastIndex;
20
+ return match;
21
+ };
22
+ const expect = (token: RegExp): RegExpExecArray => take(token) ?? malformed();
23
+ const quoted = (): string => {
24
+ const match = expect(/'([^'\\\r\n]*)'|"([^"\\\r\n]*)"/y);
25
+ return match[1] ?? match[2];
26
+ };
27
+ expect(/\{/y);
28
+ let descr: string | undefined, order: string | undefined, shape: number[] | undefined;
29
+ while (take(/\}/y) === null) {
30
+ const key = quoted();
31
+ expect(/:/y);
32
+ if (key === 'descr' && descr === undefined) descr = quoted();
33
+ else if (key === 'fortran_order' && order === undefined) order = expect(/True|False/y)[0];
34
+ else if (key === 'shape' && shape === undefined) {
35
+ shape = [];
36
+ expect(/\(/y);
37
+ if (take(/\)/y) === null) {
38
+ do {
39
+ shape.push(Number(expect(/-?(?:0|[1-9][0-9]*)/y)[0]));
40
+ if (take(/,/y) !== null) continue;
41
+ if (shape.length === 1) return malformed(); // A one-element tuple needs its comma.
42
+ expect(/\)/y);
43
+ break;
44
+ } while (take(/\)/y) === null);
45
+ }
46
+ } else return malformed();
47
+ if (take(/,/y) === null) {
48
+ expect(/\}/y);
49
+ break;
50
+ }
51
+ }
52
+ skipSpace();
53
+ if (offset !== body.length || descr === undefined || order === undefined || shape === undefined) return malformed();
54
+ if (descr !== '<f4' && descr !== '<f8') return fail('DEPTH_ARRAY_FORMAT', at,
55
+ `dtype ${JSON.stringify(descr)}; required little-endian float32 (<f4) or float64 (<f8)`);
56
+ if (order !== 'False') return fail('DEPTH_ARRAY_FORMAT', at, `fortran_order=${order}; required False (C order)`);
57
+ return { shape, itemBytes: descr === '<f4' ? 4 : 8 };
58
+ }
59
+
60
+ function readArray(bytes: Uint8Array, kind: 'depth' | 'normals', at: string) {
61
+ if (!MAGIC.every((byte, i) => bytes[i] === byte) || bytes.length < 8) return fail('DEPTH_ARRAY_FORMAT', at,
62
+ `found ${bytes.length} bytes without a complete NumPy magic/version prefix; required a NumPy .npy file`);
63
+ const major = bytes[6], minor = bytes[7];
64
+ if ((major !== 1 && major !== 2 && major !== 3) || minor !== 0) return fail('DEPTH_ARRAY_FORMAT', at,
65
+ `NumPy version ${major}.${minor}; required 1.0, 2.0 or 3.0`);
66
+ const prefix = major === 1 ? 10 : 12;
67
+ if (bytes.length < prefix) return fail('DEPTH_ARRAY_FORMAT', at,
68
+ `found ${bytes.length} bytes; required ${prefix} for the NumPy ${major}.0 prefix and header length`);
69
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
70
+ const length = major === 1 ? view.getUint16(8, true) : view.getUint32(8, true);
71
+ const start = prefix + length;
72
+ if (start > bytes.length) return fail('DEPTH_ARRAY_FORMAT', at,
73
+ `header declares ${length} bytes; found ${bytes.length - prefix} bytes after the prefix`);
74
+ let header: string;
75
+ try {
76
+ // The supported keys, primitive dtypes and tuple grammar are ASCII in every version.
77
+ header = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes.subarray(prefix, start));
78
+ } catch {
79
+ return fail('DEPTH_ARRAY_FORMAT', at, 'header contains invalid text; required the NumPy dictionary for a primitive floating-point array');
80
+ }
81
+ const { shape, itemBytes } = readHeader(header, at);
82
+ const [height, width, planes] = shape;
83
+ const channels = kind === 'depth' ? 1 : 3;
84
+ const shapeMatches = kind === 'depth' ? shape.length === 2 || (shape.length === 3 && planes === 1) : shape.length === 3 && planes === 3;
85
+ if (!shapeMatches || !shape.every(n => Number.isSafeInteger(n) && n > 0)) return fail('DEPTH_ARRAY_SHAPE', at,
86
+ `shape (${shape.join(',')}) for ${kind}; required ${kind === 'depth' ? '(H,W) or (H,W,1)' : '(H,W,3)'} with positive safe integer dimensions`);
87
+ const expected = BigInt(height) * BigInt(width) * BigInt(channels) * BigInt(itemBytes);
88
+ const found = bytes.length - start;
89
+ if (BigInt(found) !== expected) return fail('DEPTH_ARRAY_FORMAT', at,
90
+ `payload has ${found} bytes; shape (${shape.join(',')}) and dtype require exactly ${expected}`);
91
+ const value = itemBytes === 4
92
+ ? (index: number) => view.getFloat32(start + index * itemBytes, true)
93
+ : (index: number) => view.getFloat64(start + index * itemBytes, true);
94
+ return { width, height, channels, value } as const;
95
+ }
96
+
97
+ function cropPadding(raw: string | undefined): [left: number, top: number, right: number, bottom: number] {
98
+ if (raw === undefined) return [0, 0, 0, 0];
99
+ const values = raw.split(',');
100
+ const [left, top, right, bottom] = values.map(Number);
101
+ if (values.length !== 4 || values.some(value => !/^\d+$/.test(value) || !Number.isSafeInteger(Number(value)))) {
102
+ return fail('DEPTH_ARRAY_PADDING', 'depth-map --padding',
103
+ `found ${JSON.stringify(raw)}; required four nonnegative safe integers LEFT,TOP,RIGHT,BOTTOM`);
104
+ }
105
+ return [left, top, right, bottom];
106
+ }
107
+
108
+ function unpaddedExtent(extent: number, before: number, after: number): number {
109
+ return extent - before - after;
110
+ }
111
+
112
+ const magnitude = (value: bigint): bigint => value < 0n ? -value : value;
113
+
114
+ /** A finite binary64 value is an integer multiple of the smallest subnormal (2^-1074). */
115
+ function floatUnits(value: number, bits: DataView): bigint {
116
+ bits.setFloat64(0, value);
117
+ const high = bits.getUint32(0), low = bits.getUint32(4);
118
+ const exponent = (high >>> 20) & 0x7ff;
119
+ const fraction = (BigInt(high & 0xfffff) << 32n) | BigInt(low);
120
+ const units = exponent === 0 ? fraction : ((1n << 52n) | fraction) << BigInt(exponent - 1);
121
+ return (high >>> 31) === 0 ? units : -units;
122
+ }
123
+
124
+ /** Divide exact units, rounding once to binary64 (nearest, ties to even). */
125
+ function meanOfUnits(sum: bigint, count: bigint): number {
126
+ if (sum === 0n) return 0;
127
+ const abs = magnitude(sum);
128
+ const shift = Math.max(0, (abs / count).toString(2).length - 53);
129
+ const divisor = count << BigInt(shift);
130
+ const quotient = abs / divisor, twiceRemainder = (abs % divisor) * 2n;
131
+ const roundUp = twiceRemainder > divisor || (twiceRemainder === divisor && quotient % 2n !== 0n);
132
+ const value = Number(roundUp ? quotient + 1n : quotient) * 2 ** (shift - 1074);
133
+ return sum < 0n ? -value : value;
134
+ }
135
+
136
+ function normalize(x: number, y: number, z: number): [number, number, number] {
137
+ const scale = Math.max(Math.abs(x), Math.abs(y), Math.abs(z));
138
+ const nx = x / scale, ny = y / scale, nz = z / scale;
139
+ const length = Math.sqrt(nx * nx + ny * ny + nz * nz);
140
+ return [nx / length, ny / length, nz / length];
141
+ }
142
+
143
+ export function modelArrayMap(bytes: Uint8Array, image: { width: number; height: number }, kind: string,
144
+ padding: string | undefined, at: string): NumericMap {
145
+ if (kind !== 'depth' && kind !== 'normals') return fail('DEPTH_ARRAY_KIND', 'depth-map --kind',
146
+ `found ${JSON.stringify(kind)}; required depth or normals`);
147
+ const [left, top, right, bottom] = cropPadding(padding);
148
+ const array = readArray(bytes, kind, at);
149
+ const retainedWidth = unpaddedExtent(array.width, left, right), retainedHeight = unpaddedExtent(array.height, top, bottom);
150
+ if (retainedWidth <= 0 || retainedHeight <= 0) return fail('DEPTH_ARRAY_PADDING', at,
151
+ `padding ${left},${top},${right},${bottom} leaves ${retainedWidth}x${retainedHeight} of raw ${array.width}x${array.height}; required a nonempty crop`);
152
+ const { width, height } = image;
153
+ if (!Number.isSafeInteger(width) || !Number.isSafeInteger(height) || width < 1 || height < 1 ||
154
+ retainedWidth % width !== 0 || retainedHeight % height !== 0) return fail('DEPTH_ARRAY_SIZE', at,
155
+ `retained ${retainedWidth}x${retainedHeight}, prepared PNG ${width}x${height}; required a positive integer pooling factor on each axis`);
156
+ const stepX = retainedWidth / width, stepY = retainedHeight / height;
157
+ const { channels, value } = array;
158
+ const data: number[] = [];
159
+ const single = stepX === 1 && stepY === 1;
160
+ const count = BigInt(stepX) * BigInt(stepY), bits = new DataView(new ArrayBuffer(8));
161
+ for (let y = 0; y < height; y++) for (let x = 0; x < width; x++) {
162
+ const rawLeft = left + x * stepX, rawTop = top + y * stepY;
163
+ let sumX = 0n, sumY = 0n, sumZ = 0n;
164
+ for (let sy = rawTop; sy < rawTop + stepY; sy++) for (let sx = rawLeft; sx < rawLeft + stepX; sx++) {
165
+ const index = (sy * array.width + sx) * channels;
166
+ const vx = value(index);
167
+ if (channels === 1) {
168
+ if (!Number.isFinite(vx)) return fail('DEPTH_ARRAY_NONFINITE', at,
169
+ `raw pixel (${sx},${sy}) has depth ${vx}; required a finite value`);
170
+ if (single) data.push(vx);
171
+ else sumX += floatUnits(vx, bits);
172
+ continue;
173
+ }
174
+ const vy = value(index + 1), vz = value(index + 2);
175
+ if (!Number.isFinite(vx) || !Number.isFinite(vy) || !Number.isFinite(vz) || (vx === 0 && vy === 0 && vz === 0)) {
176
+ return fail('DEPTH_ARRAY_NORMAL', at,
177
+ `raw pixel (${sx},${sy}) has normal [${vx},${vy},${vz}]; required a finite nonzero XYZ vector`);
178
+ }
179
+ if (single) data.push(...normalize(vx, vy, vz));
180
+ else {
181
+ sumX += floatUnits(vx, bits);
182
+ sumY += floatUnits(vy, bits);
183
+ sumZ += floatUnits(vz, bits);
184
+ }
185
+ }
186
+ if (single) continue;
187
+ if (channels === 1) data.push(meanOfUnits(sumX, count));
188
+ else {
189
+ const scale = [sumX, sumY, sumZ].map(magnitude).reduce((a, b) => a > b ? a : b);
190
+ if (scale === 0n) return fail('DEPTH_ARRAY_NORMAL', at,
191
+ `output pixel (${x},${y}) has pooled normal [0,0,0]; required a nonzero pooled XYZ vector`);
192
+ // The tile count cancels in normalization. Scale the exact sums before rounding,
193
+ // so a subnormal residual or an overflowing sum can still give a direction.
194
+ data.push(...normalize(meanOfUnits(sumX << 1074n, scale), meanOfUnits(sumY << 1074n, scale), meanOfUnits(sumZ << 1074n, scale)));
195
+ }
196
+ }
197
+ return { spec: 'rig-parts-map/1', width, height, channels, data };
198
+ }
199
+
200
+ /** JSON accepts signed zero even though JSON.stringify emits 0 for either sign. */
201
+ export function serializeModelArrayMap(map: NumericMap): string {
202
+ if (!map.data.some(value => Object.is(value, -0))) return JSON.stringify(map) + '\n';
203
+ const { data, ...header } = map;
204
+ const values = data.map(value => Object.is(value, -0) ? '-0' : String(value)).join(',');
205
+ return `${JSON.stringify(header).slice(0, -1)},"data":[${values}]}\n`;
206
+ }
package/src/neckdraft.ts CHANGED
@@ -75,9 +75,9 @@ export function draftIndependentNeck(input: { config: CharacterConfig; source: R
75
75
  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');
76
76
  const zNeck = sampleUnitPartDepth(scalar, art, ref);
77
77
  const zRef = sampleUnitPartDepth(extendDepthSilhouette(surf.depthImage, surf.image), surf.image, surf.record.depth);
78
- const value = pyRound(pivot + zNeck - zRef, 4);
79
- body.unitDepths = { ...unitDepths, [part]: value };
78
+ const projectedDepth = pyRound(pivot + zNeck - zRef, 4);
79
+ body.unitDepths = { ...unitDepths, [part]: zNeck };
80
80
  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)`);
81
- 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
+ notes.push(`neck depth: turn.body.unitDepths.${part} = neck world median ${zNeck}; projected depth ${projectedDepth} = 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`);
82
82
  return { config: cfg, assembled, notes };
83
83
  }
package/src/rig.ts CHANGED
@@ -3479,10 +3479,33 @@ export function buildWaistPairSource(
3479
3479
  const bodyTransform = world.get(bodyRoot) as BoneTransform;
3480
3480
  const bodyTurnDeg = turn.get(bodyRoot) ?? 0;
3481
3481
  const surfBones: RigBone[] = [];
3482
- const unitMeshBones: RigBone[] = [];
3482
+ const bodyUnitBones: RigBone[] = [];
3483
+ const unitDepths = bodySpec.unitDepths ?? cfg.turn.unitDepths;
3484
+ const torsoRoots = new Set<string>([bodyRoot, 'chest', 'hip', `${bodyRoot}${CONTROL_SUFFIX}`, `chest${CONTROL_SUFFIX}`, `hip${CONTROL_SUFFIX}`]);
3485
+ const regionUnitCarriers = new Map<string, string>();
3486
+ const addBodyUnitCarrier = (slot: string): string => {
3487
+ const name = turnUnitBone(slot);
3488
+ if (bones.some(b => b.name === name) || bodyUnitBones.some(b => b.name === name)) {
3489
+ fail('RIG_TURN_NAME_FREE', `bone "${name}"`, `is the body unit carrier for slot "${slot}", and the rig already has a bone of that name; rename it`);
3490
+ } else {
3491
+ bodyUnitBones.push({ name, parent: BODYSHIFT_BONE, x: 0, y: 0 });
3492
+ }
3493
+ return name;
3494
+ };
3495
+ const addRegionUnitCarrier = (part: string, slot: string, bone: string): void => {
3496
+ if (torsoRoots.has(bone) && (unitDepths?.[part] !== undefined || unitDepths?.[bone] !== undefined)) {
3497
+ regionUnitCarriers.set(slot, addBodyUnitCarrier(slot));
3498
+ }
3499
+ };
3483
3500
  for (const p of parts.parts) {
3484
- if (bodyRoles[p.name] === 'unit' && cfg.meshes[p.name] !== undefined) {
3485
- unitMeshBones.push({ name: turnUnitBone(p.name), parent: BODYSHIFT_BONE, x: 0, y: 0 });
3501
+ if (bodyRoles[p.name] === 'unit') {
3502
+ if (cfg.meshes[p.name] !== undefined) {
3503
+ addBodyUnitCarrier(p.name);
3504
+ } else if (cfg.regions[p.name] !== undefined) {
3505
+ addRegionUnitCarrier(p.name, p.name, regionBone(cfg.regions[p.name]));
3506
+ const still = stills[p.name];
3507
+ if (still !== undefined) addRegionUnitCarrier(p.name, `${p.name}${STILL_SUFFIX}`, still.bone);
3508
+ }
3486
3509
  continue;
3487
3510
  }
3488
3511
  if (bodyRoles[p.name] !== 'surface' || cfg.meshes[p.name] !== undefined) continue;
@@ -3505,7 +3528,7 @@ export function buildWaistPairSource(
3505
3528
  { name: BODYSHIFT_BONE, parent: bodyRoot, x: 0, y: 0 },
3506
3529
  ...(hasRear ? [{ name: BODY_REAR_SHIFT_BONE, parent: bodyRoot, x: 0, y: 0 }] : []),
3507
3530
  ...surfBones,
3508
- ...unitMeshBones,
3531
+ ...bodyUnitBones,
3509
3532
  ];
3510
3533
  bones.splice(bodyIdx + 1, 0, ...carriers);
3511
3534
  const bodyDialBone = bodySpec.slider ?? BODY_YAW_DIAL_BONE;
@@ -3520,7 +3543,6 @@ export function buildWaistPairSource(
3520
3543
  throw new Error(`turn invariant violated: turn carrier "${boneName}" must never be reparented (target "${targetParent}")`);
3521
3544
  }
3522
3545
  };
3523
- const torsoRoots = new Set<string>([bodyRoot, 'chest', 'hip', `${bodyRoot}${CONTROL_SUFFIX}`, `chest${CONTROL_SUFFIX}`, `hip${CONTROL_SUFFIX}`]);
3524
3546
  const headExclusion = new Set<string>(['head', `head${CONTROL_SUFFIX}`, 'neck', `neck${CONTROL_SUFFIX}`, FACESHIFT_BONE, REAR_SHIFT_BONE]);
3525
3547
  const reparentFromTorso = (boneName: string, targetParent: string): void => {
3526
3548
  assertNotBodyTurnCarrier(boneName, targetParent);
@@ -3671,31 +3693,42 @@ export function buildWaistPairSource(
3671
3693
  rebindBodyPartToCarrier(part, unitBone);
3672
3694
  };
3673
3695
 
3696
+ const rebindTorsoRegion = (slot: string, bone: string, carrier: string): void => {
3697
+ const sl = slotByName.get(slot);
3698
+ if (sl !== undefined) sl.bone = carrier;
3699
+ if (bone === bodyRoot) return;
3700
+ const oldTr = world.get(bone);
3701
+ if (oldTr === undefined) return;
3702
+ for (const att of Object.values(skin[slot] ?? {})) {
3703
+ if (!('type' in att)) {
3704
+ const [wx, wy] = toWorld(oldTr, att.x, att.y);
3705
+ const [lx, ly] = toBoneLocal(bodyTransform, wx, wy);
3706
+ att.x = places(lx);
3707
+ att.y = places(ly);
3708
+ if (regionUnitCarriers.get(slot) === carrier) {
3709
+ const rotation = places(normaliseDegrees((att.rotation ?? 0) + (turn.get(bone) ?? 0) - bodyTurnDeg));
3710
+ if (rotation === 0) delete att.rotation;
3711
+ else att.rotation = rotation;
3712
+ }
3713
+ }
3714
+ }
3715
+ };
3674
3716
  for (const [part, role] of Object.entries(bodyRoles)) {
3675
3717
  if (role === 'unit') {
3676
3718
  if (cfg.regions[part] !== undefined) {
3677
3719
  const bName = regionBone(cfg.regions[part]);
3678
3720
  if (torsoRoots.has(bName)) {
3679
- const sl = slotByName.get(part);
3680
- if (sl !== undefined) sl.bone = BODYSHIFT_BONE;
3681
- if (bName !== bodyRoot) {
3682
- const oldTr = world.get(bName);
3683
- if (oldTr !== undefined) {
3684
- for (const att of Object.values(skin[part] ?? {})) {
3685
- if (!('type' in att)) {
3686
- const [wx, wy] = toWorld(oldTr, att.x, att.y);
3687
- const [lx, ly] = toBoneLocal(bodyTransform, wx, wy);
3688
- att.x = places(lx);
3689
- att.y = places(ly);
3690
- }
3691
- }
3692
- }
3693
- }
3721
+ rebindTorsoRegion(part, bName, regionUnitCarriers.get(part) ?? BODYSHIFT_BONE);
3694
3722
  } else {
3695
3723
  reparentFromTorso(bName, BODYSHIFT_BONE);
3696
3724
  }
3697
3725
  const st = stills[part];
3698
- if (st !== undefined) reparentFromTorso(st.bone, BODYSHIFT_BONE);
3726
+ if (st !== undefined) {
3727
+ const slot = `${part}${STILL_SUFFIX}`;
3728
+ const carrier = regionUnitCarriers.get(slot);
3729
+ if (carrier !== undefined) rebindTorsoRegion(slot, st.bone, carrier);
3730
+ else reparentFromTorso(st.bone, BODYSHIFT_BONE);
3731
+ }
3699
3732
  } else if (cfg.meshes[part] !== undefined) {
3700
3733
  rebindBodyUnitMeshToCarrier(part);
3701
3734
  }
@@ -3703,21 +3736,7 @@ export function buildWaistPairSource(
3703
3736
  if (cfg.regions[part] !== undefined) {
3704
3737
  const bName = regionBone(cfg.regions[part]);
3705
3738
  if (torsoRoots.has(bName)) {
3706
- const sl = slotByName.get(part);
3707
- if (sl !== undefined) sl.bone = BODY_REAR_SHIFT_BONE;
3708
- if (bName !== bodyRoot) {
3709
- const oldTr = world.get(bName);
3710
- if (oldTr !== undefined) {
3711
- for (const att of Object.values(skin[part] ?? {})) {
3712
- if (!('type' in att)) {
3713
- const [wx, wy] = toWorld(oldTr, att.x, att.y);
3714
- const [lx, ly] = toBoneLocal(bodyTransform, wx, wy);
3715
- att.x = places(lx);
3716
- att.y = places(ly);
3717
- }
3718
- }
3719
- }
3720
- }
3739
+ rebindTorsoRegion(part, bName, BODY_REAR_SHIFT_BONE);
3721
3740
  } else {
3722
3741
  reparentFromTorso(bName, BODY_REAR_SHIFT_BONE);
3723
3742
  }
package/src/turn.ts CHANGED
@@ -672,6 +672,7 @@ export function applyFaceSurfaceDeform(
672
672
  skins: { default: Record<string, Record<string, DeformMeshAttachment | DeformRegionAttachment>> };
673
673
  constraints?: Array<Record<string, unknown>>;
674
674
  invariants?: Record<string, unknown>;
675
+ stops?: Depth25DTurnRig['stops'];
675
676
  },
676
677
  motion: {
677
678
  groups?: Record<string, string[]>;
@@ -890,20 +891,28 @@ export function applyFaceSurfaceDeform(
890
891
  ? opts.surfaceRadius
891
892
  : turnSurfaceRadius(opts.turn, W);
892
893
 
893
- const boneOrder = new Map<string, number>(rig.bones.map((b, i) => [b.name, i]));
894
+ const setup = surfaceSetupGraph(rig);
895
+ // Core splices each drawn link after its source. Keep these emitted names
896
+ // and their order in the weight rows that the deform pairs are indexed by.
897
+ const boneOrder = new Map(rig.bones.map((b, i) => [b.name, 2 * i]));
898
+ const orderOf = (bone: string): number => {
899
+ const source = setup.resolve(bone);
900
+ return (boneOrder.get(source) ?? 0) + (source === bone ? 0 : 1);
901
+ };
894
902
  for (const slotName of ['hair_front', 'hair_back', 'hairpin']) {
895
903
  const slotObj = rig.skins.default[slotName];
896
904
  const att = slotObj?.[slotName];
897
905
  if (hasDeformWeights(att)) {
898
906
  for (const infls of att.weights) {
899
- infls.sort((a, b) => (boneOrder.get(a.bone) ?? 0) - (boneOrder.get(b.bone) ?? 0));
907
+ infls.sort((a, b) => orderOf(a.bone) - orderOf(b.bone));
900
908
  }
901
909
  }
902
910
  }
903
911
 
904
- const tf = computeWorldTransforms(rig.bones);
912
+ const tf = computeWorldTransforms(setup.bones);
905
913
  const headTf = tf.get('head') as BoneTransform | undefined;
906
914
  if (headTf === undefined) return;
915
+ const influenceFrame = (bone: string): BoneTransform => tf.get(setup.resolve(bone)) as BoneTransform;
907
916
 
908
917
  interface VertexSetup {
909
918
  hx: number;
@@ -918,11 +927,12 @@ export function applyFaceSurfaceDeform(
918
927
  let wy = 0;
919
928
  const boneWeights: Record<string, number> = {};
920
929
  for (const inf of infls) {
921
- const m = tf.get(inf.bone) as BoneTransform;
930
+ const bone = setup.resolve(inf.bone);
931
+ const m = influenceFrame(inf.bone);
922
932
  const [x, y] = toWorld(m, inf.x, inf.y);
923
933
  wx += x * inf.weight;
924
934
  wy += y * inf.weight;
925
- boneWeights[inf.bone] = (boneWeights[inf.bone] ?? 0) + inf.weight;
935
+ boneWeights[bone] = (boneWeights[bone] ?? 0) + inf.weight;
926
936
  }
927
937
  return { hx: wx - headTf.worldX, hy: wy - headTf.worldY, boneWeights, infls };
928
938
  });
@@ -932,7 +942,7 @@ export function applyFaceSurfaceDeform(
932
942
  for (const v of verts) {
933
943
  const [dx, dy] = evalVertex(v);
934
944
  for (const inf of v.infls) {
935
- const m = tf.get(inf.bone) as BoneTransform;
945
+ const m = influenceFrame(inf.bone);
936
946
  const [bx, by] = toBoneLocalVector(m, dx, dy);
937
947
  out.push(pyRound(bx, 4), pyRound(by, 4));
938
948
  }
@@ -940,7 +950,7 @@ export function applyFaceSurfaceDeform(
940
950
  return out;
941
951
  };
942
952
 
943
- const boneMap = new Map(rig.bones.map((b) => [b.name, b]));
953
+ const boneMap = new Map(setup.bones.map((b) => [b.name, b]));
944
954
  const referencedGroups = new Set<string>();
945
955
  for (const anim of [tiltAnim, turnAnim]) {
946
956
  for (const tr of anim?.tracks ?? []) {
@@ -1556,7 +1566,7 @@ interface Depth25DGroupSpec {
1556
1566
  }
1557
1567
 
1558
1568
  interface Depth25DTurnRig {
1559
- bones: Array<{ name: string; parent?: string; x: number; y: number; rotation?: number; length?: number }>;
1569
+ bones: Array<{ name: string; parent?: string; x: number; y: number; rotation?: number; length?: number; inherit?: string }>;
1560
1570
  slots: Array<{ name: string; bone: string; attachment: string | null }>;
1561
1571
  constraints?: Array<Record<string, unknown>>;
1562
1572
  stops?: ReadonlyArray<{ links: readonly string[] }>;
@@ -1573,7 +1583,7 @@ interface TurnBandCover {
1573
1583
  }
1574
1584
 
1575
1585
  /** Stop draw bones share their link's setup frame; Core emits them later. */
1576
- function surfaceSetupGraph(rig: Depth25DTurnRig) {
1586
+ function surfaceSetupGraph(rig: Pick<Depth25DTurnRig, 'bones' | 'stops'>) {
1577
1587
  const aliases = new Map<string, string>();
1578
1588
  for (const stop of rig.stops ?? []) for (const link of stop.links) aliases.set(`${link}_d`, link);
1579
1589
  const resolve = (name: string): string => aliases.get(name) ?? name;
@@ -1748,7 +1758,8 @@ function buildDepth25DTurnGroup(
1748
1758
  }
1749
1759
  if (problems.length > startProblems) return;
1750
1760
  }
1751
- // Collect unit bones that sit directly under carrierBone and resolve one scalar depth per unit bone.
1761
+ // Key one scalar depth per direct carrier child. A region can bind a
1762
+ // descendant of that child or a generated carrier instead of its authored bone.
1752
1763
  const carrierChildren = new Set(rig.bones.filter((b) => b.parent === group.carrierBone).map((b) => b.name));
1753
1764
  const unitDepthMap: Record<string, number> = {};
1754
1765
  const unitBones: string[] = [];
@@ -1757,31 +1768,79 @@ function buildDepth25DTurnGroup(
1757
1768
  if (!unitBones.includes(bone)) unitBones.push(bone);
1758
1769
  unitDepthMap[bone] = pyRound(depth, 4);
1759
1770
  };
1771
+ const isBody = group.fieldPrefix === 'config.turn.body';
1772
+ const bodySetup = isBody ? surfaceSetupGraph(rig) : undefined;
1773
+ const bodyParents = new Map(bodySetup?.bones.map(b => [b.name, b.parent]));
1774
+ const directCarrierChild = (bone: string): string | undefined => {
1775
+ let current: string | undefined = bodySetup?.resolve(bone);
1776
+ const seen = new Set<string>();
1777
+ while (current !== undefined && !seen.has(current)) {
1778
+ if (carrierChildren.has(current)) return current;
1779
+ seen.add(current);
1780
+ current = bodyParents.get(current);
1781
+ }
1782
+ return undefined;
1783
+ };
1784
+ const bodyUnitOwners = new Map<string, { part: string; depth: number; explicit: boolean }>();
1785
+ const refuseCarrier = (part: string, bone: string, reason: string): void => {
1786
+ problems.push({
1787
+ code: 'RIG_TURN_BODY_UNIT_CARRIER',
1788
+ object: `${group.fieldPrefix}.roles.${part}`,
1789
+ detail: `cannot resolve a movable carrier for unit part "${part}" (bone "${bone}"); ${reason}`,
1790
+ });
1791
+ };
1760
1792
 
1761
1793
  for (const [part, role] of Object.entries(roles)) {
1762
1794
  if (role !== 'unit') continue;
1763
1795
  const regSpec = opts.regions[part];
1764
1796
  let baseBone: string | undefined;
1765
- let candidateBones: string[] = [];
1797
+ const candidateBones: Array<{ bone: string; carrier: string }> = [];
1798
+ const explicitPartDepth = group.unitDepths?.[part];
1766
1799
  if (regSpec !== undefined) {
1767
1800
  baseBone = typeof regSpec === 'string' ? regSpec : regSpec.bone;
1768
1801
  const stillBone = opts.stills[part]?.bone;
1769
- candidateBones = [baseBone, ...(stillBone === undefined ? [] : [stillBone])].filter((b) => carrierChildren.has(b));
1802
+ const pieces = [{ bone: baseBone, slot: part }];
1803
+ if (stillBone !== undefined) pieces.push({ bone: stillBone, slot: `${part}_still` });
1804
+ for (const { bone, slot } of pieces) {
1805
+ if (isBody && (explicitPartDepth !== undefined || group.unitDepths?.[bone] !== undefined)) {
1806
+ const binding = rig.slots.find(s => s.name === slot)?.bone;
1807
+ const carrier = binding === undefined ? undefined : directCarrierChild(binding);
1808
+ if (carrier === undefined) {
1809
+ refuseCarrier(part, bone, binding === undefined
1810
+ ? `slot "${slot}" has no emitted bone binding`
1811
+ : `slot "${slot}" binds "${binding}", which has no movable ancestor directly under "${group.carrierBone}"`);
1812
+ } else {
1813
+ candidateBones.push({ bone, carrier });
1814
+ }
1815
+ } else if (carrierChildren.has(bone)) {
1816
+ candidateBones.push({ bone, carrier: bone });
1817
+ }
1818
+ }
1770
1819
  } else {
1771
1820
  const uBone = turnUnitBone(part);
1772
- if (carrierChildren.has(uBone)) candidateBones = [uBone];
1821
+ if (carrierChildren.has(uBone)) {
1822
+ const explicit = isBody && (explicitPartDepth !== undefined || group.unitDepths?.[uBone] !== undefined);
1823
+ const outside = explicit ? opts.neighbourMeshes?.filter(m => m.part === part)
1824
+ .flatMap(m => m.weights).flat().find(w => w.weight > 0 && directCarrierChild(w.bone) !== uBone) : undefined;
1825
+ if (outside !== undefined) refuseCarrier(part, outside.bone, `its weighted binding is outside the dedicated carrier "${uBone}" under "${group.carrierBone}"`);
1826
+ else candidateBones.push({ bone: uBone, carrier: uBone });
1827
+ } else if (isBody && (explicitPartDepth !== undefined || group.unitDepths?.[uBone] !== undefined)) {
1828
+ refuseCarrier(part, uBone, `the rig has no dedicated unit carrier "${uBone}" under "${group.carrierBone}"`);
1829
+ }
1773
1830
  }
1774
- if (candidateBones.length === 0) continue;
1775
1831
 
1776
- for (const bName of candidateBones) {
1777
- const explicitPartDepth = group.unitDepths?.[part];
1832
+ for (const { bone: bName, carrier } of candidateBones) {
1778
1833
  const explicitBoneDepth = group.unitDepths?.[bName];
1779
1834
  let resolved: number | null = null;
1780
1835
  if (typeof explicitPartDepth === 'number' && Number.isFinite(explicitPartDepth)) {
1781
1836
  resolved = explicitPartDepth;
1782
1837
  } else if (typeof explicitBoneDepth === 'number' && Number.isFinite(explicitBoneDepth)) {
1783
1838
  resolved = explicitBoneDepth;
1784
- } else if (primarySurface !== undefined) {
1839
+ }
1840
+ const explicitBodyDepth = isBody && resolved !== null;
1841
+ if (explicitBodyDepth && resolved !== null && primarySurface !== undefined) {
1842
+ resolved = pivot + (resolved - primarySurface.zRef);
1843
+ } else if (resolved === null && primarySurface !== undefined) {
1785
1844
  let pt: readonly [number, number] | undefined =
1786
1845
  opts.boneLandmarks.get(bName) ??
1787
1846
  (baseBone === undefined ? undefined : opts.boneLandmarks.get(baseBone));
@@ -1864,7 +1923,16 @@ function buildDepth25DTurnGroup(
1864
1923
  }
1865
1924
  }
1866
1925
  }
1867
- addUnitBone(bName, resolved);
1926
+ if (isBody) {
1927
+ const depth = pyRound(resolved, 4);
1928
+ const owner = bodyUnitOwners.get(carrier);
1929
+ if (owner !== undefined && (owner.explicit || explicitBodyDepth) && owner.depth !== depth) {
1930
+ refuseCarrier(part, bName, `carrier "${carrier}" is shared with part "${owner.part}" at effective depth ${owner.depth}, and cannot also move at effective depth ${depth}`);
1931
+ continue;
1932
+ }
1933
+ bodyUnitOwners.set(carrier, { part, depth, explicit: explicitBodyDepth || owner?.explicit === true });
1934
+ }
1935
+ addUnitBone(carrier, resolved);
1868
1936
  }
1869
1937
  }
1870
1938
  if (problems.length > startProblems) return;