@rig-c/parts 1.70.1 → 1.71.1

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 { EAR_DEPTH_RANGE, FACE_DEFORM_FRACTIONS, FACE_DEFORM_RANGES, type FaceDeformKey, FACE_RATED_PITCH_BAND, FACE_RATED_YAW_BAND, FACESHIFT_BONE, REAR_SHIFT_BONE, TURN_BONE, TURN_ROLES, type TurnSpec, turnNearest, turnSurfaceBone } 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);
@@ -1697,7 +1933,16 @@ function parseConfigFrom(raw: Json, base: string | null): { config: CharacterCon
1697
1933
  const attached = attachedParts(t.meshes, t.regions);
1698
1934
  if ('motion_seams' in t) c.problems.push(...motionSeamProblems(t.motion_seams, attached, 'config.motion_seams', 'CONFIG_MOTION_SEAM'));
1699
1935
  const hasAltFace = hasAlternateFaceSet(t.assemble, [...parts, ...cuts]);
1700
- if ('turn' in t) checkTurn(c, t.turn, attached, names.bones, hasAltFace, parts);
1936
+ const declaredSliders = new Set<string>();
1937
+ if (Array.isArray(t.constraints)) {
1938
+ for (const entry of t.constraints) {
1939
+ if (isPlainObject(entry) && entry.type === 'slider' && typeof entry.name === 'string' && entry.name.length > 0) {
1940
+ declaredSliders.add(entry.name);
1941
+ }
1942
+ }
1943
+ }
1944
+ const meshParts = isPlainObject(t.meshes) ? new Set(Object.keys(t.meshes).filter((k) => !isRecordKey(k))) : new Set<string>();
1945
+ if ('turn' in t) checkTurn(c, t.turn, attached, names.bones, hasAltFace, parts, declaredSliders, meshParts, t.meshes, names.chains, names.parents);
1701
1946
  if ('scene' in t) checkScene(c, t.scene);
1702
1947
  if ('cloth' in t) checkCloth(c, t.cloth);
1703
1948
  if ('requirements' in t && c.string('config.requirements', t.requirements) && base !== null) checkRequirementsFile(c, resolve(base, t.requirements));
@@ -4383,60 +4628,166 @@ function checkAnimationSetKeys(
4383
4628
  }
4384
4629
  }
4385
4630
 
4386
- function checkTurn(c: Check, v: Json, attached: Set<string>, bones: Set<string>, hasAltFace: boolean, parts: readonly string[] = []): void {
4631
+ function checkTurn(
4632
+ c: Check,
4633
+ v: Json,
4634
+ attached: Set<string>,
4635
+ bones: Set<string>,
4636
+ hasAltFace: boolean,
4637
+ parts: readonly string[] = [],
4638
+ declaredSliders: ReadonlySet<string> = new Set(),
4639
+ meshParts: ReadonlySet<string> = new Set(),
4640
+ rawMeshes: Json = undefined,
4641
+ chains: ReadonlyMap<string, number> = new Map(),
4642
+ parents: ReadonlyMap<string, string> = new Map(),
4643
+ ): void {
4387
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;
4388
4731
  const hasRoles = isPlainObject(v) && 'roles' in v;
4732
+ const hasBody = isPlainObject(v) && 'body' in v;
4733
+ const hasDepths = isPlainObject(v) && 'depths' in v;
4389
4734
  const o = hasRoles
4390
- ? c.object(at, v, ['roles'], ['pivot', 'depths', 'counter', 'grid', 'unitDepths', 'head', 'deform', 'band', 'radius', 'surface'])
4391
- : c.object(at, v, ['pivot', 'depths'], ['roles', 'counter', 'grid', 'unitDepths', 'head', 'deform', 'band', 'radius', 'surface']);
4735
+ ? c.object(at, v, ['roles'], ['pivot', 'depths', 'counter', 'grid', 'unitDepths', 'head', 'deform', 'band', 'radius', 'surface', 'body'])
4736
+ : hasBody && !hasDepths
4737
+ ? c.object(at, v, ['body'], ['pivot', 'depths', 'roles', 'counter', 'grid', 'unitDepths', 'head', 'deform', 'band', 'radius', 'surface'])
4738
+ : c.object(at, v, ['pivot', 'depths'], ['roles', 'counter', 'grid', 'unitDepths', 'head', 'deform', 'band', 'radius', 'surface', 'body']);
4392
4739
  if (o === null) return;
4393
4740
  const pivot = 'pivot' in o && c.number(`${at}.pivot`, o.pivot) ? (o.pivot as number) : null;
4394
- if ('counter' in o && c.number(`${at}.counter`, o.counter)) {
4395
- const cnt = o.counter as number;
4396
- if (cnt < 0 || cnt > 1) {
4397
- c.fail('CONFIG_TURN_COUNTER_RANGE', `${at}.counter`, `is ${cnt}; a rear counter fraction in [0, 1] is required`);
4398
- }
4399
- }
4400
- if ('grid' in o) {
4401
- const checkGridPair = (gAt: string, gv: Json): void => {
4402
- if (!Array.isArray(gv) || gv.length !== 2 || !gv.every((n) => typeof n === 'number' && Number.isInteger(n) && n >= 2)) {
4403
- c.fail('CONFIG_FIELD_TYPE', gAt, `is ${show(gv)}; a [cols, rows] pair of integers >= 2 is required`);
4741
+ const checkGridField = (gAt: string, gv: Json): void => {
4742
+ const checkGridPair = (pAt: string, pv: Json): void => {
4743
+ if (!Array.isArray(pv) || pv.length !== 2 || !pv.every((n) => typeof n === 'number' && Number.isInteger(n) && n >= 2)) {
4744
+ c.fail('CONFIG_FIELD_TYPE', pAt, `is ${show(pv)}; a [cols, rows] pair of integers >= 2 is required`);
4404
4745
  }
4405
4746
  };
4406
- if (Array.isArray(o.grid)) {
4407
- checkGridPair(`${at}.grid`, o.grid);
4408
- } else if (isPlainObject(o.grid)) {
4409
- for (const [part, gv] of Object.entries(o.grid)) {
4747
+ if (Array.isArray(gv)) {
4748
+ checkGridPair(gAt, gv);
4749
+ } else if (isPlainObject(gv)) {
4750
+ for (const [part, pv] of Object.entries(gv)) {
4410
4751
  if (isRecordKey(part)) continue;
4411
4752
  if (!attached.has(part)) {
4412
- c.fail('CONFIG_NAME_RESOLVES', `${at}.grid.${part}`, `names "${part}", which neither config.meshes nor config.regions attaches`);
4753
+ c.fail('CONFIG_NAME_RESOLVES', `${gAt}.${part}`, `names "${part}", which neither config.meshes nor config.regions attaches`);
4413
4754
  }
4414
- checkGridPair(`${at}.grid.${part}`, gv);
4755
+ checkGridPair(`${gAt}.${part}`, pv);
4415
4756
  }
4416
4757
  } else {
4417
- c.fail('CONFIG_FIELD_TYPE', `${at}.grid`, `is ${show(o.grid)}; a [cols, rows] pair or object of part -> [cols, rows] is required`);
4758
+ c.fail('CONFIG_FIELD_TYPE', gAt, `is ${show(gv)}; a [cols, rows] pair or object of part -> [cols, rows] is required`);
4418
4759
  }
4419
- }
4420
- if ('unitDepths' in o) {
4421
- if (!isPlainObject(o.unitDepths)) {
4422
- c.fail('CONFIG_FIELD_TYPE', `${at}.unitDepths`, `is ${show(o.unitDepths)}; an object of part or bone name -> scalar depth is required`);
4760
+ };
4761
+ const checkUnitDepthsField = (uAt: string, uv: Json): void => {
4762
+ if (!isPlainObject(uv)) {
4763
+ c.fail('CONFIG_FIELD_TYPE', uAt, `is ${show(uv)}; an object of part or bone name -> scalar depth is required`);
4423
4764
  } else {
4424
- for (const [k, dv] of Object.entries(o.unitDepths)) {
4765
+ for (const [k, dv] of Object.entries(uv)) {
4425
4766
  if (isRecordKey(k)) continue;
4426
4767
  if (!attached.has(k) && !bones.has(k)) {
4427
- c.fail('CONFIG_NAME_RESOLVES', `${at}.unitDepths.${k}`, `names "${k}", which is neither an attached part nor a declared bone`);
4768
+ c.fail('CONFIG_NAME_RESOLVES', `${uAt}.${k}`, `names "${k}", which is neither an attached part nor a declared bone`);
4428
4769
  }
4429
- c.number(`${at}.unitDepths.${k}`, dv);
4770
+ c.number(`${uAt}.${k}`, dv);
4430
4771
  }
4431
4772
  }
4773
+ };
4774
+ if ('counter' in o && c.number(`${at}.counter`, o.counter)) {
4775
+ const cnt = o.counter as number;
4776
+ if (cnt < 0 || cnt > 1) {
4777
+ c.fail('CONFIG_TURN_COUNTER_RANGE', `${at}.counter`, `is ${cnt}; a rear counter fraction in [0, 1] is required`);
4778
+ }
4432
4779
  }
4780
+ if ('grid' in o) checkGridField(`${at}.grid`, o.grid);
4781
+ if ('unitDepths' in o) checkUnitDepthsField(`${at}.unitDepths`, o.unitDepths);
4433
4782
  if ('roles' in o) {
4434
4783
  const r = o.roles;
4435
4784
  if (!isPlainObject(r) || Object.keys(r).length === 0) {
4436
4785
  c.fail('CONFIG_FIELD_TYPE', `${at}.roles`, `is ${show(r)}; a non-empty object of part name -> ("surface" | "unit" | "rear") is required`);
4437
4786
  } else {
4438
4787
  const surfaceParts: string[] = [];
4788
+ const unitMeshParts: string[] = [];
4439
4789
  const earParts: string[] = [];
4790
+ const headUnitRootOwner = new Map<string, { part: string; bone: string }>();
4440
4791
  for (const [part, role] of Object.entries(r)) {
4441
4792
  if (isRecordKey(part)) continue;
4442
4793
  if (!attached.has(part)) {
@@ -4445,8 +4796,56 @@ function checkTurn(c: Check, v: Json, attached: Set<string>, bones: Set<string>,
4445
4796
  if (typeof role !== 'string' || !(TURN_ROLES as readonly string[]).includes(role)) {
4446
4797
  c.fail('CONFIG_TURN_ROLE_UNKNOWN', `${at}.roles.${part}`, `is ${show(role)}; expected one of ${TURN_ROLES.map((x) => `"${x}"`).join(', ')}`);
4447
4798
  } else {
4448
- if (role === 'surface') surfaceParts.push(part);
4449
- if (role === 'unit' && (part === 'ear_r' || part === 'ear_l')) earParts.push(part);
4799
+ if (role === 'surface') {
4800
+ if (meshParts.has(part)) {
4801
+ c.fail(
4802
+ 'CONFIG_TURN_SURFACE_REGION',
4803
+ `${at}.roles.${part}`,
4804
+ `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`,
4805
+ );
4806
+ }
4807
+ surfaceParts.push(part);
4808
+ }
4809
+ if (role === 'unit') {
4810
+ if (part === 'ear_r' || part === 'ear_l') earParts.push(part);
4811
+ if (meshParts.has(part)) {
4812
+ unitMeshParts.push(part);
4813
+ if (bones.has('head')) {
4814
+ const bound = meshBoundBones(part);
4815
+ const uncarried = bound.filter((b) => !canCarryHeadUnitBone(b));
4816
+ if (bound.length > 0 && uncarried.length > 0) {
4817
+ c.fail(
4818
+ 'CONFIG_TURN_UNIT_MESH_BONES',
4819
+ `${at}.roles.${part}`,
4820
+ `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"`,
4821
+ );
4822
+ }
4823
+ const reportedRoots = new Set<string>();
4824
+ for (const b of bound) {
4825
+ if (b === 'head') continue;
4826
+ const rootBone = headSubtreeRoot(b);
4827
+ if (rootBone === null) continue;
4828
+ const owner = headUnitRootOwner.get(rootBone);
4829
+ if (owner !== undefined && owner.part !== part) {
4830
+ if (!reportedRoots.has(rootBone)) {
4831
+ reportedRoots.add(rootBone);
4832
+ const sharedDetail =
4833
+ owner.bone === b
4834
+ ? `bone "${b}"${b === rootBone ? '' : ` (under "${rootBone}")`}`
4835
+ : `chain root "${rootBone}" ("${owner.part}" binds "${owner.bone}", "${part}" binds "${b}")`;
4836
+ c.fail(
4837
+ 'CONFIG_TURN_UNIT_MESH_BONES',
4838
+ `${at}.roles.${part}`,
4839
+ `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"`,
4840
+ );
4841
+ }
4842
+ } else if (owner === undefined) {
4843
+ headUnitRootOwner.set(rootBone, { part, bone: b });
4844
+ }
4845
+ }
4846
+ }
4847
+ }
4848
+ }
4450
4849
  }
4451
4850
  }
4452
4851
  if (surfaceParts.length === 0) {
@@ -4468,13 +4867,131 @@ function checkTurn(c: Check, v: Json, attached: Set<string>, bones: Set<string>,
4468
4867
  if (!bones.has('head')) {
4469
4868
  c.fail('CONFIG_TURN_HEAD_BONE', `${at}.roles`, 'requires a declared "head" bone in config.bones to parent the 2.5D turn carriers');
4470
4869
  }
4471
- for (const reserved of [FACESHIFT_BONE, REAR_SHIFT_BONE, ...surfaceParts.map(turnSurfaceBone)]) {
4870
+ for (const reserved of [FACESHIFT_BONE, REAR_SHIFT_BONE, ...surfaceParts.map(turnSurfaceBone), ...unitMeshParts.map(turnUnitBone)]) {
4472
4871
  if (bones.has(reserved)) {
4473
4872
  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`);
4474
4873
  }
4475
4874
  }
4476
4875
  }
4477
4876
  }
4877
+ if ('body' in o) {
4878
+ const bAt = `${at}.body`;
4879
+ const bo = c.object(bAt, o.body, ['roles'], ['pivot', 'bone', 'slider', 'counter', 'grid', 'unitDepths']);
4880
+ if (bo !== null) {
4881
+ if ('pivot' in bo) {
4882
+ c.number(`${bAt}.pivot`, bo.pivot);
4883
+ } else if (pivot === null) {
4884
+ c.fail('CONFIG_FIELD_PRESENT', `${bAt}.pivot`, 'is absent and required when config.turn.pivot is not declared');
4885
+ }
4886
+ if ('counter' in bo && c.number(`${bAt}.counter`, bo.counter)) {
4887
+ const cnt = bo.counter as number;
4888
+ if (cnt < 0 || cnt > 1) {
4889
+ c.fail('CONFIG_TURN_COUNTER_RANGE', `${bAt}.counter`, `is ${cnt}; a rear counter fraction in [0, 1] is required`);
4890
+ }
4891
+ }
4892
+ if ('grid' in bo) checkGridField(`${bAt}.grid`, bo.grid);
4893
+ if ('unitDepths' in bo) checkUnitDepthsField(`${bAt}.unitDepths`, bo.unitDepths);
4894
+ if ('bone' in bo) {
4895
+ if (c.string(`${bAt}.bone`, bo.bone) && !bones.has(bo.bone as string)) {
4896
+ c.fail('CONFIG_NAME_RESOLVES', `${bAt}.bone`, `names "${bo.bone}", which config.bones does not declare`);
4897
+ }
4898
+ } else if (!bones.has('chest') && !bones.has('hip')) {
4899
+ c.fail('CONFIG_TURN_HEAD_BONE', `${bAt}.roles`, 'requires a declared "chest" or "hip" bone (or config.turn.body.bone) in config.bones to parent the 2.5D body turn carriers');
4900
+ }
4901
+ let sliderName = BODY_YAW_DIAL_BONE;
4902
+ if ('slider' in bo) {
4903
+ if (c.string(`${bAt}.slider`, bo.slider)) sliderName = bo.slider as string;
4904
+ }
4905
+ const headSliders = new Set(['yaw', 'pitch', YAW_DIAL_BONE, PITCH_DIAL_BONE]);
4906
+ if (declaredSliders.has(sliderName) || headSliders.has(sliderName)) {
4907
+ c.fail(
4908
+ 'CONFIG_TURN_SLIDER_NAME_FREE',
4909
+ `${bAt}.slider`,
4910
+ `is "${sliderName}", which collides with an existing slider constraint "${sliderName}"; choose a distinct slider name`,
4911
+ );
4912
+ }
4913
+ if (bones.has(sliderName)) {
4914
+ c.fail(
4915
+ 'CONFIG_TURN_BONE_FREE',
4916
+ `bone "${sliderName}"`,
4917
+ `is the dial bone the rig stage adds under root for config.turn.body, and config.bones already declares a bone of that name; rename it`,
4918
+ );
4919
+ }
4920
+ const br = bo.roles;
4921
+ if (!isPlainObject(br) || Object.keys(br).length === 0) {
4922
+ c.fail('CONFIG_FIELD_TYPE', `${bAt}.roles`, `is ${show(br)}; a non-empty object of part name -> ("surface" | "unit" | "rear") is required`);
4923
+ } else {
4924
+ const bodySurfaceParts: string[] = [];
4925
+ const bodyUnitMeshParts: string[] = [];
4926
+ const bodyRoot = typeof bo.bone === 'string' && bones.has(bo.bone) ? bo.bone : bones.has('chest') ? 'chest' : 'hip';
4927
+ const torsoRoots = new Set<string>([bodyRoot, 'chest', 'hip']);
4928
+ const headExclusion = new Set<string>(['head', 'neck']);
4929
+ const bodyUnitRootOwner = new Map<string, { part: string; bone: string }>();
4930
+ for (const [part, role] of Object.entries(br)) {
4931
+ if (isRecordKey(part)) continue;
4932
+ if (!attached.has(part)) {
4933
+ c.fail('CONFIG_NAME_RESOLVES', `${bAt}.roles.${part}`, `names "${part}", which neither config.meshes nor config.regions attaches; a part the rig draws is required`);
4934
+ }
4935
+ if (typeof role !== 'string' || !(TURN_ROLES as readonly string[]).includes(role)) {
4936
+ c.fail('CONFIG_TURN_ROLE_UNKNOWN', `${bAt}.roles.${part}`, `is ${show(role)}; expected one of ${TURN_ROLES.map((x) => `"${x}"`).join(', ')}`);
4937
+ } else if (role === 'surface') {
4938
+ if (meshParts.has(part)) {
4939
+ c.fail(
4940
+ 'CONFIG_TURN_SURFACE_REGION',
4941
+ `${bAt}.roles.${part}`,
4942
+ `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`,
4943
+ );
4944
+ }
4945
+ bodySurfaceParts.push(part);
4946
+ } else if (role === 'unit' && meshParts.has(part)) {
4947
+ bodyUnitMeshParts.push(part);
4948
+ if (bones.has(bodyRoot)) {
4949
+ const bound = meshBoundBones(part);
4950
+ const uncarried = bound.filter((b) => !canCarryBodyUnitBone(b, torsoRoots, headExclusion));
4951
+ if (bound.length > 0 && uncarried.length > 0) {
4952
+ c.fail(
4953
+ 'CONFIG_TURN_UNIT_MESH_BONES',
4954
+ `${bAt}.roles.${part}`,
4955
+ `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`,
4956
+ );
4957
+ }
4958
+ const reportedRoots = new Set<string>();
4959
+ for (const b of bound) {
4960
+ if (torsoRoots.has(b)) continue;
4961
+ const rootBone = bodySubtreeRoot(b, torsoRoots, headExclusion);
4962
+ if (rootBone === null) continue;
4963
+ const owner = bodyUnitRootOwner.get(rootBone);
4964
+ if (owner !== undefined && owner.part !== part) {
4965
+ if (!reportedRoots.has(rootBone)) {
4966
+ reportedRoots.add(rootBone);
4967
+ const sharedDetail =
4968
+ owner.bone === b
4969
+ ? `bone "${b}"${b === rootBone ? '' : ` (under "${rootBone}")`}`
4970
+ : `chain root "${rootBone}" ("${owner.part}" binds "${owner.bone}", "${part}" binds "${b}")`;
4971
+ c.fail(
4972
+ 'CONFIG_TURN_UNIT_MESH_BONES',
4973
+ `${bAt}.roles.${part}`,
4974
+ `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}"`,
4975
+ );
4976
+ }
4977
+ } else if (owner === undefined) {
4978
+ bodyUnitRootOwner.set(rootBone, { part, bone: b });
4979
+ }
4980
+ }
4981
+ }
4982
+ }
4983
+ }
4984
+ if (bodySurfaceParts.length === 0) {
4985
+ 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');
4986
+ }
4987
+ for (const reserved of [BODYSHIFT_BONE, BODY_REAR_SHIFT_BONE, ...bodySurfaceParts.map(turnSurfaceBone), ...bodyUnitMeshParts.map(turnUnitBone)]) {
4988
+ if (bones.has(reserved)) {
4989
+ 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`);
4990
+ }
4991
+ }
4992
+ }
4993
+ }
4994
+ }
4478
4995
  if ('radius' in o) c.number(`${at}.radius`, o.radius, 'positive');
4479
4996
  if ('surface' in o) {
4480
4997
  const so = c.object(`${at}.surface`, o.surface, [], ['radius']);
@@ -4590,7 +5107,7 @@ function checkTurn(c: Check, v: Json, attached: Set<string>, bones: Set<string>,
4590
5107
  );
4591
5108
  }
4592
5109
  }
4593
- if (!hasRoles && bones.has(TURN_BONE)) {
5110
+ if (!hasRoles && (!hasBody || hasDepths) && bones.has(TURN_BONE)) {
4594
5111
  c.fail('CONFIG_TURN_BONE_FREE', `bone "${TURN_BONE}"`, `is the control the rig stage adds under root for config.turn, and config.bones already declares a bone of that name; rename it`);
4595
5112
  }
4596
5113
  }