@rig-c/parts 1.71.0 → 1.72.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/rig.ts CHANGED
@@ -187,7 +187,7 @@ import { alphaAbove, crop, pad, type Raster } from './raster/index.ts';
187
187
  import { pyRound } from './round.ts';
188
188
  import { boneHeat, type HeatDust, heatInfluences, HEAT_LIMITS, heatRow, type HeatRow, latticeSilhouette, tracedSilhouette } from './heat.ts';
189
189
  import type { PosePoints } from './skeleton.ts';
190
- import { applyFaceSurfaceDeform, BODY_REAR_SHIFT_BONE, BODY_YAW_DIAL_BONE, BODYSHIFT_BONE, buildDepth25DTurn, FACE_RATED_BAND, FACESHIFT_BONE, PITCH_DIAL_BONE, REAR_SHIFT_BONE, resolveTurnGrid, TURN_BONE, TURN_CARRIER_TAG, TURN_GRID_MAX_TRIANGLES_PER_SLOT, TURN_GRID_MAX_TRIANGLES_TOTAL, TURN_PLACES, TURN_RIDER_APART, TURN_RIDER_TAGS, turnRiderDepth, type TurnRole, type TurnSpec, turnConstraintName, turnFractions, turnNearest, turnSurfaceBone, turnTwin, YAW_DIAL_BONE } from './turn.ts';
190
+ import { applyFaceSurfaceDeform, BODY_REAR_SHIFT_BONE, BODY_YAW_DIAL_BONE, BODYSHIFT_BONE, buildDepth25DTurn, FACE_RATED_BAND, FACESHIFT_BONE, PITCH_DIAL_BONE, REAR_SHIFT_BONE, resolveTurnGrid, TURN_BONE, TURN_CARRIER_TAG, TURN_GRID_MAX_TRIANGLES_PER_SLOT, TURN_GRID_MAX_TRIANGLES_TOTAL, TURN_PLACES, TURN_RIDER_APART, TURN_RIDER_TAGS, turnRiderDepth, type TurnRole, type TurnSpec, turnConstraintName, turnFractions, turnNearest, turnSurfaceBone, turnTwin, turnUnitBone, YAW_DIAL_BONE } from './turn.ts';
191
191
  import { DISTANCE_EXPONENT, type FloorForm, type Influence, influences, type InfluenceLimits, type MeshInfluences, meshLimits, type Segment } from './weights.ts';
192
192
 
193
193
  /** Transparent pixels added round every part image — the reference's `PAD`. */
@@ -2435,12 +2435,8 @@ export function buildWaistPairSource(
2435
2435
  const isBodySurface = cfg.turn?.body?.roles?.[p.name] === 'surface';
2436
2436
  if (isHeadSurface || isBodySurface) {
2437
2437
  const roleField = isHeadSurface ? `config.turn.roles.${p.name}` : `config.turn.body.roles.${p.name}`;
2438
- if (cfg.meshes[p.name] !== undefined) {
2439
- fail(
2440
- 'CONFIG_TURN_SURFACE_REGION',
2441
- roleField,
2442
- `declares "${p.name}" as "surface", and config.meshes.${p.name} also declares a mesh for "${p.name}"; a 2.5D turn "surface" part must be attached in config.regions so the rig stage can promote it to a depth-backed grid mesh`,
2443
- );
2438
+ if (cfg.meshes[p.name] !== undefined && configuredAlts.some((a) => (a.parts === undefined || a.parts.includes(p.name)) && !(a.hides ?? []).includes(p.name))) {
2439
+ fail('RIG_TURN_SURFACE_MESH_ATTACHMENT', roleField, `declares an alternate drawing for surface mesh "${p.name}"; alternate drawings need their own registered depth sampling frame`);
2444
2440
  continue;
2445
2441
  }
2446
2442
  if (p.depth === undefined || scalar === undefined) {
@@ -3128,8 +3124,13 @@ export function buildWaistPairSource(
3128
3124
  const headTransform = world.get('head') as BoneTransform;
3129
3125
  const headTurnDeg = turn.get('head') ?? 0;
3130
3126
  const surfBones: RigBone[] = [];
3127
+ const unitMeshBones: RigBone[] = [];
3131
3128
  for (const p of parts.parts) {
3132
- if (roles[p.name] !== 'surface') continue;
3129
+ if (roles[p.name] === 'unit' && cfg.meshes[p.name] !== undefined) {
3130
+ unitMeshBones.push({ name: turnUnitBone(p.name), parent: FACESHIFT_BONE, x: 0, y: 0 });
3131
+ continue;
3132
+ }
3133
+ if (roles[p.name] !== 'surface' || cfg.meshes[p.name] !== undefined) continue;
3133
3134
  const [cols, rows] = resolveTurnGrid(cfg.turn, p.name);
3134
3135
  totalGridTriangles += 2 * (cols - 1) * (rows - 1);
3135
3136
  const cx = p.x + p.w / 2;
@@ -3149,6 +3150,7 @@ export function buildWaistPairSource(
3149
3150
  { name: FACESHIFT_BONE, parent: 'head', x: 0, y: 0 },
3150
3151
  ...(hasRear ? [{ name: REAR_SHIFT_BONE, parent: 'head', x: 0, y: 0 }] : []),
3151
3152
  ...surfBones,
3153
+ ...unitMeshBones,
3152
3154
  ];
3153
3155
  bones.splice(headIdx + 1, 0, ...carriers);
3154
3156
  const existingNames = new Set(bones.map((b) => b.name));
@@ -3156,7 +3158,14 @@ export function buildWaistPairSource(
3156
3158
  if (!existingNames.has(PITCH_DIAL_BONE)) bones.push({ name: PITCH_DIAL_BONE, parent: ROOT_BONE, x: 0, y: 0 });
3157
3159
 
3158
3160
  const boneByName = new Map(bones.map((b) => [b.name, b]));
3161
+ const headCarriers = new Set<string>(carriers.map((b) => b.name));
3162
+ const assertNotHeadTurnCarrier = (boneName: string, targetParent: string): void => {
3163
+ if (headCarriers.has(boneName)) {
3164
+ throw new Error(`turn invariant violated: turn carrier "${boneName}" must never be reparented (target "${targetParent}")`);
3165
+ }
3166
+ };
3159
3167
  const reparentFromHead = (boneName: string, targetParent: string): void => {
3168
+ assertNotHeadTurnCarrier(boneName, targetParent);
3160
3169
  const b = boneByName.get(boneName);
3161
3170
  if (b !== undefined && b.parent === 'head') b.parent = targetParent;
3162
3171
  };
@@ -3168,25 +3177,100 @@ export function buildWaistPairSource(
3168
3177
  if (stillSl.bone === 'head') stillSl.bone = carrierBone;
3169
3178
  else reparentFromHead(stillSl.bone, carrierBone);
3170
3179
  }
3171
- const atts = skin[part] ?? {};
3172
- for (const att of Object.values(atts)) {
3173
- if (!('type' in att) || att.weights === undefined) continue;
3174
- for (const row of att.weights) {
3175
- for (const w of row) {
3176
- if (w.bone === 'head') {
3177
- w.bone = carrierBone;
3178
- } else {
3179
- let cur = boneByName.get(w.bone);
3180
- while (cur !== undefined && cur.parent !== undefined && cur.parent !== 'head' && cur.parent !== carrierBone) {
3181
- cur = boneByName.get(cur.parent);
3180
+ for (const slotEntry of finalSlots) {
3181
+ if (slotEntry.name !== part && !slotEntry.name.startsWith(`${part}__island`)) continue;
3182
+ if (slotEntry.bone === 'head') slotEntry.bone = carrierBone;
3183
+ const atts = skin[slotEntry.name] ?? {};
3184
+ for (const att of Object.values(atts)) {
3185
+ if (!('type' in att) || att.weights === undefined) continue;
3186
+ for (const row of att.weights) {
3187
+ for (const w of row) {
3188
+ if (w.bone === 'head') {
3189
+ w.bone = carrierBone;
3190
+ } else {
3191
+ let cur = boneByName.get(w.bone);
3192
+ while (cur !== undefined && cur.parent !== undefined && cur.parent !== 'head' && !headCarriers.has(cur.parent)) {
3193
+ cur = boneByName.get(cur.parent);
3194
+ }
3195
+ if (cur !== undefined && cur.parent === 'head') {
3196
+ assertNotHeadTurnCarrier(cur.name, carrierBone);
3197
+ cur.parent = carrierBone;
3198
+ }
3182
3199
  }
3183
- if (cur !== undefined && cur.parent === 'head') cur.parent = carrierBone;
3184
3200
  }
3185
3201
  }
3186
3202
  }
3187
3203
  }
3188
3204
  };
3189
3205
 
3206
+ const headUnitRootOwner = new Map<string, { part: string; bone: string; rootLabel: string }>();
3207
+ const rebindUnitMeshToHeadCarrier = (part: string): void => {
3208
+ const unitBone = turnUnitBone(part);
3209
+ const bound: string[] = [];
3210
+ const addBound = (bName: string): void => {
3211
+ if (!bound.includes(bName)) bound.push(bName);
3212
+ };
3213
+ for (const sl of finalSlots) {
3214
+ if (sl.name !== part && !sl.name.startsWith(`${part}__island`)) continue;
3215
+ const atts = skin[sl.name] ?? {};
3216
+ let hasWeights = false;
3217
+ for (const att of Object.values(atts)) {
3218
+ if ('type' in att && att.weights !== undefined && att.weights.length > 0) {
3219
+ hasWeights = true;
3220
+ for (const row of att.weights) {
3221
+ for (const w of row) addBound(w.bone);
3222
+ }
3223
+ }
3224
+ }
3225
+ if (!hasWeights) addBound(sl.bone);
3226
+ }
3227
+ const stillSl = slotByName.get(`${part}${STILL_SUFFIX}`);
3228
+ if (stillSl !== undefined) addBound(stillSl.bone);
3229
+ const uncarried: string[] = [];
3230
+ const sharedRoots = new Set<string>();
3231
+ let hasShared = false;
3232
+ for (const bName of bound) {
3233
+ if (bName === 'head' || bName === unitBone) continue;
3234
+ let cur = boneByName.get(bName);
3235
+ while (cur !== undefined && cur.parent !== undefined && cur.parent !== 'head' && !headCarriers.has(cur.parent)) {
3236
+ cur = boneByName.get(cur.parent);
3237
+ }
3238
+ if (cur === undefined || cur.parent === undefined || (cur.parent !== 'head' && !headCarriers.has(cur.parent)) || headCarriers.has(cur.name)) {
3239
+ uncarried.push(bName);
3240
+ continue;
3241
+ }
3242
+ const rootLabel = cur.name.endsWith(CONTROL_SUFFIX) ? cur.name.slice(0, -CONTROL_SUFFIX.length) : cur.name;
3243
+ const owner = headUnitRootOwner.get(cur.name);
3244
+ if (owner !== undefined && owner.part !== part) {
3245
+ hasShared = true;
3246
+ if (!sharedRoots.has(cur.name)) {
3247
+ sharedRoots.add(cur.name);
3248
+ const sharedDetail =
3249
+ owner.bone === bName
3250
+ ? `bone "${bName}"${bName === owner.rootLabel ? '' : ` (under "${owner.rootLabel}")`}`
3251
+ : `chain root "${owner.rootLabel}" ("${owner.part}" binds "${owner.bone}", "${part}" binds "${bName}")`;
3252
+ fail(
3253
+ 'CONFIG_TURN_UNIT_MESH_BONES',
3254
+ `config.turn.roles.${part}`,
3255
+ `declares "${part}" as "unit", and config.meshes.${part} shares ${sharedDetail} with "unit" mesh "${owner.part}" (config.turn.roles.${owner.part}); each "unit" mesh reparents its bound chain root under its own "<part>_unit" carrier, so two "unit" meshes cannot share a bone or chain under "head"`,
3256
+ );
3257
+ }
3258
+ } else if (owner === undefined) {
3259
+ headUnitRootOwner.set(cur.name, { part, bone: bName, rootLabel });
3260
+ }
3261
+ }
3262
+ if (uncarried.length > 0) {
3263
+ fail(
3264
+ 'CONFIG_TURN_UNIT_MESH_BONES',
3265
+ `config.turn.roles.${part}`,
3266
+ `declares "${part}" as "unit", and config.meshes.${part} binds bone(s) ${uncarried.map((b) => `"${b}"`).join(', ')} outside the "head" subtree, which cannot be carried by "${unitBone}" under "${FACESHIFT_BONE}"; bind a head "unit" mesh only to "head" or bones and chains under "head"`,
3267
+ );
3268
+ return;
3269
+ }
3270
+ if (hasShared) return;
3271
+ rebindPartToCarrier(part, unitBone);
3272
+ };
3273
+
3190
3274
  for (const [part, role] of Object.entries(roles)) {
3191
3275
  if (role === 'unit') {
3192
3276
  if (cfg.regions[part] !== undefined) {
@@ -3200,7 +3284,7 @@ export function buildWaistPairSource(
3200
3284
  const st = stills[part];
3201
3285
  if (st !== undefined) reparentFromHead(st.bone, FACESHIFT_BONE);
3202
3286
  } else if (cfg.meshes[part] !== undefined) {
3203
- rebindPartToCarrier(part, FACESHIFT_BONE);
3287
+ rebindUnitMeshToHeadCarrier(part);
3204
3288
  }
3205
3289
  } else if (role === 'rear' && hasRear) {
3206
3290
  if (cfg.regions[part] !== undefined) {
@@ -3230,8 +3314,13 @@ export function buildWaistPairSource(
3230
3314
  const bodyTransform = world.get(bodyRoot) as BoneTransform;
3231
3315
  const bodyTurnDeg = turn.get(bodyRoot) ?? 0;
3232
3316
  const surfBones: RigBone[] = [];
3317
+ const unitMeshBones: RigBone[] = [];
3233
3318
  for (const p of parts.parts) {
3234
- if (bodyRoles[p.name] !== 'surface') continue;
3319
+ if (bodyRoles[p.name] === 'unit' && cfg.meshes[p.name] !== undefined) {
3320
+ unitMeshBones.push({ name: turnUnitBone(p.name), parent: BODYSHIFT_BONE, x: 0, y: 0 });
3321
+ continue;
3322
+ }
3323
+ if (bodyRoles[p.name] !== 'surface' || cfg.meshes[p.name] !== undefined) continue;
3235
3324
  const [cols, rows] = resolveTurnGrid(bodySpec, p.name, cfg.turn);
3236
3325
  totalGridTriangles += 2 * (cols - 1) * (rows - 1);
3237
3326
  const cx = p.x + p.w / 2;
@@ -3251,6 +3340,7 @@ export function buildWaistPairSource(
3251
3340
  { name: BODYSHIFT_BONE, parent: bodyRoot, x: 0, y: 0 },
3252
3341
  ...(hasRear ? [{ name: BODY_REAR_SHIFT_BONE, parent: bodyRoot, x: 0, y: 0 }] : []),
3253
3342
  ...surfBones,
3343
+ ...unitMeshBones,
3254
3344
  ];
3255
3345
  bones.splice(bodyIdx + 1, 0, ...carriers);
3256
3346
  const bodyDialBone = bodySpec.slider ?? BODY_YAW_DIAL_BONE;
@@ -3259,21 +3349,29 @@ export function buildWaistPairSource(
3259
3349
  }
3260
3350
 
3261
3351
  const boneByName = new Map(bones.map((b) => [b.name, b]));
3352
+ const bodyCarriers = new Set<string>(carriers.map((b) => b.name));
3353
+ const assertNotBodyTurnCarrier = (boneName: string, targetParent: string): void => {
3354
+ if (bodyCarriers.has(boneName)) {
3355
+ throw new Error(`turn invariant violated: turn carrier "${boneName}" must never be reparented (target "${targetParent}")`);
3356
+ }
3357
+ };
3262
3358
  const torsoRoots = new Set<string>([bodyRoot, 'chest', 'hip', `${bodyRoot}${CONTROL_SUFFIX}`, `chest${CONTROL_SUFFIX}`, `hip${CONTROL_SUFFIX}`]);
3263
3359
  const headExclusion = new Set<string>(['head', `head${CONTROL_SUFFIX}`, 'neck', `neck${CONTROL_SUFFIX}`, FACESHIFT_BONE, REAR_SHIFT_BONE]);
3264
3360
  const reparentFromTorso = (boneName: string, targetParent: string): void => {
3361
+ assertNotBodyTurnCarrier(boneName, targetParent);
3265
3362
  if (torsoRoots.has(boneName) || headExclusion.has(boneName)) return;
3266
3363
  let cur = boneByName.get(boneName);
3267
3364
  while (
3268
3365
  cur !== undefined &&
3269
3366
  cur.parent !== undefined &&
3270
3367
  !torsoRoots.has(cur.parent) &&
3271
- cur.parent !== targetParent &&
3368
+ !bodyCarriers.has(cur.parent) &&
3272
3369
  !headExclusion.has(cur.parent)
3273
3370
  ) {
3274
3371
  cur = boneByName.get(cur.parent);
3275
3372
  }
3276
3373
  if (cur !== undefined && cur.parent !== undefined && torsoRoots.has(cur.parent) && !torsoRoots.has(cur.name) && !headExclusion.has(cur.name)) {
3374
+ assertNotBodyTurnCarrier(cur.name, targetParent);
3277
3375
  const oldParent = cur.parent;
3278
3376
  if (oldParent !== bodyRoot) {
3279
3377
  const oldTr = world.get(oldParent);
@@ -3295,30 +3393,119 @@ export function buildWaistPairSource(
3295
3393
  if (torsoRoots.has(stillSl.bone)) stillSl.bone = carrierBone;
3296
3394
  else reparentFromTorso(stillSl.bone, carrierBone);
3297
3395
  }
3298
- const atts = skin[part] ?? {};
3299
- for (const att of Object.values(atts)) {
3300
- if (!('type' in att) || att.weights === undefined) continue;
3301
- for (const row of att.weights) {
3302
- for (const w of row) {
3303
- if (torsoRoots.has(w.bone)) {
3304
- if (w.bone !== bodyRoot) {
3305
- const oldTr = world.get(w.bone);
3306
- if (oldTr !== undefined) {
3307
- const [wx, wy] = toWorld(oldTr, w.x, w.y);
3308
- const [lx, ly] = toBoneLocal(bodyTransform, wx, wy);
3309
- w.x = places(lx);
3310
- w.y = places(ly);
3396
+ for (const slotEntry of finalSlots) {
3397
+ if (slotEntry.name !== part && !slotEntry.name.startsWith(`${part}__island`)) continue;
3398
+ if (torsoRoots.has(slotEntry.bone)) slotEntry.bone = carrierBone;
3399
+ const atts = skin[slotEntry.name] ?? {};
3400
+ for (const att of Object.values(atts)) {
3401
+ if (!('type' in att) || att.weights === undefined) continue;
3402
+ for (const row of att.weights) {
3403
+ for (const w of row) {
3404
+ if (torsoRoots.has(w.bone)) {
3405
+ if (w.bone !== bodyRoot) {
3406
+ const oldTr = world.get(w.bone);
3407
+ if (oldTr !== undefined) {
3408
+ const [wx, wy] = toWorld(oldTr, w.x, w.y);
3409
+ const [lx, ly] = toBoneLocal(bodyTransform, wx, wy);
3410
+ w.x = places(lx);
3411
+ w.y = places(ly);
3412
+ }
3311
3413
  }
3414
+ w.bone = carrierBone;
3415
+ } else {
3416
+ reparentFromTorso(w.bone, carrierBone);
3312
3417
  }
3313
- w.bone = carrierBone;
3314
- } else {
3315
- reparentFromTorso(w.bone, carrierBone);
3316
3418
  }
3317
3419
  }
3318
3420
  }
3319
3421
  }
3320
3422
  };
3321
3423
 
3424
+ const bodyUnitRootOwner = new Map<string, { part: string; bone: string; rootLabel: string }>();
3425
+ const rebindBodyUnitMeshToCarrier = (part: string): void => {
3426
+ const unitBone = turnUnitBone(part);
3427
+ const bound: string[] = [];
3428
+ const addBound = (bName: string): void => {
3429
+ if (!bound.includes(bName)) bound.push(bName);
3430
+ };
3431
+ for (const sl of finalSlots) {
3432
+ if (sl.name !== part && !sl.name.startsWith(`${part}__island`)) continue;
3433
+ const atts = skin[sl.name] ?? {};
3434
+ let hasWeights = false;
3435
+ for (const att of Object.values(atts)) {
3436
+ if ('type' in att && att.weights !== undefined && att.weights.length > 0) {
3437
+ hasWeights = true;
3438
+ for (const row of att.weights) {
3439
+ for (const w of row) addBound(w.bone);
3440
+ }
3441
+ }
3442
+ }
3443
+ if (!hasWeights) addBound(sl.bone);
3444
+ }
3445
+ const stillSl = slotByName.get(`${part}${STILL_SUFFIX}`);
3446
+ if (stillSl !== undefined) addBound(stillSl.bone);
3447
+ const uncarried: string[] = [];
3448
+ const sharedRoots = new Set<string>();
3449
+ let hasShared = false;
3450
+ for (const bName of bound) {
3451
+ if (headExclusion.has(bName)) {
3452
+ uncarried.push(bName);
3453
+ continue;
3454
+ }
3455
+ if (torsoRoots.has(bName) || bName === unitBone) continue;
3456
+ let cur = boneByName.get(bName);
3457
+ while (
3458
+ cur !== undefined &&
3459
+ cur.parent !== undefined &&
3460
+ !torsoRoots.has(cur.parent) &&
3461
+ !bodyCarriers.has(cur.parent) &&
3462
+ !headExclusion.has(cur.parent)
3463
+ ) {
3464
+ cur = boneByName.get(cur.parent);
3465
+ }
3466
+ if (
3467
+ cur === undefined ||
3468
+ cur.parent === undefined ||
3469
+ (!torsoRoots.has(cur.parent) && !bodyCarriers.has(cur.parent)) ||
3470
+ torsoRoots.has(cur.name) ||
3471
+ headExclusion.has(cur.name) ||
3472
+ bodyCarriers.has(cur.name)
3473
+ ) {
3474
+ uncarried.push(bName);
3475
+ continue;
3476
+ }
3477
+ const rootLabel = cur.name.endsWith(CONTROL_SUFFIX) ? cur.name.slice(0, -CONTROL_SUFFIX.length) : cur.name;
3478
+ const owner = bodyUnitRootOwner.get(cur.name);
3479
+ if (owner !== undefined && owner.part !== part) {
3480
+ hasShared = true;
3481
+ if (!sharedRoots.has(cur.name)) {
3482
+ sharedRoots.add(cur.name);
3483
+ const sharedDetail =
3484
+ owner.bone === bName
3485
+ ? `bone "${bName}"${bName === owner.rootLabel ? '' : ` (under "${owner.rootLabel}")`}`
3486
+ : `chain root "${owner.rootLabel}" ("${owner.part}" binds "${owner.bone}", "${part}" binds "${bName}")`;
3487
+ fail(
3488
+ 'CONFIG_TURN_UNIT_MESH_BONES',
3489
+ `config.turn.body.roles.${part}`,
3490
+ `declares "${part}" as "unit", and config.meshes.${part} shares ${sharedDetail} with "unit" mesh "${owner.part}" (config.turn.body.roles.${owner.part}); each "unit" mesh reparents its bound chain root under its own "<part>_unit" carrier, so two "unit" meshes cannot share a bone or chain under "${bodyRoot}"`,
3491
+ );
3492
+ }
3493
+ } else if (owner === undefined) {
3494
+ bodyUnitRootOwner.set(cur.name, { part, bone: bName, rootLabel });
3495
+ }
3496
+ }
3497
+ if (uncarried.length > 0) {
3498
+ fail(
3499
+ 'CONFIG_TURN_UNIT_MESH_BONES',
3500
+ `config.turn.body.roles.${part}`,
3501
+ `declares "${part}" as "unit", and config.meshes.${part} binds bone(s) ${uncarried.map((b) => `"${b}"`).join(', ')} outside the "${bodyRoot}" torso subtree, which cannot be carried by "${unitBone}" under "${BODYSHIFT_BONE}"; bind a body "unit" mesh only to the torso root or bones and chains under it`,
3502
+ );
3503
+ return;
3504
+ }
3505
+ if (hasShared) return;
3506
+ rebindBodyPartToCarrier(part, unitBone);
3507
+ };
3508
+
3322
3509
  for (const [part, role] of Object.entries(bodyRoles)) {
3323
3510
  if (role === 'unit') {
3324
3511
  if (cfg.regions[part] !== undefined) {
@@ -3345,7 +3532,7 @@ export function buildWaistPairSource(
3345
3532
  const st = stills[part];
3346
3533
  if (st !== undefined) reparentFromTorso(st.bone, BODYSHIFT_BONE);
3347
3534
  } else if (cfg.meshes[part] !== undefined) {
3348
- rebindBodyPartToCarrier(part, BODYSHIFT_BONE);
3535
+ rebindBodyUnitMeshToCarrier(part);
3349
3536
  }
3350
3537
  } else if (role === 'rear' && hasRear) {
3351
3538
  if (cfg.regions[part] !== undefined) {
@@ -3474,6 +3661,7 @@ export function buildWaistPairSource(
3474
3661
  stills,
3475
3662
  boneLandmarks,
3476
3663
  hasAlternateFaceSet,
3664
+ surfaceMeshes: turnSurfaceMeshes(cfg, rig, parts.rig_size),
3477
3665
  });
3478
3666
  }
3479
3667
  bindFaceSurfaceDeform(motion, (merged) => {
@@ -3489,6 +3677,7 @@ export function buildWaistPairSource(
3489
3677
  stills,
3490
3678
  boneLandmarks,
3491
3679
  hasAlternateFaceSet,
3680
+ surfaceMeshes: turnSurfaceMeshes(cfg, rig, parts.rig_size),
3492
3681
  });
3493
3682
  }
3494
3683
  if (cfg.turn?.roles === undefined && (cfg.turn === undefined || cfg.turn.body === undefined || cfg.turn.depths !== undefined)) {
@@ -3986,3 +4175,24 @@ function refuseSharedWaistMotion(motion: MotionSpec, top: string, bone: string):
3986
4175
  if (record(value) && Array.isArray(value.tracks) && value.tracks.some((track) => record(track) && track.bone === bone)) refuse('RIG_WAIST_MOTION', `animation "${animation}" drives generated waist bone "${bone}"; original tracks must retain their authored targets`);
3987
4176
  }
3988
4177
  }
4178
+
4179
+ /** Final named bindings, including explicit islands; grid surfaces keep their Core path. */
4180
+ function turnSurfaceMeshes(cfg: CharacterConfig, rig: RigSpec, canvas: readonly [number, number]) {
4181
+ const meshes = [];
4182
+ for (const part of Object.keys(cfg.meshes)) {
4183
+ if (cfg.turn?.roles?.[part] !== 'surface' && cfg.turn?.body?.roles?.[part] !== 'surface') continue;
4184
+ for (const slot of rig.slots) {
4185
+ if (slot.name !== part && !slot.name.startsWith(`${part}__island`)) continue;
4186
+ for (const [attachment, att] of Object.entries(rig.skins.default[slot.name] ?? {})) {
4187
+ if (!('type' in att) || att.weights === undefined || att.weights.length === 0) {
4188
+ throw new PartsError([{ code: 'RIG_TURN_SURFACE_MESH_BINDINGS', object: `surface mesh "${slot.name}/${attachment}"`, detail: 'requires an authored weighted mesh with named bindings; a region or unresolved generator cannot carry weighted depth offsets' }]);
4189
+ }
4190
+ if (attachment !== part && !slot.name.startsWith(`${part}__island`)) {
4191
+ throw new PartsError([{ code: 'RIG_TURN_SURFACE_MESH_ATTACHMENT', object: `surface mesh "${slot.name}/${attachment}"`, detail: `requires the base drawing "${part}"; alternate drawings need their own registered depth sampling frame` }]);
4192
+ }
4193
+ meshes.push({ part, slot: slot.name, attachment, weights: att.weights, canvas });
4194
+ }
4195
+ }
4196
+ }
4197
+ return meshes;
4198
+ }
package/src/turn.ts CHANGED
@@ -28,8 +28,8 @@
28
28
  * that the depth maps do not carry relief inside a layer, so a part moves as
29
29
  * one piece. Pure: no file, no clock.
30
30
  */
31
- import { computeWorldTransforms, toBoneLocalVector, toWorld, type BoneTransform } from './coords.ts';
32
- import { extendDepthSilhouette, type PartDepthReference } from './depthsheets.ts';
31
+ import { computeWorldTransforms, setupToPaintingPoint, toBoneLocalVector, toWorld, type BoneTransform } from './coords.ts';
32
+ import { extendDepthSilhouette, sampleDepthFloat, type PartDepthReference } from './depthsheets.ts';
33
33
  import { type Problem, refuseIfAny } from './errors.ts';
34
34
  import type { Raster } from './raster/index.ts';
35
35
  import { pyRound } from './round.ts';
@@ -245,6 +245,11 @@ export function turnSurfaceBone(part: string): string {
245
245
  return `${part}_surface`;
246
246
  }
247
247
 
248
+ /** The carrier bone that carries a 2.5D `'unit'` mesh part (`<part>_unit`) under `faceshift` / `bodyshift` (#790). */
249
+ export function turnUnitBone(part: string): string {
250
+ return `${part}_unit`;
251
+ }
252
+
248
253
  /** Optional 2.5D body-yaw turn block under `config.turn.body` (#787). */
249
254
  export interface TurnBodySpec {
250
255
  pivot?: number;
@@ -1475,6 +1480,16 @@ export interface Depth25DTurnOptions {
1475
1480
  stills: Readonly<Record<string, { row: number; bone: string }>>;
1476
1481
  boneLandmarks: ReadonlyMap<string, readonly [number, number]>;
1477
1482
  hasAlternateFaceSet: boolean;
1483
+ /** Existing weighted attachments; offsets are emitted per binding, never per UV. */
1484
+ surfaceMeshes?: ReadonlyArray<{
1485
+ part: string;
1486
+ slot: string;
1487
+ attachment: string;
1488
+ weights: ReadonlyArray<ReadonlyArray<{ bone: string; x: number; y: number; weight: number }>>;
1489
+ canvas: readonly [number, number];
1490
+ /** Every attachment of a part containing a blended mesh carries its own group mask. */
1491
+ groups?: ReadonlyMap<string, 'head' | 'body'>;
1492
+ }>;
1478
1493
  }
1479
1494
 
1480
1495
  interface Depth25DGroupSpec {
@@ -1596,10 +1611,16 @@ function buildDepth25DTurnGroup(
1596
1611
  for (const [part, role] of Object.entries(roles)) {
1597
1612
  if (role !== 'unit') continue;
1598
1613
  const regSpec = opts.regions[part];
1599
- if (regSpec === undefined) continue;
1600
- const baseBone = typeof regSpec === 'string' ? regSpec : regSpec.bone;
1601
- const stillBone = opts.stills[part]?.bone;
1602
- const candidateBones = [baseBone, ...(stillBone === undefined ? [] : [stillBone])].filter((b) => carrierChildren.has(b));
1614
+ let baseBone: string | undefined;
1615
+ let candidateBones: string[] = [];
1616
+ if (regSpec !== undefined) {
1617
+ baseBone = typeof regSpec === 'string' ? regSpec : regSpec.bone;
1618
+ const stillBone = opts.stills[part]?.bone;
1619
+ candidateBones = [baseBone, ...(stillBone === undefined ? [] : [stillBone])].filter((b) => carrierChildren.has(b));
1620
+ } else {
1621
+ const uBone = turnUnitBone(part);
1622
+ if (carrierChildren.has(uBone)) candidateBones = [uBone];
1623
+ }
1603
1624
  if (candidateBones.length === 0) continue;
1604
1625
 
1605
1626
  for (const bName of candidateBones) {
@@ -1611,7 +1632,26 @@ function buildDepth25DTurnGroup(
1611
1632
  } else if (typeof explicitBoneDepth === 'number' && Number.isFinite(explicitBoneDepth)) {
1612
1633
  resolved = explicitBoneDepth;
1613
1634
  } else if (primarySurface !== undefined) {
1614
- const pt = opts.boneLandmarks.get(bName) ?? opts.boneLandmarks.get(baseBone);
1635
+ let pt: readonly [number, number] | undefined =
1636
+ opts.boneLandmarks.get(bName) ??
1637
+ (baseBone === undefined ? undefined : opts.boneLandmarks.get(baseBone));
1638
+ if (pt === undefined && regSpec === undefined) {
1639
+ const childPts: Array<readonly [number, number]> = [];
1640
+ for (const child of rig.bones) {
1641
+ if (child.parent !== bName) continue;
1642
+ const bare = child.name.endsWith('_ctl') ? child.name.slice(0, -4) : child.name;
1643
+ const cp = opts.boneLandmarks.get(child.name) ?? opts.boneLandmarks.get(bare);
1644
+ if (cp !== undefined) childPts.push(cp);
1645
+ }
1646
+ if (childPts.length > 0) {
1647
+ const sx = childPts.reduce((acc, p) => acc + p[0], 0) / childPts.length;
1648
+ const sy = childPts.reduce((acc, p) => acc + p[1], 0) / childPts.length;
1649
+ pt = [sx, sy];
1650
+ } else {
1651
+ const partRec = partMap.get(part);
1652
+ if (partRec !== undefined) pt = [partRec.x + partRec.w / 2, partRec.y + partRec.h / 2];
1653
+ }
1654
+ }
1615
1655
  if (pt !== undefined) {
1616
1656
  const { rec, ext, zRef } = primarySurface;
1617
1657
  const padX = Math.floor((ext.width - rec.w) / 2);
@@ -1722,6 +1762,7 @@ function buildDepth25DTurnGroup(
1722
1762
  });
1723
1763
  }
1724
1764
  for (const [part, { zRef }] of surfaceSheets) {
1765
+ if (opts.surfaceMeshes?.some((m) => m.part === part)) continue;
1725
1766
  const surfShift = pyRound(-zRef, 4);
1726
1767
  if (surfShift !== 0) {
1727
1768
  tracks.push({
@@ -1770,7 +1811,63 @@ function buildDepth25DTurnGroup(
1770
1811
  };
1771
1812
  }>;
1772
1813
  }> = [];
1773
- for (const part of surfaceSheets.keys()) {
1814
+ for (const [part, { rec, ext, zRef }] of surfaceSheets) {
1815
+ const authored = opts.surfaceMeshes?.filter((m) => m.part === part) ?? [];
1816
+ if (authored.length > 0) {
1817
+ const world = computeWorldTransforms(rig.bones);
1818
+ for (const mesh of authored) {
1819
+ // An all-zero timeline can overwrite another slider's deform (Core A40).
1820
+ // A sibling with no positive binding in this group owns no timeline here.
1821
+ const active = mesh.groups === undefined || [...mesh.groups.values()].includes(group.fieldPrefix === 'config.turn' ? 'head' : 'body');
1822
+ const vertices = mesh.weights.map((row, index) => {
1823
+ let wx = 0, wy = 0, total = 0;
1824
+ for (const w of row) {
1825
+ const frame = world.get(w.bone);
1826
+ if (frame === undefined) {
1827
+ problems.push({ code: 'RIG_TURN_SURFACE_MESH_BINDINGS', object: `surface mesh "${mesh.slot}/${mesh.attachment}" vertex ${index}`, detail: `names missing bone "${w.bone}"; every influence must resolve in the final setup` });
1828
+ continue;
1829
+ }
1830
+ // A unit/rear mesh sharing this root would move our bindings too.
1831
+ let ancestor = rig.bones.find((b) => b.name === w.bone);
1832
+ while (ancestor !== undefined) {
1833
+ if ([FACESHIFT_BONE, REAR_SHIFT_BONE, BODYSHIFT_BONE, BODY_REAR_SHIFT_BONE].includes(ancestor.name)) {
1834
+ problems.push({ code: 'RIG_TURN_SURFACE_MESH_BINDINGS', object: `${group.fieldPrefix}.roles.${part}`, detail: `binds "${w.bone}" through turn carrier "${ancestor.name}" shared with another role; surface mesh bindings must retain their authored frame` });
1835
+ break;
1836
+ }
1837
+ ancestor = rig.bones.find((b) => b.name === ancestor?.parent);
1838
+ }
1839
+ const [x, y] = toWorld(frame, w.x, w.y);
1840
+ wx += x * w.weight; wy += y * w.weight; total += w.weight;
1841
+ }
1842
+ if (!Number.isFinite(total) || Math.abs(total - 1) > 0.0001) {
1843
+ problems.push({ code: 'RIG_TURN_SURFACE_MESH_BINDINGS', object: `surface mesh "${mesh.slot}/${mesh.attachment}" vertex ${index}`, detail: `has influence sum ${total}; weights closing at 1 are required to sample a setup position` });
1844
+ }
1845
+ const [cx, cy] = setupToPaintingPoint([wx, wy], mesh.canvas, mesh.canvas);
1846
+ const z = levelToDepthZ(sampleDepthFloat(ext, cx - rec.x, cy - rec.y), rec.depth);
1847
+ return { row, depth: pivot + z - zRef };
1848
+ });
1849
+ if (problems.length > startProblems || !active) continue;
1850
+ deform.push({
1851
+ slot: mesh.slot,
1852
+ attachment: mesh.attachment,
1853
+ keys: keyList.map(({ t, deg }) => deg === 0 ? { t } : {
1854
+ t,
1855
+ // Spine's weighted deform is one bind-space pair per influence.
1856
+ // Do not multiply by weight: the runtime performs that sum once.
1857
+ vertices: vertices.flatMap(({ row, depth }) => {
1858
+ const d = -depth * Math.sin(deg * Math.PI / 180);
1859
+ return row.flatMap((w) => {
1860
+ if (mesh.groups !== undefined && (w.weight === 0 || mesh.groups.get(w.bone) !== (group.fieldPrefix === 'config.turn' ? 'head' : 'body'))) return [0, 0];
1861
+ const frame = world.get(w.bone)!; // every influence resolved before emitting keys
1862
+ const [x, y] = toBoneLocalVector(frame, kind === 'yaw' ? d : 0, kind === 'pitch' ? d : 0);
1863
+ return [pyRound(x, 6), pyRound(y, 6)];
1864
+ });
1865
+ }),
1866
+ }),
1867
+ });
1868
+ }
1869
+ continue;
1870
+ }
1774
1871
  deform.push({
1775
1872
  slot: part,
1776
1873
  attachment: part,
@@ -1864,6 +1961,60 @@ export function buildDepth25DTurn(
1864
1961
  const problems: Problem[] = [];
1865
1962
  const { yaw: yawMax, pitch: pitchMax } = resolveTurnBands(opts.turn);
1866
1963
 
1964
+ // Only a surface opt-in spanning both authored subtrees changes paths (#796).
1965
+ // Single-group meshes keep #795's role and bytes, including explicit islands.
1966
+ const parents = new Map(rig.bones.map((b) => [b.name, b.parent]));
1967
+ const bodyRoot = opts.turn.body?.bone ?? (parents.has('chest') ? 'chest' : 'hip');
1968
+ const descends = (bone: string, root: string): boolean => {
1969
+ const seen = new Set<string>();
1970
+ for (let cur: string | undefined = bone; cur !== undefined && !seen.has(cur); cur = parents.get(cur)) {
1971
+ if (cur === root) return true;
1972
+ seen.add(cur);
1973
+ }
1974
+ return false;
1975
+ };
1976
+ const blended = new Set<string>();
1977
+ const classified = opts.surfaceMeshes?.map((mesh) => {
1978
+ const groups = new Map<string, 'head' | 'body'>();
1979
+ const outside = new Set<string>();
1980
+ for (const w of mesh.weights.flat()) {
1981
+ if (w.weight <= 0) continue;
1982
+ if (descends(w.bone, 'head')) groups.set(w.bone, 'head');
1983
+ else if (descends(w.bone, bodyRoot)) groups.set(w.bone, 'body');
1984
+ else outside.add(w.bone);
1985
+ }
1986
+ if (new Set(groups.values()).size === 2) blended.add(mesh.part);
1987
+ return { mesh, groups, outside };
1988
+ });
1989
+ // A part's role covers every island, but each attachment keeps its own mask.
1990
+ // Without a blended attachment the explicit role still owns the legacy path.
1991
+ const surfaceMeshes = classified?.map(({ mesh, groups, outside }) => {
1992
+ if (!blended.has(mesh.part)) return mesh;
1993
+ if (opts.turn.roles === undefined || opts.turn.body === undefined || outside.size > 0 || descends(bodyRoot, 'head')) {
1994
+ problems.push({
1995
+ code: 'RIG_TURN_SURFACE_MESH_GROUPS', object: `surface mesh "${mesh.slot}/${mesh.attachment}"`,
1996
+ detail: `belongs to a part with blended head and body bindings${outside.size === 0 ? '' : ` with ungrouped bone(s) ${[...outside].map(b => `"${b}"`).join(', ')}`}; declare both config.turn.roles and config.turn.body with a body root outside head, and bind every influence to one of those subtrees`,
1997
+ });
1998
+ return mesh;
1999
+ }
2000
+ // A second declaration cannot ask the same attachment to be both a sampled
2001
+ // surface and a unit/rear carrier. No binding is reparented here.
2002
+ const roles = [opts.turn.roles[mesh.part], opts.turn.body.roles[mesh.part]];
2003
+ if (roles.some(role => role !== undefined && role !== 'surface')) {
2004
+ problems.push({ code: 'RIG_TURN_SURFACE_MESH_GROUPS', object: `surface mesh "${mesh.slot}/${mesh.attachment}"`, detail: 'declares a unit/rear role as well as surface across the head and body groups; declare surface in one or both groups so its authored frames are retained' });
2005
+ return mesh;
2006
+ }
2007
+ return { ...mesh, groups };
2008
+ });
2009
+ refuseIfAny(problems);
2010
+ if (blended.size > 0) {
2011
+ const surfaceRoles = Object.fromEntries([...blended].map(part => [part, 'surface' as const]));
2012
+ opts = { ...opts, surfaceMeshes, turn: { ...opts.turn,
2013
+ roles: { ...opts.turn.roles, ...surfaceRoles },
2014
+ body: { ...opts.turn.body!, roles: { ...opts.turn.body!.roles, ...surfaceRoles } },
2015
+ } };
2016
+ }
2017
+
1867
2018
  if (opts.turn.roles !== undefined) {
1868
2019
  buildDepth25DTurnGroup(
1869
2020
  rig,