@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/config.ts CHANGED
@@ -99,7 +99,8 @@ import { edgeLength } from './length.ts';
99
99
  import { setFocusProblems } from './setfocus.ts';
100
100
  import { isSkeletonName, KEYPOINT_NAMES, type KeypointName, type PosePoints, scaledPoints, SKELETON_NAMES, type SkeletonName } from './skeleton.ts';
101
101
  import { acceptedTagNames, AUTHOR_LABEL_RULE, AUTHOR_PREFIX, readLayerTag } from './tags.ts';
102
- import { BODY_REAR_SHIFT_BONE, BODY_YAW_DIAL_BONE, BODYSHIFT_BONE, EAR_DEPTH_RANGE, FACE_DEFORM_FRACTIONS, FACE_DEFORM_RANGES, type FaceDeformKey, FACE_RATED_PITCH_BAND, FACE_RATED_YAW_BAND, FACESHIFT_BONE, PITCH_DIAL_BONE, REAR_SHIFT_BONE, TURN_BONE, TURN_ROLES, type TurnSpec, turnNearest, turnSurfaceBone, YAW_DIAL_BONE } from './turn.ts';
102
+ import { BODYSHIFT_BONE, BODY_REAR_SHIFT_BONE, BODY_YAW_DIAL_BONE, EAR_DEPTH_RANGE, FACESHIFT_BONE, FACE_DEFORM_FRACTIONS, FACE_DEFORM_RANGES, FACE_RATED_PITCH_BAND, FACE_RATED_YAW_BAND, type FaceDeformKey, PITCH_DIAL_BONE, REAR_SHIFT_BONE, TURN_BONE, TURN_ROLES, type TurnRole, type TurnSpec, YAW_DIAL_BONE, turnNearest, turnSurfaceBone, turnUnitBone } from './turn.ts';
103
+ export type { TurnSpec };
103
104
  import { FLOOR_FORMS, type FloorForm, type MeshInfluences } from './weights.ts';
104
105
 
105
106
  export type Point = [number, number];
@@ -791,30 +792,244 @@ export interface PartBinding {
791
792
  */
792
793
  export function partBoundBones(b: PartBinding): Map<string, string[]> {
793
794
  const chains = new Map<string, string[]>();
794
- for (const e of b.bones) if ('chain' in e) chains.set(e.chain, e.points.map((_, k) => `${e.chain}${k}`));
795
+ for (const e of Array.isArray(b.bones) ? b.bones : []) {
796
+ if (isPlainObject(e) && 'chain' in e && typeof e.chain === 'string' && Array.isArray(e.points)) {
797
+ chains.set(e.chain, e.points.map((_, k) => `${e.chain}${k}`));
798
+ }
799
+ }
795
800
  const out = new Map<string, string[]>();
796
801
  const bind = (part: string, bone: string): void => {
797
802
  const list = out.get(part) ?? [];
798
803
  if (!list.includes(bone)) list.push(bone);
799
804
  out.set(part, list);
800
805
  };
801
- for (const [part, m] of Object.entries(b.meshes)) {
802
- if ('explicit' in m) {
803
- for (const row of explicitWeightRows(m)) for (const w of row) bind(part, w.bone);
804
- if (m.explicit.islands !== undefined) for (const bName of explicitSlotBones(m)) bind(part, bName);
805
- continue;
806
+ if (isPlainObject(b.meshes)) {
807
+ for (const [part, m] of Object.entries(b.meshes)) {
808
+ if (isRecordKey(part) || !isPlainObject(m)) continue;
809
+ if ('explicit' in m && isPlainObject(m.explicit)) {
810
+ const addWeights = (ws: Json): void => {
811
+ if (!Array.isArray(ws)) return;
812
+ for (const row of ws) {
813
+ if (!Array.isArray(row)) continue;
814
+ for (const w of row) {
815
+ if (isPlainObject(w) && typeof w.bone === 'string') bind(part, w.bone);
816
+ }
817
+ }
818
+ };
819
+ if (Array.isArray(m.explicit.islands)) {
820
+ for (const isl of m.explicit.islands) {
821
+ if (isPlainObject(isl)) addWeights(isl.weights);
822
+ }
823
+ const seg0 =
824
+ Array.isArray(m.segments) && m.segments.length > 0
825
+ ? typeof m.segments[0] === 'string'
826
+ ? m.segments[0]
827
+ : Array.isArray(m.segments[0]) && typeof m.segments[0][0] === 'string'
828
+ ? m.segments[0][0]
829
+ : undefined
830
+ : undefined;
831
+ for (const isl of m.explicit.islands) {
832
+ if (!isPlainObject(isl)) continue;
833
+ const bName = typeof isl.bone === 'string' ? isl.bone : seg0;
834
+ if (bName !== undefined) bind(part, bName);
835
+ }
836
+ } else {
837
+ addWeights(m.explicit.weights);
838
+ }
839
+ continue;
840
+ }
841
+ if (Array.isArray(m.segments)) {
842
+ for (const sg of m.segments) {
843
+ if (typeof sg === 'string') {
844
+ for (const l of chains.get(sg) ?? [sg]) bind(part, l);
845
+ } else if (Array.isArray(sg) && typeof sg[0] === 'string') {
846
+ bind(part, sg[0]);
847
+ }
848
+ }
849
+ }
850
+ if ('contour' in m && isPlainObject(m.contour)) {
851
+ if (Array.isArray(m.contour.regions)) {
852
+ for (const rg of m.contour.regions) {
853
+ if (isPlainObject(rg) && typeof rg.bone === 'string') bind(part, rg.bone);
854
+ }
855
+ }
856
+ if (isPlainObject(m.contour.bust)) {
857
+ bind(part, typeof m.contour.bust.bone_r === 'string' ? m.contour.bust.bone_r : DEFAULT_BUST_BONE_R);
858
+ bind(part, typeof m.contour.bust.bone_l === 'string' ? m.contour.bust.bone_l : DEFAULT_BUST_BONE_L);
859
+ }
860
+ }
861
+ if ('auto' in m && isPlainObject(m.auto) && Array.isArray(m.auto.regions)) {
862
+ for (const rg of m.auto.regions) {
863
+ if (isPlainObject(rg) && typeof rg.bone === 'string') bind(part, rg.bone);
864
+ }
865
+ }
806
866
  }
807
- for (const sg of m.segments) {
808
- if (typeof sg !== 'string') bind(part, sg[0]);
809
- else for (const l of chains.get(sg) ?? [sg]) bind(part, l);
867
+ }
868
+ if (isPlainObject(b.regions)) {
869
+ for (const [part, region] of Object.entries(b.regions)) {
870
+ if (isRecordKey(part)) continue;
871
+ const bone = rawRegionBone(region);
872
+ if (typeof bone === 'string') bind(part, bone);
810
873
  }
811
- if ('contour' in m) for (const rg of contourRegionsOf(m.contour)) bind(part, rg.bone);
812
- if ('auto' in m) for (const rg of m.auto.regions ?? []) if (weightsABone(rg)) bind(part, rg.bone);
813
874
  }
814
- for (const [part, region] of Object.entries(b.regions)) bind(part, regionBone(region));
815
875
  return out;
816
876
  }
817
877
 
878
+ /**
879
+ * Issue #791: whether a turn moves two parts relative to each other — two parts
880
+ * with different turn roles or carriers (`config.turn.roles`,
881
+ * `config.turn.body.roles`, `config.turn.depths`), or a part with a physics
882
+ * chain (`config.constraints` with `type: "physics"`) over another part.
883
+ * Returns null when `config.turn` is absent, so a rig without a turn block is
884
+ * untouched.
885
+ */
886
+ export function turnMovingPartPair(
887
+ cfg: {
888
+ assemble?: CharacterConfig['assemble'];
889
+ turn?: TurnSpec;
890
+ bones?: BoneEntry[];
891
+ meshes?: Record<string, MeshSpec>;
892
+ regions?: Record<string, RegionSpec>;
893
+ limbs?: Record<string, Limb>;
894
+ constraints?: ConfigConstraint[];
895
+ },
896
+ ): ((a: string, b: string) => boolean) | null {
897
+ const turn = cfg.turn;
898
+ if (!isPlainObject(turn)) return null;
899
+
900
+ const sourceOf = new Map<string, string>();
901
+ for (const c of cfg.assemble?.cuts ?? []) {
902
+ if (isPlainObject(c) && typeof c.into === 'string' && typeof c.from === 'string') sourceOf.set(c.into, c.from);
903
+ }
904
+ if (isPlainObject(cfg.limbs)) {
905
+ for (const limb of Object.values(cfg.limbs)) {
906
+ if (!isPlainObject(limb) || !Array.isArray(limb.segments)) continue;
907
+ for (const sg of limb.segments) {
908
+ if (!isPlainObject(sg) || typeof sg.part !== 'string' || typeof sg.from !== 'string') continue;
909
+ sourceOf.set(sg.part, sg.from);
910
+ if (isPlainObject(sg.hybrid) && typeof sg.hybrid.part === 'string') sourceOf.set(sg.hybrid.part, sg.from);
911
+ }
912
+ }
913
+ }
914
+ const baseName = (p: string): string => {
915
+ let cur = p;
916
+ const seen = new Set<string>();
917
+ while (sourceOf.has(cur) && !seen.has(cur)) {
918
+ seen.add(cur);
919
+ cur = sourceOf.get(cur) as string;
920
+ }
921
+ return cur;
922
+ };
923
+
924
+ const boneEntries = Array.isArray(cfg.bones) ? cfg.bones.filter(isPlainObject) : [];
925
+ const parentOf = new Map<string, string>();
926
+ for (const e of boneEntries) {
927
+ if ('chain' in e && typeof e.chain === 'string' && Array.isArray(e.points)) {
928
+ e.points.forEach((_, k) => parentOf.set(`${e.chain}${k}`, k === 0 ? e.parent : `${e.chain}${k - 1}`));
929
+ } else if ('name' in e && typeof e.name === 'string' && typeof e.parent === 'string') {
930
+ parentOf.set(e.name, e.parent);
931
+ }
932
+ }
933
+ const physicsBones = new Set<string>();
934
+ if (Array.isArray(cfg.constraints)) {
935
+ for (const c of cfg.constraints) {
936
+ if (isPlainObject(c) && c.type === 'physics' && typeof c.bone === 'string') physicsBones.add(c.bone);
937
+ }
938
+ }
939
+ for (const b of parentOf.keys()) {
940
+ let cur: string | undefined = b;
941
+ const seen = new Set<string>();
942
+ while (cur !== undefined && !seen.has(cur)) {
943
+ if (physicsBones.has(cur)) {
944
+ physicsBones.add(b);
945
+ break;
946
+ }
947
+ seen.add(cur);
948
+ cur = parentOf.get(cur);
949
+ }
950
+ }
951
+
952
+ const meshParts = isPlainObject(cfg.meshes)
953
+ ? new Set(Object.keys(cfg.meshes).filter((k) => !isRecordKey(k)))
954
+ : new Set<string>();
955
+ const isMeshPart = (p: string): boolean => meshParts.has(p) || meshParts.has(baseName(p));
956
+
957
+ const bound =
958
+ isPlainObject(cfg.meshes) || isPlainObject(cfg.regions)
959
+ ? partBoundBones({
960
+ bones: boneEntries as BoneEntry[],
961
+ meshes: isPlainObject(cfg.meshes) ? (cfg.meshes as Record<string, MeshSpec>) : {},
962
+ regions: isPlainObject(cfg.regions) ? (cfg.regions as Record<string, RegionSpec>) : {},
963
+ })
964
+ : new Map<string, string[]>();
965
+ if (isPlainObject(cfg.limbs)) {
966
+ for (const limb of Object.values(cfg.limbs)) {
967
+ if (!isPlainObject(limb) || !Array.isArray(limb.segments)) continue;
968
+ for (const sg of limb.segments) {
969
+ if (!isPlainObject(sg) || typeof sg.part !== 'string' || typeof sg.bone !== 'string') continue;
970
+ if (!bound.has(sg.part)) bound.set(sg.part, [sg.bone]);
971
+ if (isPlainObject(sg.hybrid) && typeof sg.hybrid.part === 'string' && !bound.has(sg.hybrid.part)) {
972
+ bound.set(sg.hybrid.part, [sg.bone]);
973
+ }
974
+ }
975
+ }
976
+ }
977
+ const bonesOf = (p: string): readonly string[] => bound.get(p) ?? bound.get(baseName(p)) ?? [];
978
+ const sameNonEmptyBones = (a: readonly string[], b: readonly string[]): boolean =>
979
+ a.length > 0 && a.length === b.length && a.every((x, i) => x === b[i]);
980
+
981
+ const roleGroups: Array<{ roles: Readonly<Record<string, TurnRole>>; unitDepths?: Readonly<Record<string, number>> }> = [];
982
+ if (isPlainObject(turn.roles)) {
983
+ roleGroups.push({
984
+ roles: turn.roles as Readonly<Record<string, TurnRole>>,
985
+ ...(isPlainObject(turn.unitDepths) ? { unitDepths: turn.unitDepths as Readonly<Record<string, number>> } : {}),
986
+ });
987
+ }
988
+ if (isPlainObject(turn.body) && isPlainObject(turn.body.roles)) {
989
+ roleGroups.push({
990
+ roles: turn.body.roles as Readonly<Record<string, TurnRole>>,
991
+ ...(isPlainObject(turn.body.unitDepths) ? { unitDepths: turn.body.unitDepths as Readonly<Record<string, number>> } : {}),
992
+ });
993
+ }
994
+ const depths = isPlainObject(turn.depths) ? (turn.depths as Readonly<Record<string, number>>) : null;
995
+ const pivot = typeof turn.pivot === 'number' && Number.isFinite(turn.pivot) ? turn.pivot : null;
996
+
997
+ return (a: string, b: string): boolean => {
998
+ if (a === b) return false;
999
+ const bA = bonesOf(a);
1000
+ const bB = bonesOf(b);
1001
+ const hasPhysA = bA.some((x) => physicsBones.has(x));
1002
+ const hasPhysB = bB.some((x) => physicsBones.has(x));
1003
+ if ((hasPhysA || hasPhysB) && !(bA.length === 1 && sameNonEmptyBones(bA, bB))) return true;
1004
+
1005
+ for (const g of roleGroups) {
1006
+ const rA = g.roles[a] ?? g.roles[baseName(a)];
1007
+ const rB = g.roles[b] ?? g.roles[baseName(b)];
1008
+ if (rA === undefined && rB === undefined) continue;
1009
+ if (rA !== rB) return true;
1010
+ if (rA === 'surface') return true;
1011
+ if (rA === 'unit' && (isMeshPart(a) || isMeshPart(b) || !sameNonEmptyBones(bA, bB))) return true;
1012
+ const ud = g.unitDepths;
1013
+ if (ud !== undefined) {
1014
+ const dA = ud[a] ?? ud[baseName(a)] ?? (bA.length === 1 ? ud[bA[0]] : undefined);
1015
+ const dB = ud[b] ?? ud[baseName(b)] ?? (bB.length === 1 ? ud[bB[0]] : undefined);
1016
+ if (dA !== dB) return true;
1017
+ }
1018
+ if ((bA.length > 0 || bB.length > 0) && !sameNonEmptyBones(bA, bB)) return true;
1019
+ }
1020
+
1021
+ if (depths !== null) {
1022
+ const rawA = depths[a] ?? depths[baseName(a)];
1023
+ const rawB = depths[b] ?? depths[baseName(b)];
1024
+ const effA = typeof rawA === 'number' && Number.isFinite(rawA) && rawA !== pivot ? rawA : null;
1025
+ const effB = typeof rawB === 'number' && Number.isFinite(rawB) && rawB !== pivot ? rawB : null;
1026
+ if (effA !== effB) return true;
1027
+ }
1028
+
1029
+ return false;
1030
+ };
1031
+ }
1032
+
818
1033
  /**
819
1034
  * The bones a part can own (issue #535): every chain link, and every bone no
820
1035
  * other bone hangs from. A trunk bone — `head`, `chest`, anything with a child —
@@ -1410,6 +1625,12 @@ export interface AssembleConfig {
1410
1625
  /** Issue #349: read with `bones` (the joints are the bones' origins) when present. */
1411
1626
  limbs?: Record<string, Limb>;
1412
1627
  bones?: BoneEntry[];
1628
+ /** Issue #791: read with `turn` so `assemble` leaves moving pairs' fringes and seams alone. */
1629
+ meshes?: Record<string, MeshSpec>;
1630
+ regions?: Record<string, RegionSpec>;
1631
+ constraints?: ConfigConstraint[];
1632
+ motion?: Motion;
1633
+ turn?: TurnSpec;
1413
1634
  motion_seams?: MotionSeamDeclaration[];
1414
1635
  /** Issue #354: the `rig_scale` `propose` drafted the rig sections at, held equal to `assemble.rig_scale` when present. */
1415
1636
  proposed_rig_scale?: number;
@@ -1488,10 +1709,25 @@ function parseEarlyConfigFrom(raw: Json, door: EarlyDoor, base: string | null):
1488
1709
  if (isPlainObject(t.assemble) && 'alternates' in t.assemble) {
1489
1710
  checkAlternates(c, t.assemble.alternates, made, limbs, names?.bones ?? null, names?.chains ?? null, t.regions, t.meshes);
1490
1711
  }
1712
+ const output = new Set([...made.parts.filter(n => !limbs?.consumed.has(n)), ...made.patches, ...made.cuts, ...(limbs?.parts.keys() ?? [])]);
1491
1713
  if ('motion_seams' in t) {
1492
- const output = new Set([...made.parts.filter(n => !limbs?.consumed.has(n)), ...made.patches, ...made.cuts, ...(limbs?.parts.keys() ?? [])]);
1493
1714
  c.problems.push(...motionSeamProblems(t.motion_seams, output, 'config.motion_seams', 'CONFIG_MOTION_SEAM'));
1494
1715
  }
1716
+ if ('turn' in t) {
1717
+ if ('bones' in t && names === null) names = checkBones(c, t.bones);
1718
+ const attached = 'meshes' in t || 'regions' in t ? attachedParts(t.meshes, t.regions) : output;
1719
+ const hasAltFace = hasAlternateFaceSet(t.assemble, [...made.parts, ...made.cuts]);
1720
+ const declaredSliders = new Set<string>();
1721
+ if (Array.isArray(t.constraints)) {
1722
+ for (const entry of t.constraints) {
1723
+ if (isPlainObject(entry) && entry.type === 'slider' && typeof entry.name === 'string' && entry.name.length > 0) {
1724
+ declaredSliders.add(entry.name);
1725
+ }
1726
+ }
1727
+ }
1728
+ const meshParts = isPlainObject(t.meshes) ? new Set(Object.keys(t.meshes).filter((k) => !isRecordKey(k))) : new Set<string>();
1729
+ checkTurn(c, t.turn, attached, names?.bones ?? new Set(['root', 'head', 'chest', 'hip']), hasAltFace, made.parts, declaredSliders, meshParts);
1730
+ }
1495
1731
  }
1496
1732
  if ('cloth' in t) checkCloth(c, t.cloth);
1497
1733
  const pose = base === null ? null : poseBeside(c, t.generation, base);
@@ -1706,7 +1942,7 @@ function parseConfigFrom(raw: Json, base: string | null): { config: CharacterCon
1706
1942
  }
1707
1943
  }
1708
1944
  const meshParts = isPlainObject(t.meshes) ? new Set(Object.keys(t.meshes).filter((k) => !isRecordKey(k))) : new Set<string>();
1709
- if ('turn' in t) checkTurn(c, t.turn, attached, names.bones, hasAltFace, parts, declaredSliders, meshParts);
1945
+ if ('turn' in t) checkTurn(c, t.turn, attached, names.bones, hasAltFace, parts, declaredSliders, meshParts, t.meshes, names.chains, names.parents);
1710
1946
  if ('scene' in t) checkScene(c, t.scene);
1711
1947
  if ('cloth' in t) checkCloth(c, t.cloth);
1712
1948
  if ('requirements' in t && c.string('config.requirements', t.requirements) && base !== null) checkRequirementsFile(c, resolve(base, t.requirements));
@@ -4401,8 +4637,97 @@ function checkTurn(
4401
4637
  parts: readonly string[] = [],
4402
4638
  declaredSliders: ReadonlySet<string> = new Set(),
4403
4639
  meshParts: ReadonlySet<string> = new Set(),
4640
+ rawMeshes: Json = undefined,
4641
+ chains: ReadonlyMap<string, number> = new Map(),
4642
+ parents: ReadonlyMap<string, string> = new Map(),
4404
4643
  ): void {
4405
4644
  const at = 'config.turn';
4645
+ const meshBoundBones = (part: string): string[] => {
4646
+ if (!isPlainObject(rawMeshes) || !isPlainObject(rawMeshes[part])) return [];
4647
+ const m = rawMeshes[part] as Record<string, Json>;
4648
+ const out: string[] = [];
4649
+ const add = (rawBone: string): void => {
4650
+ const b = rawBone.endsWith('_d') && bones.has(rawBone.slice(0, -2)) ? rawBone.slice(0, -2) : rawBone;
4651
+ if (bones.has(b) && !out.includes(b)) out.push(b);
4652
+ };
4653
+ if (Array.isArray(m.segments)) {
4654
+ for (const s of m.segments) {
4655
+ if (typeof s === 'string') {
4656
+ const linkCount = chains.get(s);
4657
+ if (linkCount !== undefined) {
4658
+ for (let lk = 0; lk < linkCount; lk++) add(`${s}${lk}`);
4659
+ } else {
4660
+ add(s);
4661
+ }
4662
+ } else if (Array.isArray(s) && typeof s[0] === 'string') {
4663
+ add(s[0]);
4664
+ }
4665
+ }
4666
+ }
4667
+ if (isPlainObject(m.contour)) {
4668
+ if (Array.isArray(m.contour.regions)) {
4669
+ for (const rg of m.contour.regions) {
4670
+ if (isPlainObject(rg) && typeof rg.bone === 'string') add(rg.bone);
4671
+ }
4672
+ }
4673
+ if (isPlainObject(m.contour.bust)) {
4674
+ add(typeof m.contour.bust.bone_r === 'string' ? m.contour.bust.bone_r : DEFAULT_BUST_BONE_R);
4675
+ add(typeof m.contour.bust.bone_l === 'string' ? m.contour.bust.bone_l : DEFAULT_BUST_BONE_L);
4676
+ }
4677
+ }
4678
+ if (isPlainObject(m.auto) && Array.isArray(m.auto.regions)) {
4679
+ for (const rg of m.auto.regions) {
4680
+ if (isPlainObject(rg) && typeof rg.bone === 'string') add(rg.bone);
4681
+ }
4682
+ }
4683
+ if (isPlainObject(m.explicit)) {
4684
+ const addWeights = (ws: Json): void => {
4685
+ if (!Array.isArray(ws)) return;
4686
+ for (const row of ws) {
4687
+ if (!Array.isArray(row)) continue;
4688
+ for (const w of row) {
4689
+ if (isPlainObject(w) && typeof w.bone === 'string') add(w.bone);
4690
+ }
4691
+ }
4692
+ };
4693
+ addWeights(m.explicit.weights);
4694
+ if (Array.isArray(m.explicit.islands)) {
4695
+ for (const isl of m.explicit.islands) {
4696
+ if (isPlainObject(isl)) addWeights(isl.weights);
4697
+ }
4698
+ }
4699
+ }
4700
+ return out;
4701
+ };
4702
+ const headSubtreeRoot = (boneName: string): string | null => {
4703
+ if (boneName === 'head') return 'head';
4704
+ let cur: string | undefined = boneName;
4705
+ const seen = new Set<string>();
4706
+ while (cur !== undefined && !seen.has(cur)) {
4707
+ seen.add(cur);
4708
+ const p = parents.get(cur);
4709
+ if (p === 'head') return cur;
4710
+ cur = p;
4711
+ }
4712
+ return null;
4713
+ };
4714
+ const canCarryHeadUnitBone = (boneName: string): boolean => headSubtreeRoot(boneName) !== null;
4715
+ const bodySubtreeRoot = (boneName: string, torsoRoots: ReadonlySet<string>, headExclusion: ReadonlySet<string>): string | null => {
4716
+ if (headExclusion.has(boneName)) return null;
4717
+ if (torsoRoots.has(boneName)) return boneName;
4718
+ let cur: string | undefined = boneName;
4719
+ const seen = new Set<string>();
4720
+ while (cur !== undefined && !seen.has(cur)) {
4721
+ seen.add(cur);
4722
+ const p = parents.get(cur);
4723
+ if (p === undefined || headExclusion.has(p)) return null;
4724
+ if (torsoRoots.has(p)) return !torsoRoots.has(cur) && !headExclusion.has(cur) ? cur : null;
4725
+ cur = p;
4726
+ }
4727
+ return null;
4728
+ };
4729
+ const canCarryBodyUnitBone = (boneName: string, torsoRoots: ReadonlySet<string>, headExclusion: ReadonlySet<string>): boolean =>
4730
+ bodySubtreeRoot(boneName, torsoRoots, headExclusion) !== null;
4406
4731
  const hasRoles = isPlainObject(v) && 'roles' in v;
4407
4732
  const hasBody = isPlainObject(v) && 'body' in v;
4408
4733
  const hasDepths = isPlainObject(v) && 'depths' in v;
@@ -4460,7 +4785,9 @@ function checkTurn(
4460
4785
  c.fail('CONFIG_FIELD_TYPE', `${at}.roles`, `is ${show(r)}; a non-empty object of part name -> ("surface" | "unit" | "rear") is required`);
4461
4786
  } else {
4462
4787
  const surfaceParts: string[] = [];
4788
+ const unitMeshParts: string[] = [];
4463
4789
  const earParts: string[] = [];
4790
+ const headUnitRootOwner = new Map<string, { part: string; bone: string }>();
4464
4791
  for (const [part, role] of Object.entries(r)) {
4465
4792
  if (isRecordKey(part)) continue;
4466
4793
  if (!attached.has(part)) {
@@ -4470,16 +4797,48 @@ function checkTurn(
4470
4797
  c.fail('CONFIG_TURN_ROLE_UNKNOWN', `${at}.roles.${part}`, `is ${show(role)}; expected one of ${TURN_ROLES.map((x) => `"${x}"`).join(', ')}`);
4471
4798
  } else {
4472
4799
  if (role === 'surface') {
4800
+ surfaceParts.push(part);
4801
+ }
4802
+ if (role === 'unit') {
4803
+ if (part === 'ear_r' || part === 'ear_l') earParts.push(part);
4473
4804
  if (meshParts.has(part)) {
4474
- c.fail(
4475
- 'CONFIG_TURN_SURFACE_REGION',
4476
- `${at}.roles.${part}`,
4477
- `declares "${part}" as "surface", and config.meshes.${part} also declares a mesh for "${part}"; 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`,
4478
- );
4805
+ unitMeshParts.push(part);
4806
+ if (bones.has('head')) {
4807
+ const bound = meshBoundBones(part);
4808
+ const uncarried = bound.filter((b) => !canCarryHeadUnitBone(b));
4809
+ if (bound.length > 0 && uncarried.length > 0) {
4810
+ c.fail(
4811
+ 'CONFIG_TURN_UNIT_MESH_BONES',
4812
+ `${at}.roles.${part}`,
4813
+ `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 "${turnUnitBone(part)}" under "${FACESHIFT_BONE}"; bind a head "unit" mesh only to "head" or bones and chains under "head"`,
4814
+ );
4815
+ }
4816
+ const reportedRoots = new Set<string>();
4817
+ for (const b of bound) {
4818
+ if (b === 'head') continue;
4819
+ const rootBone = headSubtreeRoot(b);
4820
+ if (rootBone === null) continue;
4821
+ const owner = headUnitRootOwner.get(rootBone);
4822
+ if (owner !== undefined && owner.part !== part) {
4823
+ if (!reportedRoots.has(rootBone)) {
4824
+ reportedRoots.add(rootBone);
4825
+ const sharedDetail =
4826
+ owner.bone === b
4827
+ ? `bone "${b}"${b === rootBone ? '' : ` (under "${rootBone}")`}`
4828
+ : `chain root "${rootBone}" ("${owner.part}" binds "${owner.bone}", "${part}" binds "${b}")`;
4829
+ c.fail(
4830
+ 'CONFIG_TURN_UNIT_MESH_BONES',
4831
+ `${at}.roles.${part}`,
4832
+ `declares "${part}" as "unit", and config.meshes.${part} shares ${sharedDetail} with "unit" mesh "${owner.part}" (${at}.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"`,
4833
+ );
4834
+ }
4835
+ } else if (owner === undefined) {
4836
+ headUnitRootOwner.set(rootBone, { part, bone: b });
4837
+ }
4838
+ }
4839
+ }
4479
4840
  }
4480
- surfaceParts.push(part);
4481
4841
  }
4482
- if (role === 'unit' && (part === 'ear_r' || part === 'ear_l')) earParts.push(part);
4483
4842
  }
4484
4843
  }
4485
4844
  if (surfaceParts.length === 0) {
@@ -4487,7 +4846,7 @@ function checkTurn(
4487
4846
  }
4488
4847
  for (const ear of earParts) {
4489
4848
  const earIdx = parts.indexOf(ear);
4490
- for (const surf of surfaceParts) {
4849
+ for (const surf of surfaceParts.filter((p) => p === 'face')) {
4491
4850
  const surfIdx = parts.indexOf(surf);
4492
4851
  if (earIdx !== -1 && surfIdx !== -1 && earIdx > surfIdx) {
4493
4852
  c.fail(
@@ -4501,7 +4860,7 @@ function checkTurn(
4501
4860
  if (!bones.has('head')) {
4502
4861
  c.fail('CONFIG_TURN_HEAD_BONE', `${at}.roles`, 'requires a declared "head" bone in config.bones to parent the 2.5D turn carriers');
4503
4862
  }
4504
- for (const reserved of [FACESHIFT_BONE, REAR_SHIFT_BONE, ...surfaceParts.map(turnSurfaceBone)]) {
4863
+ for (const reserved of [FACESHIFT_BONE, REAR_SHIFT_BONE, ...surfaceParts.filter((p) => !meshParts.has(p)).map(turnSurfaceBone), ...unitMeshParts.map(turnUnitBone)]) {
4505
4864
  if (bones.has(reserved)) {
4506
4865
  c.fail('CONFIG_TURN_BONE_FREE', `bone "${reserved}"`, `is a carrier bone the rig stage adds under head for config.turn.roles, and config.bones already declares a bone of that name; rename it`);
4507
4866
  }
@@ -4556,6 +4915,11 @@ function checkTurn(
4556
4915
  c.fail('CONFIG_FIELD_TYPE', `${bAt}.roles`, `is ${show(br)}; a non-empty object of part name -> ("surface" | "unit" | "rear") is required`);
4557
4916
  } else {
4558
4917
  const bodySurfaceParts: string[] = [];
4918
+ const bodyUnitMeshParts: string[] = [];
4919
+ const bodyRoot = typeof bo.bone === 'string' && bones.has(bo.bone) ? bo.bone : bones.has('chest') ? 'chest' : 'hip';
4920
+ const torsoRoots = new Set<string>([bodyRoot, 'chest', 'hip']);
4921
+ const headExclusion = new Set<string>(['head', 'neck']);
4922
+ const bodyUnitRootOwner = new Map<string, { part: string; bone: string }>();
4559
4923
  for (const [part, role] of Object.entries(br)) {
4560
4924
  if (isRecordKey(part)) continue;
4561
4925
  if (!attached.has(part)) {
@@ -4564,20 +4928,49 @@ function checkTurn(
4564
4928
  if (typeof role !== 'string' || !(TURN_ROLES as readonly string[]).includes(role)) {
4565
4929
  c.fail('CONFIG_TURN_ROLE_UNKNOWN', `${bAt}.roles.${part}`, `is ${show(role)}; expected one of ${TURN_ROLES.map((x) => `"${x}"`).join(', ')}`);
4566
4930
  } else if (role === 'surface') {
4567
- if (meshParts.has(part)) {
4568
- c.fail(
4569
- 'CONFIG_TURN_SURFACE_REGION',
4570
- `${bAt}.roles.${part}`,
4571
- `declares "${part}" as "surface", and config.meshes.${part} also declares a mesh for "${part}"; 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`,
4572
- );
4573
- }
4574
4931
  bodySurfaceParts.push(part);
4932
+ } else if (role === 'unit' && meshParts.has(part)) {
4933
+ bodyUnitMeshParts.push(part);
4934
+ if (bones.has(bodyRoot)) {
4935
+ const bound = meshBoundBones(part);
4936
+ const uncarried = bound.filter((b) => !canCarryBodyUnitBone(b, torsoRoots, headExclusion));
4937
+ if (bound.length > 0 && uncarried.length > 0) {
4938
+ c.fail(
4939
+ 'CONFIG_TURN_UNIT_MESH_BONES',
4940
+ `${bAt}.roles.${part}`,
4941
+ `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 "${turnUnitBone(part)}" under "${BODYSHIFT_BONE}"; bind a body "unit" mesh only to the torso root or bones and chains under it`,
4942
+ );
4943
+ }
4944
+ const reportedRoots = new Set<string>();
4945
+ for (const b of bound) {
4946
+ if (torsoRoots.has(b)) continue;
4947
+ const rootBone = bodySubtreeRoot(b, torsoRoots, headExclusion);
4948
+ if (rootBone === null) continue;
4949
+ const owner = bodyUnitRootOwner.get(rootBone);
4950
+ if (owner !== undefined && owner.part !== part) {
4951
+ if (!reportedRoots.has(rootBone)) {
4952
+ reportedRoots.add(rootBone);
4953
+ const sharedDetail =
4954
+ owner.bone === b
4955
+ ? `bone "${b}"${b === rootBone ? '' : ` (under "${rootBone}")`}`
4956
+ : `chain root "${rootBone}" ("${owner.part}" binds "${owner.bone}", "${part}" binds "${b}")`;
4957
+ c.fail(
4958
+ 'CONFIG_TURN_UNIT_MESH_BONES',
4959
+ `${bAt}.roles.${part}`,
4960
+ `declares "${part}" as "unit", and config.meshes.${part} shares ${sharedDetail} with "unit" mesh "${owner.part}" (${bAt}.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}"`,
4961
+ );
4962
+ }
4963
+ } else if (owner === undefined) {
4964
+ bodyUnitRootOwner.set(rootBone, { part, bone: b });
4965
+ }
4966
+ }
4967
+ }
4575
4968
  }
4576
4969
  }
4577
4970
  if (bodySurfaceParts.length === 0) {
4578
4971
  c.fail('CONFIG_TURN_SURFACE_REQUIRED', `${bAt}.roles`, 'declares no part with role "surface"; at least one surface part is required for 2.5D body turn');
4579
4972
  }
4580
- for (const reserved of [BODYSHIFT_BONE, BODY_REAR_SHIFT_BONE, ...bodySurfaceParts.map(turnSurfaceBone)]) {
4973
+ for (const reserved of [BODYSHIFT_BONE, BODY_REAR_SHIFT_BONE, ...bodySurfaceParts.filter((p) => !meshParts.has(p)).map(turnSurfaceBone), ...bodyUnitMeshParts.map(turnUnitBone)]) {
4581
4974
  if (bones.has(reserved)) {
4582
4975
  c.fail('CONFIG_TURN_BONE_FREE', `bone "${reserved}"`, `is a carrier bone the rig stage adds for config.turn.body.roles, and config.bones already declares a bone of that name; rename it`);
4583
4976
  }