1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
use crate::engine::ecs::ComponentId;
use crate::engine::ecs::component::{Component, ComponentRef};
#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) struct TwoBoneIkDebugVisuals {
pub target_line: ComponentId,
pub pole_line: ComponentId,
pub plane_normal_line: ComponentId,
pub elbow_line: ComponentId,
pub elbow_point: ComponentId,
}
/// Solver configuration for an `IKChainComponent`.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum IKSolver {
/// Single-bone pose match.
///
/// Sets the root joint's world rotation to match the target TC's world rotation,
/// post-multiplied by a fixed yaw offset. Used for neck/head alignment from InputXR.
///
/// `offset_yaw`: rotation applied after copying target world rotation.
/// Use `std::f32::consts::PI` for the OpenXR (−Z forward) → VRM (+Z forward) flip.
///
/// `copy_position`: when true, also overrides the joint's world position to the
/// target's world position. Required for HMD-driven head bones so the bone tracks
/// physical head translation (HMD moves forward+down when you pitch), not just
/// rotation. Visually detaches the bone from its FK parent until a spine FABRIK
/// solver bends the chain to follow. Default false (rotation-only behavior).
///
/// `target_position_offset`: offset applied in the **target's local frame** before
/// copying its world position. Used to compensate for the gap between the head
/// bone pivot (typically at the skull base) and the camera/eye position: passing
/// `(0, -eye_height, 0)` shifts the bone down so the eye mesh (which sits above
/// the bone pivot) lands at the HMD position. Ignored when `copy_position` is
/// false.
AimConstraint {
offset_yaw: f32,
copy_position: bool,
target_position_offset: [f32; 3],
},
/// Closed-form 2-bone IK.
///
/// Used for arms: UpperArm → LowerArm → Hand. All three joints are referenced
/// by explicit `ComponentId` — the solver does NO topology discovery and is
/// resilient to sibling helper / collider / cloth bones under the arm joints.
/// The chain's `parent_of` is ignored for this solver; `end_effector_id` (the
/// hand) lives on `IKChainComponent`, root + mid are here on the variant.
///
/// `root_joint_id`: upper-arm TC (chain root).
/// `mid_joint_id`: lower-arm TC (elbow).
/// `pole_direction`: direction hint for the middle joint (elbow / knee).
/// Interpreted in body-local space when an ancestor `AvatarControlComponent`
/// exists, otherwise world-space. Body-local mode rotates the pole by the
/// model root's world rotation each tick so the elbow stays anatomically
/// correct when the body turns.
/// `copy_end_rotation`: if true, also aligns the end-effector bone to the target's rotation.
TwoBoneIK {
root_joint_id: ComponentId,
mid_joint_id: ComponentId,
pole_direction: [f32; 3],
copy_end_rotation: bool,
},
/// Iterative FABRIK solver — works for any chain length ≥ 2.
///
/// Used for spine bending: chain hips → ... → head_mount with the head pose
/// driver as the target. The spine rotates so the end-effector (head_mount)
/// FK-lands at the target position.
///
/// `target_position_offset`: same semantics as `AimConstraint` — offset in the
/// target's local frame, added to its world position before chasing. Used to
/// shift the target down by `eye_offset` so the head bone pivot (not the eye
/// mesh above it) lines up with the HMD position.
Fabrik {
max_iterations: u32,
tolerance: f32,
target_position_offset: [f32; 3],
},
}
/// Marks the root joint of an IK chain.
///
/// Place this as a **child of the root joint TC** (e.g. `J_Bip_L_UpperArm`, `head_mount`).
/// The IKSystem finds this component, reads its parent TC as the root joint, walks down to
/// `end_effector_id` to collect the chain, reads the target pose from `target_id`, solves,
/// and emits `UpdateTransform` for each joint.
///
/// All three solver types are expressed through this single component; no separate
/// end-effector or pole-vector marker components are required.
#[derive(Debug, Clone)]
pub struct IKChainComponent {
/// Which solver to run.
pub solver: IKSolver,
/// TC whose world pose is the IK target this frame.
///
/// For `AimConstraint`: target world rotation is read here.
/// For `TwoBoneIK` / `Fabrik`: target world position (and optionally rotation) is read here.
pub target_id: ComponentId,
/// TC at the end of the bone chain.
///
/// For `AimConstraint`: set to the root joint itself (chain length = 1).
/// For `TwoBoneIK`: set to the hand/foot bone (2 TCs below the root joint).
/// For `Fabrik`: set to the last bone in the spine/neck chain.
pub end_effector_id: ComponentId,
/// Blend weight: 0.0 = no IK applied, 1.0 = full solve.
pub weight: f32,
/// Authored form of `target_id` for round-trip dump. `None` for
/// IKChains wired purely at runtime (e.g. by `AvatarControlSystem`),
/// which have no MMS source to preserve.
pub target_source: Option<ComponentRef>,
/// Authored form of `end_effector_id` for round-trip dump.
pub end_effector_source: Option<ComponentRef>,
/// Cached ancestor `AvatarControlComponent` ID, discovered by `IKSystem`
/// on first tick via a parent-chain walk. When `Some`, the solver
/// transforms `TwoBoneIK.pole_direction` from body-local to world space
/// using the AVC's model root rotation. `None` → world-space pole
/// (current behavior for non-AVC chains).
pub(crate) avc_id: Option<ComponentId>,
/// Cached InputXR/XRHand component governing this runtime AVC target.
pub(crate) xr_pose_driver: Option<ComponentId>,
/// Lazily created runtime-only debug visual ids for TwoBoneIK inspection.
pub(crate) two_bone_debug_visuals: Option<TwoBoneIkDebugVisuals>,
component: Option<ComponentId>,
}
impl IKChainComponent {
pub fn new(solver: IKSolver, target_id: ComponentId, end_effector_id: ComponentId) -> Self {
Self {
solver,
target_id,
end_effector_id,
weight: 1.0,
target_source: None,
end_effector_source: None,
avc_id: None,
xr_pose_driver: None,
two_bone_debug_visuals: None,
component: None,
}
}
pub fn with_weight(mut self, w: f32) -> Self {
self.weight = w;
self
}
pub fn with_target_source(mut self, src: ComponentRef) -> Self {
self.target_source = Some(src);
self
}
pub fn with_end_effector_source(mut self, src: ComponentRef) -> Self {
self.end_effector_source = Some(src);
self
}
}
impl Component for IKChainComponent {
fn name(&self) -> &'static str {
"ik_chain"
}
fn set_id(&mut self, id: ComponentId) {
self.component = Some(id);
}
fn init(&mut self, emit: &mut dyn crate::engine::ecs::SignalEmitter, component: ComponentId) {
emit.push_intent_now(
component,
crate::engine::ecs::IntentValue::RegisterIkChain {
component_id: component,
},
);
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
self
}
fn to_mms_ast(
&self,
_world: &crate::engine::ecs::World,
) -> crate::scripting::ast::ComponentExpression {
use crate::engine::ecs::component::ce_helpers::*;
use crate::scripting::ast::Expression;
let solver_call = match self.solver {
IKSolver::AimConstraint {
offset_yaw,
copy_position,
target_position_offset,
} => (
"aim_constraint",
vec![
num(offset_yaw as f64),
b(copy_position),
array(nums(target_position_offset.iter().map(|&v| v as f64))),
],
),
IKSolver::TwoBoneIK {
pole_direction,
copy_end_rotation,
..
} => (
"two_bone_ik",
vec![
array(nums(pole_direction.iter().map(|&v| v as f64))),
b(copy_end_rotation),
],
),
IKSolver::Fabrik {
max_iterations,
tolerance,
target_position_offset,
} => (
"fabrik",
vec![
num(max_iterations as f64),
num(tolerance as f64),
array(nums(target_position_offset.iter().map(|&v| v as f64))),
],
),
};
fn target_expr(t: &ComponentRef) -> Expression {
match t {
ComponentRef::Guid(u) => Expression::String(format!("@uuid:{u}")),
ComponentRef::Query(s) => Expression::String(s.clone()),
}
}
let mut ce = ce_call("IKChain", solver_call.0, solver_call.1)
.with_call("weight", vec![num(self.weight as f64)]);
if let Some(src) = &self.target_source {
ce = ce.with_call("target", vec![target_expr(src)]);
}
if let Some(src) = &self.end_effector_source {
ce = ce.with_call("end_effector", vec![target_expr(src)]);
}
ce
}
}