vibedgames 0.10.1 → 0.10.2
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/assets/rebuild-object/.cache/spec-search/core_3d.json +1 -0
- package/assets/rebuild-object/.cache/spec-search/cs2.json +1 -0
- package/assets/rebuild-object/LICENSE +201 -0
- package/assets/rebuild-object/NOTICE +7 -0
- package/assets/rebuild-object/docs/materials/material-reference.json +2324 -0
- package/assets/rebuild-object/docs/specs/render-profile.v2.example.json +63 -0
- package/assets/rebuild-object/docs/specs/render-profile.v2.schema.json +56 -0
- package/assets/rebuild-object/docs/specs/vocabulary/README.md +86 -0
- package/assets/rebuild-object/docs/specs/vocabulary/core_3d.jsonl +12 -0
- package/assets/rebuild-object/docs/specs/vocabulary/core_3d_reconstruction.jsonl +37 -0
- package/assets/rebuild-object/docs/specs/vocabulary/cs2.jsonl +8 -0
- package/assets/rebuild-object/docs/specs/vocabulary/cs2_reconstruction.jsonl +62 -0
- package/assets/rebuild-object/forge/_shared/artifact_cache.py +54 -0
- package/assets/rebuild-object/forge/_shared/chirality.py +272 -0
- package/assets/rebuild-object/forge/_shared/color_metrics.py +107 -0
- package/assets/rebuild-object/forge/_shared/feature_acceptance_policy.py +113 -0
- package/assets/rebuild-object/forge/_shared/image_hash.py +113 -0
- package/assets/rebuild-object/forge/_shared/jpeg.py +448 -0
- package/assets/rebuild-object/forge/_shared/material_physics.py +253 -0
- package/assets/rebuild-object/forge/_shared/pipeline_routing.py +177 -0
- package/assets/rebuild-object/forge/_shared/scalp_field.py +302 -0
- package/assets/rebuild-object/forge/_shared/sdf_primitives.py +172 -0
- package/assets/rebuild-object/forge/_shared/spec_search.py +1792 -0
- package/assets/rebuild-object/forge/_shared/spec_search_profiles.json +58 -0
- package/assets/rebuild-object/forge/_shared/status_banner.py +35 -0
- package/assets/rebuild-object/forge/_shared/subdivision.py +232 -0
- package/assets/rebuild-object/forge/_shared/vertex_paint.py +236 -0
- package/assets/rebuild-object/forge/_shared/workflow_state.py +406 -0
- package/assets/rebuild-object/forge/materials/__init__.py +17 -0
- package/assets/rebuild-object/forge/materials/compatibility.py +106 -0
- package/assets/rebuild-object/forge/materials/reference.py +240 -0
- package/assets/rebuild-object/forge/next.py +116 -0
- package/assets/rebuild-object/forge/report.py +38 -0
- package/assets/rebuild-object/forge/requirements.txt +6 -0
- package/assets/rebuild-object/forge/stage1_intake/analyze_texture.py +255 -0
- package/assets/rebuild-object/forge/stage1_intake/bind_detail_properties.py +99 -0
- package/assets/rebuild-object/forge/stage1_intake/build_detail_inventory.py +349 -0
- package/assets/rebuild-object/forge/stage1_intake/camera_fitting_math.py +133 -0
- package/assets/rebuild-object/forge/stage1_intake/camera_fitting_solver.py +197 -0
- package/assets/rebuild-object/forge/stage1_intake/camera_fitting_types.py +291 -0
- package/assets/rebuild-object/forge/stage1_intake/camera_image_helpers.py +133 -0
- package/assets/rebuild-object/forge/stage1_intake/check_intake_correctness.py +116 -0
- package/assets/rebuild-object/forge/stage1_intake/check_reference_admission.py +203 -0
- package/assets/rebuild-object/forge/stage1_intake/cs2_foundation.py +139 -0
- package/assets/rebuild-object/forge/stage1_intake/cs2_manifest.py +230 -0
- package/assets/rebuild-object/forge/stage1_intake/cs2_review_contract.py +42 -0
- package/assets/rebuild-object/forge/stage1_intake/delight_albedo.py +352 -0
- package/assets/rebuild-object/forge/stage1_intake/detect_cs2.py +276 -0
- package/assets/rebuild-object/forge/stage1_intake/detect_reference_effects.py +275 -0
- package/assets/rebuild-object/forge/stage1_intake/extract_cs2_textures.py +126 -0
- package/assets/rebuild-object/forge/stage1_intake/extract_gradient_stops.py +149 -0
- package/assets/rebuild-object/forge/stage1_intake/extract_hair_evidence.py +385 -0
- package/assets/rebuild-object/forge/stage1_intake/extract_landmarks.py +456 -0
- package/assets/rebuild-object/forge/stage1_intake/extract_part_color_recipe.py +496 -0
- package/assets/rebuild-object/forge/stage1_intake/extract_pbr_evidence.py +843 -0
- package/assets/rebuild-object/forge/stage1_intake/fetch_cs2_metadata.py +147 -0
- package/assets/rebuild-object/forge/stage1_intake/label_glb_nodes.py +318 -0
- package/assets/rebuild-object/forge/stage1_intake/locate_cs2_vpk.py +73 -0
- package/assets/rebuild-object/forge/stage1_intake/material_region_analysis.py +227 -0
- package/assets/rebuild-object/forge/stage1_intake/probe_glb.py +357 -0
- package/assets/rebuild-object/forge/stage1_intake/probe_image.py +168 -0
- package/assets/rebuild-object/forge/stage1_intake/run_vision_adapter.py +45 -0
- package/assets/rebuild-object/forge/stage1_intake/search_specs.py +258 -0
- package/assets/rebuild-object/forge/stage1_intake/semantic_decomposition.py +119 -0
- package/assets/rebuild-object/forge/stage1_intake/solve_camera_pose.py +254 -0
- package/assets/rebuild-object/forge/stage2_spec/apply_material_analysis.py +192 -0
- package/assets/rebuild-object/forge/stage2_spec/cs2_adapters.py +62 -0
- package/assets/rebuild-object/forge/stage2_spec/derive_geometry.py +118 -0
- package/assets/rebuild-object/forge/stage2_spec/hair_profile.py +306 -0
- package/assets/rebuild-object/forge/stage2_spec/humanoid_proportions.py +214 -0
- package/assets/rebuild-object/forge/stage2_spec/new_pre_spec_assessment.py +343 -0
- package/assets/rebuild-object/forge/stage2_spec/new_sculpt_spec.py +2396 -0
- package/assets/rebuild-object/forge/stage2_spec/validate_sculpt_spec.py +2871 -0
- package/assets/rebuild-object/forge/stage3_build/bake_projected_texture.py +181 -0
- package/assets/rebuild-object/forge/stage3_build/decimate.py +272 -0
- package/assets/rebuild-object/forge/stage3_build/generate_threejs_factory.py +4099 -0
- package/assets/rebuild-object/forge/stage3_build/module_cache.py +155 -0
- package/assets/rebuild-object/forge/stage3_build/morph_targets.py +178 -0
- package/assets/rebuild-object/forge/stage3_build/orchestrate_passes.py +653 -0
- package/assets/rebuild-object/forge/stage3_build/uv_unwrap.py +622 -0
- package/assets/rebuild-object/forge/stage3_build/visual_hull.py +357 -0
- package/assets/rebuild-object/forge/stage4_review/_fit_divine_eye.py +64 -0
- package/assets/rebuild-object/forge/stage4_review/append_review.py +453 -0
- package/assets/rebuild-object/forge/stage4_review/attachment_anchor.py +349 -0
- package/assets/rebuild-object/forge/stage4_review/calibrate_eye.py +131 -0
- package/assets/rebuild-object/forge/stage4_review/check_part_coverage.py +298 -0
- package/assets/rebuild-object/forge/stage4_review/compare_region_passes.py +169 -0
- package/assets/rebuild-object/forge/stage4_review/correction_loop.py +258 -0
- package/assets/rebuild-object/forge/stage4_review/cs2_review.py +224 -0
- package/assets/rebuild-object/forge/stage4_review/diagnose_render.py +356 -0
- package/assets/rebuild-object/forge/stage4_review/diagnose_render_multi_angle.py +143 -0
- package/assets/rebuild-object/forge/stage4_review/divine_eye.py +461 -0
- package/assets/rebuild-object/forge/stage4_review/fit_params.py +381 -0
- package/assets/rebuild-object/forge/stage4_review/geometry_integrity.py +294 -0
- package/assets/rebuild-object/forge/stage4_review/hair_gate.py +216 -0
- package/assets/rebuild-object/forge/stage4_review/interior_difference.py +188 -0
- package/assets/rebuild-object/forge/stage4_review/joint_loops.py +209 -0
- package/assets/rebuild-object/forge/stage4_review/make_comparison_sheet.py +292 -0
- package/assets/rebuild-object/forge/stage4_review/material_comparator.py +181 -0
- package/assets/rebuild-object/forge/stage4_review/material_feedback.py +143 -0
- package/assets/rebuild-object/forge/stage4_review/material_gate.py +126 -0
- package/assets/rebuild-object/forge/stage4_review/material_views.py +184 -0
- package/assets/rebuild-object/forge/stage4_review/mesh_reference_compare.py +362 -0
- package/assets/rebuild-object/forge/stage4_review/multi_pass.py +102 -0
- package/assets/rebuild-object/forge/stage4_review/objectness.py +143 -0
- package/assets/rebuild-object/forge/stage4_review/pairwise_penetration.py +376 -0
- package/assets/rebuild-object/forge/stage4_review/per_feature.py +215 -0
- package/assets/rebuild-object/forge/stage4_review/render_bridge.py +556 -0
- package/assets/rebuild-object/forge/stage4_review/scalp_exposure.py +257 -0
- package/assets/rebuild-object/forge/stage4_review/self_intersection.py +592 -0
- package/assets/rebuild-object/forge/stage4_review/swept_arc_gate.py +336 -0
- package/assets/rebuild-object/forge/stage4_review/turntable_gate.py +415 -0
- package/assets/rebuild-object/forge/stage4_review/validate_render_profile.py +182 -0
- package/assets/rebuild-object/forge/stage4_review/vertex_region_gate.py +456 -0
- package/assets/rebuild-object/forge/stage4_review/vlm_gate.py +196 -0
- package/assets/rebuild-object/forge/stage5_rig/NOTES.md +149 -0
- package/assets/rebuild-object/forge/stage5_rig/__init__.py +6 -0
- package/assets/rebuild-object/forge/stage5_rig/emit_rig.py +420 -0
- package/assets/rebuild-object/forge/stage5_rig/geodesic_skinning.py +508 -0
- package/assets/rebuild-object/forge/stage5_rig/rig_spec.py +174 -0
- package/assets/rebuild-object/forge/stage5_rig/validate_rig_payload.py +195 -0
- package/assets/rebuild-object/forge/state.py +98 -0
- package/assets/rebuild-object/steps.json +381 -0
- package/dist/{chunk-FB3UDZAV.js → chunk-24TITAFS.js} +1 -1
- package/dist/{chunk-QNWCBPVO.js → chunk-2C5PG2QO.js} +1 -1
- package/dist/{chunk-4RYTTD4D.js → chunk-2DEVOKI7.js} +1 -1
- package/dist/{chunk-RRI23NK2.js → chunk-2GHPYT2P.js} +1 -1
- package/dist/{chunk-QEKVZ7BX.js → chunk-2HXGMXGC.js} +1 -1
- package/dist/{chunk-N2UHAQXC.js → chunk-36FORP7T.js} +0 -1
- package/dist/{chunk-DH6WPL3X.js → chunk-3IXRQTRF.js} +1 -1
- package/dist/{chunk-SXYQL4GK.js → chunk-4YHA32OE.js} +1 -1
- package/dist/{chunk-V5ADM3WC.js → chunk-4ZGQKPK5.js} +1 -1
- package/dist/{chunk-BJAN3RMY.js → chunk-6CLUPFQA.js} +1 -1
- package/dist/{chunk-52E6EKZV.js → chunk-7WTF2BA4.js} +1 -1
- package/dist/{chunk-P74GTK23.js → chunk-AAXZNK4Z.js} +1 -1
- package/dist/{chunk-F4J6XCHT.js → chunk-ALLBT4FB.js} +1 -1
- package/dist/{chunk-HRKVAXNN.js → chunk-BAZDPPIG.js} +5 -5
- package/dist/{chunk-RPJR3S5S.js → chunk-CYDENLZ4.js} +5 -8
- package/dist/{chunk-I5LELJSK.js → chunk-DKSUD44G.js} +1 -1
- package/dist/{chunk-43P4U7CB.js → chunk-DWWSJKTE.js} +1 -1
- package/dist/{chunk-6IUFHPMV.js → chunk-E72TFJZP.js} +1 -1
- package/dist/{chunk-E3FJUPLT.js → chunk-EUAAQMUA.js} +2 -0
- package/dist/{chunk-37LLKM73.js → chunk-F7LYJSZE.js} +1 -1
- package/dist/{chunk-MEAO33XW.js → chunk-FMON3C74.js} +8 -8
- package/dist/{chunk-YLUB6252.js → chunk-FPILHRLZ.js} +1 -1
- package/dist/{chunk-4UU622RK.js → chunk-GGO6ZYYI.js} +1 -3
- package/dist/{chunk-2ZKS7V72.js → chunk-GZCRYYS6.js} +5 -5
- package/dist/{chunk-E7NDOZ27.js → chunk-LE4GVTYI.js} +8 -8
- package/dist/{chunk-UTSSDFQL.js → chunk-NO6KPV64.js} +1 -1
- package/dist/{chunk-W2QPNAZ3.js → chunk-NXW3Z4Y4.js} +1 -1
- package/dist/{chunk-NG2X3SMF.js → chunk-OHOAZGO4.js} +1 -1
- package/dist/chunk-PYJNI5WD.js +83 -0
- package/dist/{chunk-VUV5U4J5.js → chunk-Q4XAGTFX.js} +1 -1
- package/dist/{chunk-3UGGMFJJ.js → chunk-QMZBSVKF.js} +1 -1
- package/dist/{chunk-ABTUEIRC.js → chunk-QO66UBOS.js} +2 -2
- package/dist/{chunk-LONQWRTR.js → chunk-S4KVGQQO.js} +8 -8
- package/dist/{chunk-FJXPMA63.js → chunk-T777EXAO.js} +1 -1
- package/dist/{chunk-YXOGRERG.js → chunk-TZZNRA3S.js} +1 -1
- package/dist/{chunk-CTY2WZQK.js → chunk-UC3QLWMQ.js} +1 -1
- package/dist/{chunk-MR5KIFI7.js → chunk-UDJH2RED.js} +3 -3
- package/dist/{chunk-FNJL6Z5C.js → chunk-UIKYK7KI.js} +1 -1
- package/dist/{chunk-PKM3JOKQ.js → chunk-UJRSQO2B.js} +1 -1
- package/dist/{chunk-ALPTHSUT.js → chunk-V7LEYVXB.js} +28 -24
- package/dist/{chunk-DPLFCKXP.js → chunk-WRMQEXUC.js} +1 -1
- package/dist/{chunk-HSMG6U7J.js → chunk-WXSBNC67.js} +3 -9
- package/dist/{chunk-HSCTPDEU.js → chunk-X4QIOXNQ.js} +1 -1
- package/dist/{chunk-72KHWZMN.js → chunk-Y6WHUK2O.js} +1 -1
- package/dist/{chunk-VZEJ2ZHE.js → chunk-Z3E7ORGQ.js} +5 -5
- package/dist/index.js +20 -20
- package/package.json +32 -22
- package/dist/{chunk-OFJIG4K3.js → chunk-4ENHS32B.js} +0 -0
- package/dist/{chunk-Q3XQPNF6.js → chunk-BN7TR6OR.js} +3 -3
- package/dist/{chunk-LORGE2NB.js → chunk-U2NCN5RO.js} +3 -3
- package/dist/{chunk-UPHB5HWO.js → chunk-VQTTSPA3.js} +3 -3
|
@@ -0,0 +1,508 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Skinning weights from geodesic distance through the model's own volume.
|
|
3
|
+
|
|
4
|
+
The weight function this replaces measures EUCLIDEAN distance from a vertex to a bone segment. That
|
|
5
|
+
is cheap and it is wrong in one specific, very visible way: straight-line distance does not care
|
|
6
|
+
whether the path stays inside the model. An arm resting against the ribs is millimetres from the
|
|
7
|
+
chest through the air, so the arm bone claims chest vertices, and raising the arm drags the chest with
|
|
8
|
+
it. Every character whose limbs touch the body has this defect; it is not an edge case, it is the
|
|
9
|
+
default pose.
|
|
10
|
+
|
|
11
|
+
Geodesic voxel binding (Dionne & de Lasa, SCA 2013) fixes it by measuring distance THROUGH THE SOLID:
|
|
12
|
+
voxelize the mesh, seed each bone's voxels, and propagate outward without ever crossing empty space.
|
|
13
|
+
The arm-to-chest path is then forced around through the shoulder and is correctly long. It is a
|
|
14
|
+
purely geometric method -- no training data, no time constants, no iteration parameters, no
|
|
15
|
+
optimization at bind or pose time -- which is why it fits a pipeline that ships code rather than
|
|
16
|
+
weights.
|
|
17
|
+
|
|
18
|
+
Interior detection is by flood fill from OUTSIDE the bounding box rather than by a point-in-mesh test
|
|
19
|
+
per voxel. Both are correct on a watertight mesh; the flood fill is one pass instead of one ray cast
|
|
20
|
+
per voxel, and it degrades sanely on a mesh with small holes (the leak is bounded by the hole) rather
|
|
21
|
+
than producing scattered wrong answers along a whole ray.
|
|
22
|
+
|
|
23
|
+
Pure Python 3.10+ stdlib. No pip installs, no numpy.
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
from __future__ import annotations
|
|
27
|
+
|
|
28
|
+
import argparse
|
|
29
|
+
import json
|
|
30
|
+
import math
|
|
31
|
+
import sys
|
|
32
|
+
from collections import deque
|
|
33
|
+
from pathlib import Path
|
|
34
|
+
from typing import Any
|
|
35
|
+
|
|
36
|
+
DEFAULT_RESOLUTION = 32
|
|
37
|
+
MAX_RESOLUTION = 96
|
|
38
|
+
MAX_INFLUENCES = 4
|
|
39
|
+
# Measured on the arm-beside-torso fixture, where the geodesic field correctly reports 1.37 world
|
|
40
|
+
# units to the spine and 4.45 to the arm: power 2 still leaves 8.6% arm influence on the far chest
|
|
41
|
+
# corner, power 3 leaves 2.8%, power 4 leaves 0.9%. The residual is a property of THIS constant, not
|
|
42
|
+
# of the distance field. Higher is tighter and lower is smoother across a joint, so 3 is the middle
|
|
43
|
+
# that removes the visible cross-talk without pinching the elbow.
|
|
44
|
+
DEFAULT_FALLOFF_POWER = 3.0
|
|
45
|
+
UNREACHABLE = float("inf")
|
|
46
|
+
|
|
47
|
+
# Roles that must be rigidly parented to a joint rather than smooth-skinned to the skeleton.
|
|
48
|
+
#
|
|
49
|
+
# WHY HAIR IS FIRST ON THIS LIST. The geodesic field measures distance THROUGH THE SOLID, which is
|
|
50
|
+
# exactly right for a limb and exactly wrong for hair. Hair sits ON the skull, so the path from the
|
|
51
|
+
# neck joint to a crown vertex runs up through the head and arrives short -- the crown then takes a
|
|
52
|
+
# real share of neck weight, and turning the neck DEFORMS the hair, shearing it against the very
|
|
53
|
+
# skull it is supposed to sit on.
|
|
54
|
+
#
|
|
55
|
+
# The deformation also voids the one guarantee the hair pipeline has. `standProud` and the
|
|
56
|
+
# `scalpExposure` gate are build-time geometric checks against the bind pose; smooth-skin the hair
|
|
57
|
+
# and every other pose is unverified, so the model can go bald when the head turns with no gate able
|
|
58
|
+
# to see it. Rigid parenting keeps hair and skull on a single shared transform, which makes the
|
|
59
|
+
# relation between them invariant under every pose.
|
|
60
|
+
#
|
|
61
|
+
# It is also simply more correct. Short hair on a skull genuinely does move rigidly with it; smooth
|
|
62
|
+
# skinning would introduce a deformation that does not exist in the subject.
|
|
63
|
+
#
|
|
64
|
+
# Long hair that crosses a joint is the real exception, and it is served by a short chain of bones
|
|
65
|
+
# with one mesh segment rigidly parented per bone -- still no blended vertex weights.
|
|
66
|
+
RIGID_ROLES = frozenset({"hair", "detail", "decal", "panel"})
|
|
67
|
+
|
|
68
|
+
# 26-connectivity with true step lengths: a face step is 1 voxel, an edge step sqrt(2), a corner
|
|
69
|
+
# sqrt(3). Using 6-connectivity instead makes every distance a Manhattan distance, which biases
|
|
70
|
+
# weights along the grid axes and shows up as boxy falloff on a diagonal limb.
|
|
71
|
+
_NEIGHBOURS: list[tuple[int, int, int, float]] = [
|
|
72
|
+
(dx, dy, dz, math.sqrt(dx * dx + dy * dy + dz * dz))
|
|
73
|
+
for dx in (-1, 0, 1)
|
|
74
|
+
for dy in (-1, 0, 1)
|
|
75
|
+
for dz in (-1, 0, 1)
|
|
76
|
+
if (dx, dy, dz) != (0, 0, 0)
|
|
77
|
+
]
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _triangles(indices: list[Any]) -> list[tuple[int, int, int]]:
|
|
81
|
+
if indices and isinstance(indices[0], (list, tuple)):
|
|
82
|
+
return [(int(t[0]), int(t[1]), int(t[2])) for t in indices]
|
|
83
|
+
return [
|
|
84
|
+
(int(indices[i]), int(indices[i + 1]), int(indices[i + 2]))
|
|
85
|
+
for i in range(0, len(indices) - 2, 3)
|
|
86
|
+
]
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _bounds(vertices: list[list[float]]) -> tuple[list[float], list[float]]:
|
|
90
|
+
low = [min(v[axis] for v in vertices) for axis in range(3)]
|
|
91
|
+
high = [max(v[axis] for v in vertices) for axis in range(3)]
|
|
92
|
+
return low, high
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
class VoxelGrid:
|
|
96
|
+
"""A padded occupancy grid over the mesh, with solid/empty classification."""
|
|
97
|
+
|
|
98
|
+
def __init__(self, vertices: list[list[float]], faces: list[tuple[int, int, int]], resolution: int):
|
|
99
|
+
low, high = _bounds(vertices)
|
|
100
|
+
extent = max(high[axis] - low[axis] for axis in range(3)) or 1.0
|
|
101
|
+
self.step = extent / resolution
|
|
102
|
+
# One voxel of padding on every side so the outside flood fill has somewhere to start; without
|
|
103
|
+
# it a mesh touching the bounding box would have no exterior seed on that face and its whole
|
|
104
|
+
# interior would be misread as outside.
|
|
105
|
+
self.low = [low[axis] - self.step for axis in range(3)]
|
|
106
|
+
self.dims = [
|
|
107
|
+
int(math.ceil((high[axis] - low[axis]) / self.step)) + 3 for axis in range(3)
|
|
108
|
+
]
|
|
109
|
+
self.surface: set[tuple[int, int, int]] = set()
|
|
110
|
+
for face in faces:
|
|
111
|
+
self._rasterize(vertices, face)
|
|
112
|
+
self.solid = self._fill_interior()
|
|
113
|
+
|
|
114
|
+
def index_of(self, point: list[float]) -> tuple[int, int, int]:
|
|
115
|
+
return tuple( # type: ignore[return-value]
|
|
116
|
+
min(self.dims[axis] - 1, max(0, int((point[axis] - self.low[axis]) / self.step)))
|
|
117
|
+
for axis in range(3)
|
|
118
|
+
)
|
|
119
|
+
|
|
120
|
+
def _rasterize(self, vertices: list[list[float]], face: tuple[int, int, int]) -> None:
|
|
121
|
+
"""Mark every voxel a triangle touches, by subdividing until steps are sub-voxel.
|
|
122
|
+
|
|
123
|
+
Barycentric sampling at a fixed rate would leave gaps in a triangle much larger than a voxel,
|
|
124
|
+
and a gap in the surface shell lets the interior flood fill leak out and erase the model.
|
|
125
|
+
"""
|
|
126
|
+
p0, p1, p2 = (vertices[i] for i in face)
|
|
127
|
+
longest = max(
|
|
128
|
+
math.dist(p0, p1), math.dist(p1, p2), math.dist(p2, p0)
|
|
129
|
+
)
|
|
130
|
+
steps = max(1, int(math.ceil(longest / (self.step * 0.5))))
|
|
131
|
+
for i in range(steps + 1):
|
|
132
|
+
for j in range(steps + 1 - i):
|
|
133
|
+
a = i / steps
|
|
134
|
+
b = j / steps
|
|
135
|
+
c = 1.0 - a - b
|
|
136
|
+
point = [p0[k] * c + p1[k] * a + p2[k] * b for k in range(3)]
|
|
137
|
+
self.surface.add(self.index_of(point))
|
|
138
|
+
|
|
139
|
+
def _fill_interior(self) -> set[tuple[int, int, int]]:
|
|
140
|
+
outside: set[tuple[int, int, int]] = set()
|
|
141
|
+
start = (0, 0, 0)
|
|
142
|
+
if start in self.surface:
|
|
143
|
+
# Padding guarantees this cannot happen; if it ever does, treat everything as solid rather
|
|
144
|
+
# than silently returning an empty model.
|
|
145
|
+
return {
|
|
146
|
+
(x, y, z)
|
|
147
|
+
for x in range(self.dims[0])
|
|
148
|
+
for y in range(self.dims[1])
|
|
149
|
+
for z in range(self.dims[2])
|
|
150
|
+
}
|
|
151
|
+
queue = deque([start])
|
|
152
|
+
outside.add(start)
|
|
153
|
+
while queue:
|
|
154
|
+
x, y, z = queue.popleft()
|
|
155
|
+
for dx, dy, dz, _ in _NEIGHBOURS:
|
|
156
|
+
nx, ny, nz = x + dx, y + dy, z + dz
|
|
157
|
+
if not (0 <= nx < self.dims[0] and 0 <= ny < self.dims[1] and 0 <= nz < self.dims[2]):
|
|
158
|
+
continue
|
|
159
|
+
cell = (nx, ny, nz)
|
|
160
|
+
if cell in outside or cell in self.surface:
|
|
161
|
+
continue
|
|
162
|
+
outside.add(cell)
|
|
163
|
+
queue.append(cell)
|
|
164
|
+
solid = set(self.surface)
|
|
165
|
+
for x in range(self.dims[0]):
|
|
166
|
+
for y in range(self.dims[1]):
|
|
167
|
+
for z in range(self.dims[2]):
|
|
168
|
+
cell = (x, y, z)
|
|
169
|
+
if cell not in outside:
|
|
170
|
+
solid.add(cell)
|
|
171
|
+
return solid
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def _segment_voxels(grid: VoxelGrid, start: list[float], end: list[float]) -> set[tuple[int, int, int]]:
|
|
175
|
+
"""Voxels a bone segment passes through, sampled at half-voxel steps."""
|
|
176
|
+
length = math.dist(start, end)
|
|
177
|
+
steps = max(1, int(math.ceil(length / (grid.step * 0.5))))
|
|
178
|
+
cells = set()
|
|
179
|
+
for i in range(steps + 1):
|
|
180
|
+
t = i / steps
|
|
181
|
+
point = [start[k] + (end[k] - start[k]) * t for k in range(3)]
|
|
182
|
+
cells.add(grid.index_of(point))
|
|
183
|
+
return cells
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def geodesic_field(grid: VoxelGrid, sources: set[tuple[int, int, int]]) -> dict[tuple[int, int, int], float]:
|
|
187
|
+
"""Dijkstra over solid voxels from a set of sources, in voxel units.
|
|
188
|
+
|
|
189
|
+
Dijkstra rather than plain BFS because the 26-connected steps have three different lengths; BFS
|
|
190
|
+
would count a corner step (sqrt 3) the same as a face step and distort the field diagonally.
|
|
191
|
+
"""
|
|
192
|
+
import heapq
|
|
193
|
+
|
|
194
|
+
distance: dict[tuple[int, int, int], float] = {}
|
|
195
|
+
heap: list[tuple[float, tuple[int, int, int]]] = []
|
|
196
|
+
for cell in sources:
|
|
197
|
+
if cell in grid.solid:
|
|
198
|
+
distance[cell] = 0.0
|
|
199
|
+
heap.append((0.0, cell))
|
|
200
|
+
heapq.heapify(heap)
|
|
201
|
+
while heap:
|
|
202
|
+
current, cell = heapq.heappop(heap)
|
|
203
|
+
if current > distance.get(cell, UNREACHABLE):
|
|
204
|
+
continue
|
|
205
|
+
x, y, z = cell
|
|
206
|
+
for dx, dy, dz, cost in _NEIGHBOURS:
|
|
207
|
+
neighbour = (x + dx, y + dy, z + dz)
|
|
208
|
+
if neighbour not in grid.solid:
|
|
209
|
+
continue
|
|
210
|
+
candidate = current + cost
|
|
211
|
+
if candidate < distance.get(neighbour, UNREACHABLE):
|
|
212
|
+
distance[neighbour] = candidate
|
|
213
|
+
heapq.heappush(heap, (candidate, neighbour))
|
|
214
|
+
return distance
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def partition_for_binding(
|
|
218
|
+
components: list[dict[str, Any]],
|
|
219
|
+
rigid_roles: frozenset[str] = RIGID_ROLES,
|
|
220
|
+
) -> dict[str, Any]:
|
|
221
|
+
"""Split a component tree into what may be smooth-skinned and what must be rigidly parented.
|
|
222
|
+
|
|
223
|
+
`bind()` weights every vertex of whatever mesh it is handed, with no notion of role. That is the
|
|
224
|
+
correct contract for a distance solver and the wrong default for a character: hand it a merged
|
|
225
|
+
mesh containing hair and it will skin the hair, because nothing told it not to. This is the
|
|
226
|
+
thing that tells it not to.
|
|
227
|
+
|
|
228
|
+
Rigid components are REPORTED, never silently dropped. Each carries the joint it rides, resolved
|
|
229
|
+
by walking up the parent chain to the first ancestor that is itself skinned -- a lock parented to
|
|
230
|
+
a hair mass parented to the head rides the head, not the mass.
|
|
231
|
+
"""
|
|
232
|
+
by_id = {
|
|
233
|
+
str(component.get("id")): component
|
|
234
|
+
for component in components
|
|
235
|
+
if isinstance(component, dict) and component.get("id")
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
def is_rigid(component: dict[str, Any]) -> bool:
|
|
239
|
+
return str(component.get("role") or "").lower() in rigid_roles
|
|
240
|
+
|
|
241
|
+
def ride(component: dict[str, Any]) -> str | None:
|
|
242
|
+
"""First ancestor that is skinned, so the rigid piece has a joint to hang from."""
|
|
243
|
+
seen: set[str] = set()
|
|
244
|
+
parent_id = component.get("parent")
|
|
245
|
+
while isinstance(parent_id, str) and parent_id in by_id and parent_id not in seen:
|
|
246
|
+
seen.add(parent_id)
|
|
247
|
+
parent = by_id[parent_id]
|
|
248
|
+
if not is_rigid(parent):
|
|
249
|
+
return parent_id
|
|
250
|
+
parent_id = parent.get("parent")
|
|
251
|
+
return None
|
|
252
|
+
|
|
253
|
+
skinned: list[str] = []
|
|
254
|
+
rigid: list[dict[str, Any]] = []
|
|
255
|
+
warnings: list[str] = []
|
|
256
|
+
for component in components:
|
|
257
|
+
if not isinstance(component, dict) or not component.get("id"):
|
|
258
|
+
continue
|
|
259
|
+
component_id = str(component["id"])
|
|
260
|
+
if not is_rigid(component):
|
|
261
|
+
skinned.append(component_id)
|
|
262
|
+
continue
|
|
263
|
+
joint = ride(component)
|
|
264
|
+
if joint is None:
|
|
265
|
+
warnings.append(
|
|
266
|
+
f"component {component_id!r} has rigid role "
|
|
267
|
+
f"{str(component.get('role') or '')!r} but no skinned ancestor to parent to; "
|
|
268
|
+
f"it would be left unattached to the skeleton"
|
|
269
|
+
)
|
|
270
|
+
rigid.append({"id": component_id, "role": component.get("role"), "parentJoint": joint})
|
|
271
|
+
|
|
272
|
+
return {
|
|
273
|
+
"schemaVersion": 1,
|
|
274
|
+
"kind": "binding-partition",
|
|
275
|
+
"skinned": skinned,
|
|
276
|
+
"rigidlyParented": rigid,
|
|
277
|
+
"rigidRoles": sorted(rigid_roles),
|
|
278
|
+
"warnings": warnings,
|
|
279
|
+
"note": (
|
|
280
|
+
"Rigid components are parented to a joint and inherit its transform exactly. They are "
|
|
281
|
+
"excluded from geodesic binding because the field measures distance through the solid, "
|
|
282
|
+
"so a crown vertex would take neck weight through the skull and shear against it."
|
|
283
|
+
),
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
def bind(
|
|
288
|
+
mesh: dict[str, Any],
|
|
289
|
+
bones: list[dict[str, Any]],
|
|
290
|
+
resolution: int = DEFAULT_RESOLUTION,
|
|
291
|
+
falloff_power: float = DEFAULT_FALLOFF_POWER,
|
|
292
|
+
max_influences: int = MAX_INFLUENCES,
|
|
293
|
+
components: list[dict[str, Any]] | None = None,
|
|
294
|
+
rigid_roles: frozenset[str] = RIGID_ROLES,
|
|
295
|
+
) -> dict[str, Any]:
|
|
296
|
+
"""Compute skin indices and weights for every vertex.
|
|
297
|
+
|
|
298
|
+
Each bone needs `id`, `jointPos` and `tipPos`. Weight falls off as 1/d**power in GEODESIC
|
|
299
|
+
distance, the top `max_influences` are kept and normalised, and a vertex no bone can reach through
|
|
300
|
+
the solid is reported rather than quietly pinned to the nearest bone in space -- being unreachable
|
|
301
|
+
usually means the mesh has a hole or a detached island, and that is worth knowing.
|
|
302
|
+
|
|
303
|
+
Pass `components` -- the component tree the mesh was built from -- and the result carries a
|
|
304
|
+
`bindingPartition` naming everything that must be rigidly parented instead of skinned, plus a
|
|
305
|
+
warning if any of it looks like it reached the mesh anyway. Without it the caller gets weights
|
|
306
|
+
for every vertex handed in and no signal at all that some of them should not have been, which is
|
|
307
|
+
the failure mode this whole rule exists to prevent: the geodesic path from the neck to a crown
|
|
308
|
+
vertex runs UP THROUGH THE SKULL, so hair takes real neck weight (8.1% on the test fixture) and
|
|
309
|
+
shears against the skull it sits on.
|
|
310
|
+
"""
|
|
311
|
+
vertices = mesh.get("vertices")
|
|
312
|
+
indices = mesh.get("indices")
|
|
313
|
+
if not isinstance(vertices, list) or not vertices:
|
|
314
|
+
raise ValueError("mesh.vertices must be a non-empty array")
|
|
315
|
+
if not isinstance(indices, list) or len(indices) < 3:
|
|
316
|
+
raise ValueError("mesh.indices must describe at least one triangle")
|
|
317
|
+
if not bones:
|
|
318
|
+
raise ValueError("at least one bone is required")
|
|
319
|
+
if resolution > MAX_RESOLUTION:
|
|
320
|
+
raise ValueError(f"resolution must not exceed {MAX_RESOLUTION}")
|
|
321
|
+
|
|
322
|
+
faces = _triangles(indices)
|
|
323
|
+
grid = VoxelGrid(vertices, faces, resolution)
|
|
324
|
+
|
|
325
|
+
fields: list[dict[tuple[int, int, int], float]] = []
|
|
326
|
+
unreachable_bones: list[str] = []
|
|
327
|
+
for bone in bones:
|
|
328
|
+
sources = _segment_voxels(grid, bone["jointPos"], bone["tipPos"])
|
|
329
|
+
field = geodesic_field(grid, sources)
|
|
330
|
+
if not field:
|
|
331
|
+
unreachable_bones.append(str(bone.get("id")))
|
|
332
|
+
fields.append(field)
|
|
333
|
+
|
|
334
|
+
skin_indices: list[list[int]] = []
|
|
335
|
+
skin_weights: list[list[float]] = []
|
|
336
|
+
unreachable_vertices = 0
|
|
337
|
+
for vertex in vertices:
|
|
338
|
+
cell = grid.index_of(vertex)
|
|
339
|
+
scored: list[tuple[float, int]] = []
|
|
340
|
+
for bone_index, field in enumerate(fields):
|
|
341
|
+
distance = field.get(cell)
|
|
342
|
+
if distance is None:
|
|
343
|
+
continue
|
|
344
|
+
# A vertex sitting on the bone itself would divide by zero; clamp to half a voxel, the
|
|
345
|
+
# finest distinction this grid can represent anyway.
|
|
346
|
+
scored.append((1.0 / max(distance, 0.5) ** falloff_power, bone_index))
|
|
347
|
+
if not scored:
|
|
348
|
+
unreachable_vertices += 1
|
|
349
|
+
skin_indices.append([0] * max_influences)
|
|
350
|
+
weights = [0.0] * max_influences
|
|
351
|
+
weights[0] = 1.0
|
|
352
|
+
skin_weights.append(weights)
|
|
353
|
+
continue
|
|
354
|
+
scored.sort(reverse=True)
|
|
355
|
+
kept = scored[:max_influences]
|
|
356
|
+
total = sum(weight for weight, _ in kept)
|
|
357
|
+
row_indices = [0] * max_influences
|
|
358
|
+
row_weights = [0.0] * max_influences
|
|
359
|
+
for slot, (weight, bone_index) in enumerate(kept):
|
|
360
|
+
row_indices[slot] = bone_index
|
|
361
|
+
row_weights[slot] = weight / total
|
|
362
|
+
skin_indices.append(row_indices)
|
|
363
|
+
skin_weights.append(row_weights)
|
|
364
|
+
|
|
365
|
+
partition = partition_for_binding(components, rigid_roles) if components is not None else None
|
|
366
|
+
partition_warnings: list[str] = []
|
|
367
|
+
rigid_pinned = 0
|
|
368
|
+
if partition and partition["rigidlyParented"]:
|
|
369
|
+
partition_warnings.append(
|
|
370
|
+
f"{len(partition['rigidlyParented'])} component(s) carry a rigid role "
|
|
371
|
+
f"({', '.join(sorted(rigid_roles))}) and are parented to a joint rather than skinned."
|
|
372
|
+
)
|
|
373
|
+
|
|
374
|
+
# EXCLUSION, not just a note. Reporting the partition and then handing back geodesic weights
|
|
375
|
+
# for those vertices anyway leaves the caller holding exactly the wrong numbers -- and the
|
|
376
|
+
# obvious thing to do with a returned weight array is to use it. A rigidly parented vertex
|
|
377
|
+
# gets weight 1.0 on the single joint it rides and nothing else, which IS rigid parenting
|
|
378
|
+
# written in the only language a skinned mesh speaks.
|
|
379
|
+
#
|
|
380
|
+
# This needs to know which vertex belongs to which component, so the mesh must carry
|
|
381
|
+
# `vertexComponents`, a component id per vertex. Without it the exclusion cannot be applied
|
|
382
|
+
# and that is said out loud rather than silently skipped.
|
|
383
|
+
rides = {entry["id"]: entry["parentJoint"] for entry in partition["rigidlyParented"]}
|
|
384
|
+
owners = mesh.get("vertexComponents")
|
|
385
|
+
if not isinstance(owners, list) or len(owners) != len(vertices):
|
|
386
|
+
partition_warnings.append(
|
|
387
|
+
"mesh has no `vertexComponents` (one component id per vertex), so the rigid "
|
|
388
|
+
"components above could NOT be excluded from these weights. Supply it, or bind "
|
|
389
|
+
"only the skinned components' geometry."
|
|
390
|
+
)
|
|
391
|
+
else:
|
|
392
|
+
bone_slot = {str(bone.get("id")): index for index, bone in enumerate(bones)}
|
|
393
|
+
for index, owner in enumerate(owners):
|
|
394
|
+
joint = rides.get(str(owner))
|
|
395
|
+
if joint is None:
|
|
396
|
+
continue
|
|
397
|
+
slot = bone_slot.get(str(joint))
|
|
398
|
+
if slot is None:
|
|
399
|
+
partition_warnings.append(
|
|
400
|
+
f"component {owner!r} rides joint {joint!r}, which is not among the bones "
|
|
401
|
+
f"supplied; its vertices keep their geodesic weights"
|
|
402
|
+
)
|
|
403
|
+
continue
|
|
404
|
+
skin_indices[index] = [slot] + [0] * (max_influences - 1)
|
|
405
|
+
skin_weights[index] = [1.0] + [0.0] * (max_influences - 1)
|
|
406
|
+
rigid_pinned += 1
|
|
407
|
+
|
|
408
|
+
return {
|
|
409
|
+
"skinIndices": skin_indices,
|
|
410
|
+
"skinWeights": skin_weights,
|
|
411
|
+
"bindingPartition": partition,
|
|
412
|
+
"partitionWarnings": partition_warnings + (partition["warnings"] if partition else []),
|
|
413
|
+
"rigidPinnedVertexCount": rigid_pinned,
|
|
414
|
+
"boneOrder": [str(bone.get("id")) for bone in bones],
|
|
415
|
+
"resolution": resolution,
|
|
416
|
+
"voxelStep": grid.step,
|
|
417
|
+
"solidVoxelCount": len(grid.solid),
|
|
418
|
+
"surfaceVoxelCount": len(grid.surface),
|
|
419
|
+
"unreachableVertexCount": unreachable_vertices,
|
|
420
|
+
"unreachableBones": unreachable_bones,
|
|
421
|
+
"maxWeightError": max(
|
|
422
|
+
abs(sum(row) - 1.0) for row in skin_weights
|
|
423
|
+
) if skin_weights else 0.0,
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
|
|
427
|
+
def euclidean_bind(
|
|
428
|
+
mesh: dict[str, Any],
|
|
429
|
+
bones: list[dict[str, Any]],
|
|
430
|
+
falloff_power: float = DEFAULT_FALLOFF_POWER,
|
|
431
|
+
max_influences: int = MAX_INFLUENCES,
|
|
432
|
+
) -> dict[str, Any]:
|
|
433
|
+
"""The straight-line binding this module replaces, kept so the difference can be MEASURED.
|
|
434
|
+
|
|
435
|
+
Without it the claim "geodesic stops weights leaking across a gap" is an assertion. With it a test
|
|
436
|
+
can bind the same mesh both ways and show the leak in one and not the other.
|
|
437
|
+
"""
|
|
438
|
+
|
|
439
|
+
def point_to_segment(point: list[float], a: list[float], b: list[float]) -> float:
|
|
440
|
+
ab = [b[k] - a[k] for k in range(3)]
|
|
441
|
+
ap = [point[k] - a[k] for k in range(3)]
|
|
442
|
+
denominator = sum(component * component for component in ab)
|
|
443
|
+
t = 0.0 if denominator <= 1e-12 else max(0.0, min(1.0, sum(ap[k] * ab[k] for k in range(3)) / denominator))
|
|
444
|
+
closest = [a[k] + ab[k] * t for k in range(3)]
|
|
445
|
+
return math.dist(point, closest)
|
|
446
|
+
|
|
447
|
+
vertices = mesh["vertices"]
|
|
448
|
+
skin_indices: list[list[int]] = []
|
|
449
|
+
skin_weights: list[list[float]] = []
|
|
450
|
+
for vertex in vertices:
|
|
451
|
+
scored = [
|
|
452
|
+
(1.0 / max(point_to_segment(vertex, bone["jointPos"], bone["tipPos"]), 1e-6) ** falloff_power, index)
|
|
453
|
+
for index, bone in enumerate(bones)
|
|
454
|
+
]
|
|
455
|
+
scored.sort(reverse=True)
|
|
456
|
+
kept = scored[:max_influences]
|
|
457
|
+
total = sum(weight for weight, _ in kept) or 1.0
|
|
458
|
+
row_indices = [0] * max_influences
|
|
459
|
+
row_weights = [0.0] * max_influences
|
|
460
|
+
for slot, (weight, bone_index) in enumerate(kept):
|
|
461
|
+
row_indices[slot] = bone_index
|
|
462
|
+
row_weights[slot] = weight / total
|
|
463
|
+
skin_indices.append(row_indices)
|
|
464
|
+
skin_weights.append(row_weights)
|
|
465
|
+
return {"skinIndices": skin_indices, "skinWeights": skin_weights,
|
|
466
|
+
"boneOrder": [str(bone.get("id")) for bone in bones]}
|
|
467
|
+
|
|
468
|
+
|
|
469
|
+
def _format_summary(result: dict[str, Any]) -> str:
|
|
470
|
+
lines = [
|
|
471
|
+
f"bones: {len(result['boneOrder'])}",
|
|
472
|
+
f"grid: {result['resolution']} ({result['solidVoxelCount']} solid voxels)",
|
|
473
|
+
f"max |sum(w) - 1|: {result['maxWeightError']:.3e}",
|
|
474
|
+
]
|
|
475
|
+
if result["unreachableVertexCount"]:
|
|
476
|
+
lines.append(
|
|
477
|
+
f"UNREACHABLE vertices: {result['unreachableVertexCount']} -- no bone reaches them through "
|
|
478
|
+
"the solid, which usually means a hole or a detached island in the mesh"
|
|
479
|
+
)
|
|
480
|
+
if result["unreachableBones"]:
|
|
481
|
+
lines.append(f"UNREACHABLE bones (outside the solid): {result['unreachableBones']}")
|
|
482
|
+
return "\n".join(lines)
|
|
483
|
+
|
|
484
|
+
|
|
485
|
+
def main(argv: list[str]) -> int:
|
|
486
|
+
parser = argparse.ArgumentParser(description="Bind skin weights by geodesic voxel distance.")
|
|
487
|
+
parser.add_argument("mesh", type=Path, help="JSON with vertices and indices")
|
|
488
|
+
parser.add_argument("--bones", type=Path, required=True, help="JSON array of bones")
|
|
489
|
+
parser.add_argument("--resolution", type=int, default=DEFAULT_RESOLUTION)
|
|
490
|
+
parser.add_argument("--out", type=Path)
|
|
491
|
+
parser.add_argument("--json", action="store_true")
|
|
492
|
+
args = parser.parse_args(argv)
|
|
493
|
+
try:
|
|
494
|
+
mesh = json.loads(args.mesh.read_text())
|
|
495
|
+
if isinstance(mesh, dict) and isinstance(mesh.get("meshes"), list) and mesh["meshes"]:
|
|
496
|
+
mesh = mesh["meshes"][0]
|
|
497
|
+
result = bind(mesh, json.loads(args.bones.read_text()), args.resolution)
|
|
498
|
+
except Exception as exc:
|
|
499
|
+
print(f"error: {exc}", file=sys.stderr)
|
|
500
|
+
return 2
|
|
501
|
+
if args.out:
|
|
502
|
+
args.out.write_text(json.dumps(result))
|
|
503
|
+
print(json.dumps(result, indent=2) if args.json else _format_summary(result))
|
|
504
|
+
return 1 if result["unreachableVertexCount"] or result["unreachableBones"] else 0
|
|
505
|
+
|
|
506
|
+
|
|
507
|
+
if __name__ == "__main__":
|
|
508
|
+
raise SystemExit(main(sys.argv[1:]))
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
"""RigSpec data model for the Milestone 0 rig kill test.
|
|
2
|
+
|
|
3
|
+
This is the schema from docs/PLAN_1.5_ANIMATION_READY_RIGS.md §6, transcribed
|
|
4
|
+
as-is (field names, optionality, semantics). It is NOT a competing schema —
|
|
5
|
+
where the plan's TypeScript type left something ambiguous for a 3-bone case,
|
|
6
|
+
the ambiguity and the reading chosen are called out explicitly below and in
|
|
7
|
+
forge/tests/test_rig_milestone0.py.
|
|
8
|
+
|
|
9
|
+
Pure Python 3.10+ stdlib. No pip installs.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
from dataclasses import dataclass, field
|
|
15
|
+
from typing import Literal, Optional
|
|
16
|
+
|
|
17
|
+
BindPose = Literal["T", "A"]
|
|
18
|
+
Forward = Literal["+Z", "-Z"]
|
|
19
|
+
Role = Literal["skinned", "attachment"]
|
|
20
|
+
Chain = Literal["spine", "head", "arm", "leg", "tail", "wing", "digit", "prop"]
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass
|
|
24
|
+
class Ellipsoid:
|
|
25
|
+
center: tuple[float, float, float]
|
|
26
|
+
axis: tuple[float, float, float]
|
|
27
|
+
semi_axes: tuple[float, float, float]
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@dataclass
|
|
31
|
+
class IkSpec:
|
|
32
|
+
is_effector: bool
|
|
33
|
+
target_bone_id: Optional[str] = None
|
|
34
|
+
rotation_min: Optional[tuple[float, float, float]] = None
|
|
35
|
+
rotation_max: Optional[tuple[float, float, float]] = None
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@dataclass
|
|
39
|
+
class BoneSpec:
|
|
40
|
+
"""Mirrors PLAN_1.5 §6 `BoneSpec` field-for-field."""
|
|
41
|
+
|
|
42
|
+
id: str
|
|
43
|
+
parent: Optional[str]
|
|
44
|
+
joint_pos: tuple[float, float, float]
|
|
45
|
+
component: Optional[str]
|
|
46
|
+
role: Role
|
|
47
|
+
chain: Chain
|
|
48
|
+
# Optional. "Defaults to the child's jointPos" per the plan. That default
|
|
49
|
+
# is well-defined only when the bone has exactly one child. See
|
|
50
|
+
# RigSpec.resolve_tip_positions() for the reading chosen when a bone has
|
|
51
|
+
# zero children (a leaf) or more than one.
|
|
52
|
+
tip_pos: Optional[tuple[float, float, float]] = None
|
|
53
|
+
ellipsoids: list[Ellipsoid] = field(default_factory=list)
|
|
54
|
+
ik: Optional[IkSpec] = None
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
@dataclass
|
|
58
|
+
class RigSpec:
|
|
59
|
+
"""Mirrors PLAN_1.5 §6 `RigSpec` field-for-field."""
|
|
60
|
+
|
|
61
|
+
version: str
|
|
62
|
+
bind_pose: BindPose
|
|
63
|
+
forward: Forward
|
|
64
|
+
bones: list[BoneSpec]
|
|
65
|
+
|
|
66
|
+
def bone_by_id(self) -> dict[str, BoneSpec]:
|
|
67
|
+
return {b.id: b for b in self.bones}
|
|
68
|
+
|
|
69
|
+
def children_of(self, bone_id: str) -> list[BoneSpec]:
|
|
70
|
+
return [b for b in self.bones if b.parent == bone_id]
|
|
71
|
+
|
|
72
|
+
def root(self) -> BoneSpec:
|
|
73
|
+
roots = [b for b in self.bones if b.parent is None]
|
|
74
|
+
if len(roots) != 1:
|
|
75
|
+
raise ValueError(
|
|
76
|
+
f"RigSpec must have exactly one root bone (parent: null), found {len(roots)}"
|
|
77
|
+
)
|
|
78
|
+
return roots[0]
|
|
79
|
+
|
|
80
|
+
def resolve_tip_positions(self) -> dict[str, tuple[float, float, float]]:
|
|
81
|
+
"""Resolve every bone's segment end point.
|
|
82
|
+
|
|
83
|
+
READING CHOSEN (schema ambiguity, PLAN_1.5 §6):
|
|
84
|
+
|
|
85
|
+
The plan says tipPos "Defaults to the child's jointPos" but does not
|
|
86
|
+
say what happens for a bone with zero children (a leaf) or more than
|
|
87
|
+
one child. The minimal reading adopted here, applied uniformly and
|
|
88
|
+
fail-closed rather than silently guessing:
|
|
89
|
+
|
|
90
|
+
- exactly one child, no explicit tipPos -> default to that child's jointPos
|
|
91
|
+
- explicit tipPos given -> always wins, no defaulting
|
|
92
|
+
- zero children (leaf) and no tipPos -> REJECTED. A leaf skinned
|
|
93
|
+
bone has nothing to default from, so the spec author must supply
|
|
94
|
+
tipPos explicitly. This is a spec-authoring responsibility, not
|
|
95
|
+
something the emitter may invent (Pillar 2 — the emitter is
|
|
96
|
+
deterministic code, it does not propose geometry).
|
|
97
|
+
- more than one child and no tipPos -> REJECTED. "the child's
|
|
98
|
+
jointPos" is only well-defined for a single child; defaulting to
|
|
99
|
+
an arbitrary one would be a silent, unreproducible choice.
|
|
100
|
+
"""
|
|
101
|
+
by_id = self.bone_by_id()
|
|
102
|
+
resolved: dict[str, tuple[float, float, float]] = {}
|
|
103
|
+
for bone in self.bones:
|
|
104
|
+
if bone.tip_pos is not None:
|
|
105
|
+
resolved[bone.id] = bone.tip_pos
|
|
106
|
+
continue
|
|
107
|
+
children = self.children_of(bone.id)
|
|
108
|
+
if len(children) == 1:
|
|
109
|
+
resolved[bone.id] = by_id[children[0].id].joint_pos
|
|
110
|
+
elif len(children) == 0:
|
|
111
|
+
raise ValueError(
|
|
112
|
+
f"bone '{bone.id}' is a leaf with no tipPos: leaf bones must "
|
|
113
|
+
"author tipPos explicitly (PLAN_1.5 §6 default only covers "
|
|
114
|
+
"the single-child case)"
|
|
115
|
+
)
|
|
116
|
+
else:
|
|
117
|
+
raise ValueError(
|
|
118
|
+
f"bone '{bone.id}' has {len(children)} children and no explicit "
|
|
119
|
+
"tipPos: the child-default is only well-defined for exactly one child"
|
|
120
|
+
)
|
|
121
|
+
return resolved
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def validate_rig_spec(spec: RigSpec) -> list[str]:
|
|
125
|
+
"""Minimal semantic gate for Milestone 0 (a scaled-down stand-in for the
|
|
126
|
+
full Joint Admission Gate Half A in PLAN_1.5 §5.2 — WS-B is out of scope
|
|
127
|
+
here). Returns a list of error strings; empty list means valid.
|
|
128
|
+
Fail-closed: callers must treat a non-empty list as a hard rejection.
|
|
129
|
+
"""
|
|
130
|
+
errors: list[str] = []
|
|
131
|
+
|
|
132
|
+
ids = [b.id for b in spec.bones]
|
|
133
|
+
if len(ids) != len(set(ids)):
|
|
134
|
+
dupes = sorted({i for i in ids if ids.count(i) > 1})
|
|
135
|
+
errors.append(f"NAME_UNIQUENESS: duplicate bone id(s) {dupes}")
|
|
136
|
+
|
|
137
|
+
roots = [b for b in spec.bones if b.parent is None]
|
|
138
|
+
if len(roots) != 1:
|
|
139
|
+
errors.append(f"exactly one root bone required (parent: null), found {len(roots)}")
|
|
140
|
+
|
|
141
|
+
id_set = set(ids)
|
|
142
|
+
for bone in spec.bones:
|
|
143
|
+
if bone.parent is not None and bone.parent not in id_set:
|
|
144
|
+
errors.append(f"bone '{bone.id}' has unresolved parent '{bone.parent}'")
|
|
145
|
+
|
|
146
|
+
if spec.version != "1.0":
|
|
147
|
+
errors.append(f"unsupported RigSpec version '{spec.version}', expected '1.0'")
|
|
148
|
+
|
|
149
|
+
if not errors:
|
|
150
|
+
try:
|
|
151
|
+
spec.resolve_tip_positions()
|
|
152
|
+
except ValueError as exc:
|
|
153
|
+
errors.append(str(exc))
|
|
154
|
+
|
|
155
|
+
return errors
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def derive_envelope_radius(
|
|
159
|
+
width: float,
|
|
160
|
+
depth: float,
|
|
161
|
+
overlap_factor: float = 1.2,
|
|
162
|
+
) -> float:
|
|
163
|
+
"""PLAN_1.5 §4.3 — envelope radius is DERIVED, never proposed.
|
|
164
|
+
|
|
165
|
+
R_b = 0.5 * max(W_component, D_component) * F
|
|
166
|
+
|
|
167
|
+
`width`/`depth` are the component bounding-box extents perpendicular to
|
|
168
|
+
the bone axis; `overlap_factor` is F (plan default 1.2).
|
|
169
|
+
"""
|
|
170
|
+
if width <= 0 or depth <= 0:
|
|
171
|
+
raise ValueError(f"component extents must be positive, got width={width} depth={depth}")
|
|
172
|
+
if overlap_factor <= 0:
|
|
173
|
+
raise ValueError(f"overlap_factor must be positive, got {overlap_factor}")
|
|
174
|
+
return 0.5 * max(width, depth) * overlap_factor
|