rig-parts 2.58.0 → 2.60.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.
@@ -6,15 +6,14 @@
6
6
  *
7
7
  * ## The falloff, as a definition
8
8
  *
9
- * A region's bone takes the weight
9
+ * The nominal linear share is
10
10
  *
11
11
  * g = 1 inside the region (its boundary included)
12
12
  * g = 1 − d / band at a distance d from the region, 0 < d < band
13
13
  * g = 0 at d ≥ band (for band 0: everywhere outside)
14
14
  *
15
15
  * where d is the Euclidean distance to the circle (|p − c| − r) or to the
16
- * nearest point of the polygon's edges. That is the declared falloff — linear,
17
- * no smoothstep, no tuned curve. The two decisions that are not a value in
16
+ * nearest point of the polygon's edges. The two decisions that are not a value in
18
17
  * between — "inside" (g = 1) and "at or past the band" (g = 0) — are made
19
18
  * EXACTLY: every region number is a multiple of 1/256 px (the config loader
20
19
  * refuses anything else) and every vertex this package writes is too
@@ -23,7 +22,11 @@
23
22
  * inside by the crossing rule on integer orientations, its distance to an edge
24
23
  * compared squared in `BigInt`. Only a value strictly in between is computed
25
24
  * in doubles (`Math.sqrt` and the reference's segment arithmetic), and it is
26
- * clamped to [0, 1].
25
+ * clamped to [0, 1]. Contour weighting applies `4 * g * g * (1 - g)` for
26
+ * `0 < g < 0.5` after the overlap check (issue #1578). The cubic reaches the
27
+ * cutoff with zero slope and meets the inner half at the same value and slope.
28
+ * Declaring `falloff: 'linear'` keeps the nominal share throughout the band,
29
+ * as automatic weighting does.
27
30
  *
28
31
  * ## The vertex's weights (see {@link localInfluences})
29
32
  *
@@ -44,8 +47,8 @@
44
47
  * lightest bone (its last) is dropped and the rest renormalised before the
45
48
  * scaling, so g itself is never cut. **The floor:** the minimum weight is
46
49
  * applied inside `S` (as today) and not again to the scaled shares — a
47
- * share (1 − g)·S(b) under 0.03 is the declared falloff near the region, not
48
- * noise to drop, and dropping it would put a step into the linear ramp.
50
+ * share (1 − g)·S(b) under 0.03 is part of the blend, and dropping it would
51
+ * put a step into the ramp.
49
52
  * The rounding: see `roundShares` in `src/rig.ts`.
50
53
  *
51
54
  * ## Overlapping regions
@@ -63,7 +66,7 @@
63
66
  * between vertices are not refused, and there the mesh interpolates between
64
67
  * vertices that each hold one region.
65
68
  */
66
- import type { Point } from './config.ts';
69
+ import type { ContourRegionSpec, Point } from './config.ts';
67
70
  import { GRID } from './contour.ts';
68
71
  import { DEFAULT_LIMITS, DISTANCE_EXPONENT, type Influence, influences, type InfluenceLimits, type Segment, segmentDistance } from './weights.ts';
69
72
 
@@ -121,8 +124,8 @@ function insideRing(px: number, py: number, xs: readonly number[], ys: readonly
121
124
  }
122
125
 
123
126
  /**
124
- * The declared falloff: the weight a region's bone takes at `p` (same frame as
125
- * the region). `p` must be on the 1/256 px grid; see the module header for
127
+ * The nominal linear share at `p` (same frame as the region), used to decide
128
+ * support. `p` must be on the 1/256 px grid. See the module header for
126
129
  * which decisions are exact.
127
130
  */
128
131
  export function regionWeight(p: Point, reg: WeightRegion): number {
@@ -167,6 +170,7 @@ export interface LocalInfluence {
167
170
  influences: Influence[];
168
171
  /** The region that reached the vertex (g > 0), by index, or -1. */
169
172
  region: number;
173
+ /** The unrounded region share used in the blend. */
170
174
  g: number;
171
175
  }
172
176
 
@@ -175,7 +179,9 @@ export interface LocalInfluence {
175
179
  * given, is `S` from another rule — bone heat's shares at the vertex
176
180
  * (`src/heat.ts`, issue #161), already capped and floored by `limits` — and
177
181
  * the regions apply to it exactly as to the distance rule's. Returns the
178
- * overlap instead when two regions both reach the vertex. Order: with no
182
+ * nominal overlap when two regions both reach the vertex. With `context`
183
+ * set to `contour`, the chosen region's outer half is eased by default.
184
+ * Order: with no
179
185
  * region, `S`'s own order; with a region, the region's bone first, then `S`'s
180
186
  * bones in `S`'s order.
181
187
  */
@@ -183,10 +189,11 @@ export function localInfluences(
183
189
  p: Point,
184
190
  segments: readonly Segment[],
185
191
  r: number,
186
- regions: readonly WeightRegion[],
192
+ regions: readonly (WeightRegion & Pick<ContourRegionSpec, 'falloff'>)[],
187
193
  limits: InfluenceLimits = DEFAULT_LIMITS,
188
194
  exponent: number = DISTANCE_EXPONENT,
189
195
  shares?: Influence[],
196
+ context?: 'contour',
190
197
  ): LocalInfluence | RegionOverlap {
191
198
  let region = -1;
192
199
  let g = 0;
@@ -199,7 +206,8 @@ export function localInfluences(
199
206
  }
200
207
  const S = shares ?? influences(p, segments, r, limits, exponent);
201
208
  if (region < 0) return { influences: S, region, g: 0 };
202
- const bone = regions[region].bone;
209
+ const { bone, falloff } = regions[region];
210
+ if (context === 'contour' && falloff !== 'linear' && g < 0.5) g = 4 * g * g * (1 - g);
203
211
  if (g >= 1) return { influences: [{ bone, weight: 1 }], region, g };
204
212
  let base = S;
205
213
  if (!S.some((e) => e.bone === bone) && S.length >= limits.maxInfluences) {
@@ -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
@@ -2118,6 +2118,11 @@ export function buildWaistPairSource(
2118
2118
  const w = img.width;
2119
2119
  const h = img.height;
2120
2120
  const regions = contourRegionsOf(spec);
2121
+ const explicitRegions = spec.regions?.length ?? 0;
2122
+ // The shorthand appends its derived circles, which keep the legacy ramp.
2123
+ const weightRegions = spec.bust === undefined ? regions : regions.map((rg, index) =>
2124
+ index < explicitRegions ? rg : { ...rg, falloff: 'linear' as const },
2125
+ );
2121
2126
  const ribs = chainRibs(ribSpec.segments, ribSpec.ribs, ox, oy);
2122
2127
  const cm = rigContour(p, img, spec, ribs);
2123
2128
  if (Array.isArray(cm)) {
@@ -2147,7 +2152,7 @@ export function buildWaistPairSource(
2147
2152
  const wx = vx + ox;
2148
2153
  const wy = vy + oy;
2149
2154
  const vSegs = segsAt(wy);
2150
- const li = localInfluences([wx, wy], vSegs, r, regions, limits, exponent ?? DISTANCE_EXPONENT, heat === null ? undefined : heatInfluences(heat, [vx, vy], limits));
2155
+ const li = localInfluences([wx, wy], vSegs, r, weightRegions, limits, exponent ?? DISTANCE_EXPONENT, heat === null ? undefined : heatInfluences(heat, [vx, vy], limits), 'contour');
2151
2156
  if ('first' in li) {
2152
2157
  if (!overlapped) {
2153
2158
  let bustHint = '';
@@ -2205,7 +2210,6 @@ export function buildWaistPairSource(
2205
2210
  for (const [x, y] of cm.vertices) uvs.push(pyRound(x / w, 6), pyRound(y / h, 6));
2206
2211
  const bones = new Set(segs.map((s) => s.bone));
2207
2212
  for (const rg of regions) bones.add(rg.bone);
2208
- const explicitRegions = spec.regions?.length ?? 0;
2209
2213
  if (explicitRegions > 0) {
2210
2214
  contourRegionSummaries.set(
2211
2215
  p.name,
@@ -3479,10 +3483,33 @@ export function buildWaistPairSource(
3479
3483
  const bodyTransform = world.get(bodyRoot) as BoneTransform;
3480
3484
  const bodyTurnDeg = turn.get(bodyRoot) ?? 0;
3481
3485
  const surfBones: RigBone[] = [];
3482
- const unitMeshBones: RigBone[] = [];
3486
+ const bodyUnitBones: RigBone[] = [];
3487
+ const unitDepths = bodySpec.unitDepths ?? cfg.turn.unitDepths;
3488
+ const torsoRoots = new Set<string>([bodyRoot, 'chest', 'hip', `${bodyRoot}${CONTROL_SUFFIX}`, `chest${CONTROL_SUFFIX}`, `hip${CONTROL_SUFFIX}`]);
3489
+ const regionUnitCarriers = new Map<string, string>();
3490
+ const addBodyUnitCarrier = (slot: string): string => {
3491
+ const name = turnUnitBone(slot);
3492
+ if (bones.some(b => b.name === name) || bodyUnitBones.some(b => b.name === name)) {
3493
+ 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`);
3494
+ } else {
3495
+ bodyUnitBones.push({ name, parent: BODYSHIFT_BONE, x: 0, y: 0 });
3496
+ }
3497
+ return name;
3498
+ };
3499
+ const addRegionUnitCarrier = (part: string, slot: string, bone: string): void => {
3500
+ if (torsoRoots.has(bone) && (unitDepths?.[part] !== undefined || unitDepths?.[bone] !== undefined)) {
3501
+ regionUnitCarriers.set(slot, addBodyUnitCarrier(slot));
3502
+ }
3503
+ };
3483
3504
  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 });
3505
+ if (bodyRoles[p.name] === 'unit') {
3506
+ if (cfg.meshes[p.name] !== undefined) {
3507
+ addBodyUnitCarrier(p.name);
3508
+ } else if (cfg.regions[p.name] !== undefined) {
3509
+ addRegionUnitCarrier(p.name, p.name, regionBone(cfg.regions[p.name]));
3510
+ const still = stills[p.name];
3511
+ if (still !== undefined) addRegionUnitCarrier(p.name, `${p.name}${STILL_SUFFIX}`, still.bone);
3512
+ }
3486
3513
  continue;
3487
3514
  }
3488
3515
  if (bodyRoles[p.name] !== 'surface' || cfg.meshes[p.name] !== undefined) continue;
@@ -3505,7 +3532,7 @@ export function buildWaistPairSource(
3505
3532
  { name: BODYSHIFT_BONE, parent: bodyRoot, x: 0, y: 0 },
3506
3533
  ...(hasRear ? [{ name: BODY_REAR_SHIFT_BONE, parent: bodyRoot, x: 0, y: 0 }] : []),
3507
3534
  ...surfBones,
3508
- ...unitMeshBones,
3535
+ ...bodyUnitBones,
3509
3536
  ];
3510
3537
  bones.splice(bodyIdx + 1, 0, ...carriers);
3511
3538
  const bodyDialBone = bodySpec.slider ?? BODY_YAW_DIAL_BONE;
@@ -3520,7 +3547,6 @@ export function buildWaistPairSource(
3520
3547
  throw new Error(`turn invariant violated: turn carrier "${boneName}" must never be reparented (target "${targetParent}")`);
3521
3548
  }
3522
3549
  };
3523
- const torsoRoots = new Set<string>([bodyRoot, 'chest', 'hip', `${bodyRoot}${CONTROL_SUFFIX}`, `chest${CONTROL_SUFFIX}`, `hip${CONTROL_SUFFIX}`]);
3524
3550
  const headExclusion = new Set<string>(['head', `head${CONTROL_SUFFIX}`, 'neck', `neck${CONTROL_SUFFIX}`, FACESHIFT_BONE, REAR_SHIFT_BONE]);
3525
3551
  const reparentFromTorso = (boneName: string, targetParent: string): void => {
3526
3552
  assertNotBodyTurnCarrier(boneName, targetParent);
@@ -3671,31 +3697,42 @@ export function buildWaistPairSource(
3671
3697
  rebindBodyPartToCarrier(part, unitBone);
3672
3698
  };
3673
3699
 
3700
+ const rebindTorsoRegion = (slot: string, bone: string, carrier: string): void => {
3701
+ const sl = slotByName.get(slot);
3702
+ if (sl !== undefined) sl.bone = carrier;
3703
+ if (bone === bodyRoot) return;
3704
+ const oldTr = world.get(bone);
3705
+ if (oldTr === undefined) return;
3706
+ for (const att of Object.values(skin[slot] ?? {})) {
3707
+ if (!('type' in att)) {
3708
+ const [wx, wy] = toWorld(oldTr, att.x, att.y);
3709
+ const [lx, ly] = toBoneLocal(bodyTransform, wx, wy);
3710
+ att.x = places(lx);
3711
+ att.y = places(ly);
3712
+ if (regionUnitCarriers.get(slot) === carrier) {
3713
+ const rotation = places(normaliseDegrees((att.rotation ?? 0) + (turn.get(bone) ?? 0) - bodyTurnDeg));
3714
+ if (rotation === 0) delete att.rotation;
3715
+ else att.rotation = rotation;
3716
+ }
3717
+ }
3718
+ }
3719
+ };
3674
3720
  for (const [part, role] of Object.entries(bodyRoles)) {
3675
3721
  if (role === 'unit') {
3676
3722
  if (cfg.regions[part] !== undefined) {
3677
3723
  const bName = regionBone(cfg.regions[part]);
3678
3724
  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
- }
3725
+ rebindTorsoRegion(part, bName, regionUnitCarriers.get(part) ?? BODYSHIFT_BONE);
3694
3726
  } else {
3695
3727
  reparentFromTorso(bName, BODYSHIFT_BONE);
3696
3728
  }
3697
3729
  const st = stills[part];
3698
- if (st !== undefined) reparentFromTorso(st.bone, BODYSHIFT_BONE);
3730
+ if (st !== undefined) {
3731
+ const slot = `${part}${STILL_SUFFIX}`;
3732
+ const carrier = regionUnitCarriers.get(slot);
3733
+ if (carrier !== undefined) rebindTorsoRegion(slot, st.bone, carrier);
3734
+ else reparentFromTorso(st.bone, BODYSHIFT_BONE);
3735
+ }
3699
3736
  } else if (cfg.meshes[part] !== undefined) {
3700
3737
  rebindBodyUnitMeshToCarrier(part);
3701
3738
  }
@@ -3703,21 +3740,7 @@ export function buildWaistPairSource(
3703
3740
  if (cfg.regions[part] !== undefined) {
3704
3741
  const bName = regionBone(cfg.regions[part]);
3705
3742
  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
- }
3743
+ rebindTorsoRegion(part, bName, BODY_REAR_SHIFT_BONE);
3721
3744
  } else {
3722
3745
  reparentFromTorso(bName, BODY_REAR_SHIFT_BONE);
3723
3746
  }