1use super::ConstraintEntry;
18use crate::feature_pipeline::component::ComponentRecord;
19use crate::feature_pipeline::{Env, SceneMap};
20use crate::{
21 resolve_edge_selection, resolve_face_selection, resolve_named_selection,
22 resolve_vertex_selection, AffineTransform, MateAlign, MateKind, SelectionGeometry, Vec3,
23};
24
25#[derive(Debug, Clone)]
27pub(super) struct ConstraintFailure {
28 pub status: &'static str,
29 pub message: String,
30}
31
32impl ConstraintFailure {
33 pub fn new(status: &'static str, message: impl Into<String>) -> Self {
34 Self {
35 status,
36 message: message.into(),
37 }
38 }
39 pub(super) fn unsupported(message: impl Into<String>) -> Self {
40 Self::new("unsupported-selection", message)
41 }
42 pub(super) fn invalid(message: impl Into<String>) -> Self {
43 Self::new("invalid-selection", message)
44 }
45}
46
47#[derive(Debug, Clone)]
55pub(super) struct ResolvedElement {
56 pub name: String,
57 pub component: String,
58 pub world: SelectionGeometry,
59 pub local: SelectionGeometry,
60 pub transform: AffineTransform,
61 pub curve: Option<crate::MateCurve>,
64 pub freeform: Option<ConstraintFailure>,
68}
69
70pub(super) fn resolve_element(
74 scene: &SceneMap,
75 name: &str,
76) -> Result<ResolvedElement, ConstraintFailure> {
77 let record = scene.owning_component(name).ok_or_else(|| {
78 ConstraintFailure::invalid(format!(
79 "selection '{name}' does not belong to an assembly component — only component geometry participates in constraints"
80 ))
81 })?;
82 if let Some(follow) = &record.pattern {
83 return Err(ConstraintFailure::invalid(format!(
84 "'{}' is instance {} of pattern {}: it follows its seed {} and takes no mates of its own — mate {} instead",
85 record.id, follow.key, follow.pattern_id, follow.seed, follow.seed
86 )));
87 }
88 let curve = edge_curve(scene, name, &record.transform)?;
89 let (world, freeform) = match resolve_world_geometry(scene, name, record) {
90 Ok(world) => (world, None),
91 Err(failure) if failure.status == "unsupported-selection" && curve.is_some() => {
92 let chord = curve.as_ref().and_then(|c| {
93 let mid = c.curve.evaluate(0.5 * (c.t0 + c.t1)).ok()?;
94 Some(record.transform.point(mid))
95 });
96 match chord {
97 Some(position) => (SelectionGeometry::Point { position }, Some(failure)),
98 None => return Err(failure),
99 }
100 }
101 Err(failure) => return Err(failure),
102 };
103 let inverse = record.transform.rigid_inverse().map_err(|error| {
104 ConstraintFailure::new(
105 "error",
106 format!("component '{}': non-rigid pose: {error}", record.id),
107 )
108 })?;
109 let local = world.transformed(&inverse).map_err(|error| {
110 ConstraintFailure::new("error", format!("selection '{name}': {error}"))
111 })?;
112 Ok(ResolvedElement {
113 curve,
114 freeform,
115 name: name.to_string(),
116 component: record.id.clone(),
117 world,
118 local,
119 transform: record.transform,
120 })
121}
122
123fn edge_curve(
126 scene: &SceneMap,
127 name: &str,
128 transform: &AffineTransform,
129) -> Result<Option<crate::MateCurve>, ConstraintFailure> {
130 let Some(edge) = scene.resolve_edge(name) else { return Ok(None) };
131 let inverse = transform.rigid_inverse().map_err(ConstraintFailure::invalid)?;
132 crate::with_registered_solid_str(edge.handle, |solid| {
133 let Some(record) = solid.edges.iter().find(|record| record.id == edge.edge_id) else {
134 return Ok(None);
135 };
136 let curve = crate::transform_topology::transform_curve(&record.curve, inverse)?;
137 Ok(Some(crate::MateCurve { curve, t0: record.t0, t1: record.t1 }))
138 })
139 .map_err(ConstraintFailure::invalid)
140}
141
142fn resolve_world_geometry(
143 scene: &SceneMap,
144 name: &str,
145 record: &ComponentRecord,
146) -> Result<SelectionGeometry, ConstraintFailure> {
147 if let Some((solid_name, coords)) = name.split_once('@') {
149 let handle = scene.resolve_solid(solid_name).ok_or_else(|| {
150 ConstraintFailure::invalid(format!("vertex ref '{name}': unknown solid '{solid_name}'"))
151 })?;
152 let local = parse_triple(coords).ok_or_else(|| {
153 ConstraintFailure::invalid(format!(
154 "vertex ref '{name}': position must be 'x,y,z' numbers"
155 ))
156 })?;
157 let world_query = record.transform.point(local);
158 return crate::with_registered_solid_str(handle, |solid| {
159 Ok(resolve_vertex_selection(solid, world_query))
160 })
161 .map_err(ConstraintFailure::invalid)?
162 .map_err(|error| ConstraintFailure::new(error.status(), error.to_string()));
163 }
164
165 if scene.namespace.names_component(name) {
169 let prefix = format!("{name}:");
170 let members: Vec<(String, u32)> = scene
171 .component_solids(&record.id)
172 .into_iter()
173 .filter(|(member, _)| record.id == name || member.starts_with(&prefix))
174 .collect();
175 if members.is_empty() {
176 return Err(ConstraintFailure::invalid(format!(
177 "component ref '{name}' has no member solids"
178 )));
179 }
180 return component_point(&members);
181 }
182
183 if let Some(face) = scene.resolve_face(name) {
186 return crate::with_registered_solid_str(face.handle, |solid| {
187 Ok(resolve_face_selection(solid, face.face_id))
188 })
189 .map_err(ConstraintFailure::invalid)?
190 .map_err(|error| ConstraintFailure::new(error.status(), error.to_string()));
191 }
192 if let Some(edge) = scene.resolve_edge(name) {
193 return crate::with_registered_solid_str(edge.handle, |solid| {
194 Ok(resolve_edge_selection(solid, edge.edge_id))
195 })
196 .map_err(ConstraintFailure::invalid)?
197 .map_err(|error| ConstraintFailure::new(error.status(), error.to_string()));
198 }
199 if let Some(handle) = scene.resolve_solid(name) {
202 return component_point(&[(name.to_string(), handle)]);
203 }
204 for (_member, handle) in scene.component_solids(&record.id) {
207 let found = crate::with_registered_solid_str(handle, |solid| {
208 Ok(resolve_named_selection(solid, name).ok())
209 })
210 .map_err(ConstraintFailure::invalid)?;
211 if let Some(geometry) = found {
212 return Ok(geometry);
213 }
214 }
215 Err(ConstraintFailure::invalid(format!(
216 "selection '{name}' not found in the scene"
217 )))
218}
219
220fn component_point(members: &[(String, u32)]) -> Result<SelectionGeometry, ConstraintFailure> {
225 let mut low = Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY);
226 let mut high = Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
227 let mut any = false;
228 for (member, handle) in members {
229 let (lo, hi, non_empty) = crate::with_registered_solid_str(*handle, |solid| {
230 let mut lo = Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY);
231 let mut hi = Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
232 let mut non_empty = false;
233 let mut include = |point: Vec3| {
234 lo = Vec3::new(lo.x.min(point.x), lo.y.min(point.y), lo.z.min(point.z));
235 hi = Vec3::new(hi.x.max(point.x), hi.y.max(point.y), hi.z.max(point.z));
236 non_empty = true;
237 };
238 for vertex in &solid.vertices {
239 include(vertex.point);
240 }
241 for shell in &solid.shells {
242 for face in &shell.faces {
243 for row in &face.surface.control_points {
244 for control in row {
245 include(control.point()?);
246 }
247 }
248 }
249 }
250 Ok((lo, hi, non_empty))
251 })
252 .map_err(|error| {
253 ConstraintFailure::invalid(format!("component member '{member}': {error}"))
254 })?;
255 if non_empty {
256 low = Vec3::new(low.x.min(lo.x), low.y.min(lo.y), low.z.min(lo.z));
257 high = Vec3::new(high.x.max(hi.x), high.y.max(hi.y), high.z.max(hi.z));
258 any = true;
259 }
260 }
261 if !any {
262 return Err(ConstraintFailure::invalid(
263 "component has no geometry to anchor",
264 ));
265 }
266 Ok(SelectionGeometry::Point {
267 position: low.add(high).scale(0.5),
268 })
269}
270
271fn parse_triple(coords: &str) -> Option<Vec3> {
272 let mut parts = coords.split(',').map(str::trim);
273 let x = parts.next()?.parse::<f64>().ok()?;
274 let y = parts.next()?.parse::<f64>().ok()?;
275 let z = parts.next()?.parse::<f64>().ok()?;
276 if parts.next().is_some() {
277 return None;
278 }
279 Some(Vec3::new(x, y, z))
280}
281
282#[derive(Debug, Clone)]
288pub(super) struct MappedMate {
289 pub body_a: String,
290 pub body_b: String,
291 pub body_c: Option<String>,
294 pub kind: MateKind,
295}
296
297#[derive(Debug, Clone, Default)]
301pub(super) struct MappedConstraint {
302 pub mates: Vec<MappedMate>,
303 pub pending_params: Vec<(String, serde_json::Value)>,
304 pub pending_persistent: Vec<(String, serde_json::Value)>,
305 pub measured: Option<(f64, &'static str)>,
308 pub target: Option<f64>,
310 pub angle_axis: Option<Vec3>,
312 pub groups: Vec<Vec<usize>>,
316 pub note: Option<String>,
320}
321
322pub(super) fn map_constraint(
328 entry: &mut ConstraintEntry,
329 resolved: &[ResolvedElement],
330 env: &Env,
331) -> Result<MappedConstraint, ConstraintFailure> {
332 let pair = || -> Result<(&ResolvedElement, &ResolvedElement), ConstraintFailure> {
334 match resolved {
335 [a, b] => Ok((a, b)),
336 _ => Err(ConstraintFailure::invalid(format!(
337 "{} takes exactly two elements ({} given)",
338 entry.constraint_type,
339 resolved.len()
340 ))),
341 }
342 };
343 if !matches!(entry.constraint_type.as_str(), "path" | "cam") {
345 if let Some(refusal) = resolved.iter().find_map(|element| element.freeform.clone()) {
346 return Err(refusal);
347 }
348 }
349 match entry.constraint_type.as_str() {
350 "coincident" => {
351 let (a, b) = pair()?;
352 super::constraints::coincident::map_entry(entry, a, b)
353 }
354 "touch_align" => {
355 let (a, b) = pair()?;
356 super::constraints::touch_align::map(entry, a, b)
357 }
358 "parallel" => {
359 let (a, b) = pair()?;
360 super::constraints::parallel::map(entry, a, b)
361 }
362 "distance" => {
363 let (a, b) = pair()?;
364 let mut mapped = super::constraints::distance::map(entry, a, b, env)?;
365 super::constraints::apply_limit(entry, &mut mapped, env, |value| value)?;
366 Ok(mapped)
367 }
368 "angle" => {
369 let (a, b) = pair()?;
370 let mut mapped = super::constraints::angle::map(entry, a, b, env)?;
371 let exterior = entry.flag("exteriorAngle");
372 super::constraints::apply_limit(entry, &mut mapped, env, |value| {
373 if exterior { 180.0 - value } else { value }
374 })?;
375 Ok(mapped)
376 }
377 "concentric" => {
378 let (a, b) = pair()?;
379 super::constraints::concentric::map(entry, a, b)
380 }
381 "perpendicular" => pair().and_then(|(a, b)| super::constraints::perpendicular::map(a, b)),
382 "tangent" => pair().and_then(|(a, b)| super::constraints::tangent::map(a, b)),
383 "center" => super::constraints::center::map(entry, resolved),
384 "symmetric" => super::constraints::symmetric::map(resolved),
385 "gear" => {
386 let (a, b) = pair()?;
387 super::constraints::gear::map(entry, a, b, env)
388 }
389 "rack_pinion" => {
390 let (a, b) = pair()?;
391 super::constraints::rack_pinion::map(entry, a, b, env)
392 }
393 "screw" => {
394 let (a, b) = pair()?;
395 super::constraints::screw::map(entry, a, b, env)
396 }
397 "path" => {
398 let (a, b) = pair()?;
399 super::constraints::path::map(entry, a, b, env)
400 }
401 "slot" => super::constraints::slot::map(entry, resolved, env),
402 "cam" => {
403 let (a, b) = pair()?;
404 super::constraints::cam::map(entry, a, b, env)
405 }
406 other => Err(ConstraintFailure::new(
407 "error",
408 format!("Unknown constraint type: {other}"),
409 )),
410 }
411}
412
413pub(super) fn mate(a: &ResolvedElement, b: &ResolvedElement, kind: MateKind) -> MappedMate {
414 MappedMate {
415 body_a: a.component.clone(),
416 body_b: b.component.clone(),
417 body_c: None,
418 kind,
419 }
420}
421
422pub(super) fn direction_of(geometry: &SelectionGeometry) -> Option<Vec3> {
425 match *geometry {
426 SelectionGeometry::Plane { normal, .. } => Some(normal),
427 SelectionGeometry::Axis { direction, .. } | SelectionGeometry::Line { direction, .. } => {
428 Some(direction)
429 }
430 SelectionGeometry::Circle { axis, .. } => Some(axis),
431 SelectionGeometry::Sphere { .. } | SelectionGeometry::Point { .. } => None,
432 }
433}
434
435pub(super) fn local_point(element: &ResolvedElement) -> [f64; 3] {
436 let p = element.local.representative_point();
437 [p.x, p.y, p.z]
438}
439
440pub(super) fn require_direction(element: &ResolvedElement) -> Result<(Vec3, Vec3), ConstraintFailure> {
441 let world = direction_of(&element.world).ok_or_else(|| {
442 ConstraintFailure::unsupported(format!(
443 "selection '{}' carries no direction (needs a planar face, straight edge, axis face, or circular edge)",
444 element.name
445 ))
446 })?;
447 let local = direction_of(&element.local).expect("local mirrors world kind");
448 Ok((world, local))
449}
450
451pub(super) fn require_axis(element: &ResolvedElement) -> Result<crate::MateAxis, ConstraintFailure> {
452 element.local.mate_axis().ok_or_else(|| {
453 ConstraintFailure::unsupported(format!(
454 "selection '{}' carries no axis (needs a cylindrical/conical face, circular edge, or straight edge)",
455 element.name
456 ))
457 })
458}
459
460pub(super) fn require_plane(element: &ResolvedElement) -> Result<crate::MatePlane, ConstraintFailure> {
461 element.local.mate_plane().ok_or_else(|| {
462 ConstraintFailure::unsupported(format!(
463 "selection '{}' is not a planar face",
464 element.name
465 ))
466 })
467}
468
469pub(super) fn pair_signature(elements: &[String]) -> String {
472 let mut pair: Vec<&str> = elements.iter().map(String::as_str).collect();
473 pair.sort_unstable();
474 pair.join("\n")
475}
476
477pub(super) fn effective_align(
488 entry: &mut ConstraintEntry,
489 dir_a: Vec3,
490 dir_b: Vec3,
491 legacy: &str,
492) -> MateAlign {
493 let dot = dir_a.dot(dir_b);
494 entry.set_persistent("lastOrientationDot", serde_json::json!(dot));
495 match entry.input_params.get(FACING).and_then(|value| value.as_str()) {
496 Some(OPPOSED) => return MateAlign::AntiAligned,
497 Some(_) => return MateAlign::Aligned,
498 None => {}
499 }
500 let signature = pair_signature(&entry.elements());
501 let cached = entry
502 .persistent("preferredOpposeSignature")
503 .and_then(|value| value.as_str())
504 .map(|stored| stored == signature)
505 .unwrap_or(false)
506 .then(|| entry.persistent("preferredOppose").and_then(|v| v.as_bool()))
507 .flatten();
508 let opposed = cached.unwrap_or(dot < 0.0) != entry.flag(legacy);
509 if let Some(params) = entry.input_params.as_object_mut() {
510 params.remove(legacy);
511 params.insert(FACING.into(), serde_json::json!(if opposed { OPPOSED } else { ALIGNED }));
512 }
513 entry.remove_persistent("preferredOppose");
514 entry.remove_persistent("preferredOpposeSignature");
515 if opposed {
516 MateAlign::AntiAligned
517 } else {
518 MateAlign::Aligned
519 }
520}
521
522pub(super) const FACING: &str = "facing";
524pub(super) const ALIGNED: &str = "aligned";
525pub(super) const OPPOSED: &str = "opposed";
526
527pub(super) fn facing_field(hint: &str) -> serde_json::Value {
530 serde_json::json!({
531 "type": "options",
532 "options": [ALIGNED, OPPOSED],
533 "default_value": null,
534 "label": "Facing",
535 "hint": hint,
536 })
537}
538
539
540
541
542
543#[allow(clippy::type_complexity)]
550pub(super) fn first_solve_target(
551 entry: &ConstraintEntry,
552 param_key: &str,
553 flag_key: &str,
554 configured: f64,
555 current: f64,
556) -> (
557 f64,
558 (Vec<(String, serde_json::Value)>, Vec<(String, serde_json::Value)>),
559) {
560 let initialized = entry
561 .persistent(flag_key)
562 .and_then(|value| value.as_bool())
563 .unwrap_or(false);
564 let given = entry.input_params.get(param_key).is_some_and(|value| !value.is_null());
565 if initialized {
566 (configured, (Vec::new(), Vec::new()))
567 } else if given {
568 (configured, (Vec::new(), vec![(flag_key.to_string(), serde_json::Value::Bool(true))]))
569 } else {
570 (
571 current,
572 (
573 vec![(param_key.to_string(), serde_json::json!(current))],
574 vec![(flag_key.to_string(), serde_json::Value::Bool(true))],
575 ),
576 )
577 }
578}
579
580
581
582
583
584pub(super) fn angle_between_deg(a: Vec3, b: Vec3) -> f64 {
589 let denominator = a.length() * b.length();
590 if denominator <= 0.0 {
591 return 0.0;
592 }
593 (a.dot(b) / denominator).clamp(-1.0, 1.0).acos().to_degrees()
594}
595
596pub(super) fn point_line_distance(point: Vec3, origin: Vec3, direction: Vec3) -> f64 {
597 let offset = point.sub(origin);
598 let along = offset.dot(direction) / direction.dot(direction).max(1e-300);
599 offset.sub(direction.scale(along)).length()
600}
601
602pub(super) fn line_line_distance(oa: Vec3, da: Vec3, ob: Vec3, db: Vec3) -> f64 {
605 let cross = da.cross(db);
606 let denominator = cross.length();
607 if denominator < 1e-9 * da.length().max(db.length()).max(1.0) {
608 return point_line_distance(ob, oa, da);
609 }
610 (ob.sub(oa).dot(cross) / denominator).abs()
611}
612
613pub(super) fn elements_scale(elements: &[ResolvedElement]) -> f64 {
616 let mut scale = 1.0f64;
617 for point in elements.iter().map(|element| element.world.representative_point()) {
618 scale = scale
619 .max(point.x.abs())
620 .max(point.y.abs())
621 .max(point.z.abs());
622 }
623 scale
624}
625
626pub(super) fn matrix_to_quaternion(transform: &AffineTransform) -> [f64; 4] {
633 let m = &transform.elements;
634 let (r00, r01, r02) = (m[0], m[1], m[2]);
635 let (r10, r11, r12) = (m[4], m[5], m[6]);
636 let (r20, r21, r22) = (m[8], m[9], m[10]);
637 let trace = r00 + r11 + r22;
638 let q = if trace > 0.0 {
639 let s = (trace + 1.0).sqrt() * 2.0;
640 [s / 4.0, (r21 - r12) / s, (r02 - r20) / s, (r10 - r01) / s]
641 } else if r00 > r11 && r00 > r22 {
642 let s = (1.0 + r00 - r11 - r22).sqrt() * 2.0;
643 [(r21 - r12) / s, s / 4.0, (r01 + r10) / s, (r02 + r20) / s]
644 } else if r11 > r22 {
645 let s = (1.0 + r11 - r00 - r22).sqrt() * 2.0;
646 [(r02 - r20) / s, (r01 + r10) / s, s / 4.0, (r12 + r21) / s]
647 } else {
648 let s = (1.0 + r22 - r00 - r11).sqrt() * 2.0;
649 [(r10 - r01) / s, (r02 + r20) / s, (r12 + r21) / s, s / 4.0]
650 };
651 normalize_quaternion(q)
652}
653
654pub(super) fn normalize_quaternion(q: [f64; 4]) -> [f64; 4] {
655 let norm = (q[0] * q[0] + q[1] * q[1] + q[2] * q[2] + q[3] * q[3]).sqrt();
656 if norm <= 0.0 || !norm.is_finite() {
657 return [1.0, 0.0, 0.0, 0.0];
658 }
659 [q[0] / norm, q[1] / norm, q[2] / norm, q[3] / norm]
660}
661
662pub(super) fn pose_to_transform(
666 rotation: [f64; 4],
667 translation: [f64; 3],
668) -> Result<AffineTransform, String> {
669 let [w, x, y, z] = normalize_quaternion(rotation);
670 AffineTransform::new([
671 1.0 - 2.0 * (y * y + z * z), 2.0 * (x * y - w * z), 2.0 * (x * z + w * y), translation[0],
672 2.0 * (x * y + w * z), 1.0 - 2.0 * (x * x + z * z), 2.0 * (y * z - w * x), translation[1],
673 2.0 * (x * z - w * y), 2.0 * (y * z + w * x), 1.0 - 2.0 * (x * x + y * y), translation[2],
674 0.0, 0.0, 0.0, 1.0,
675 ])
676}
677
678pub fn pose_params_to_transform(pose: &serde_json::Value) -> Result<AffineTransform, String> {
682 let triple = |key: &str| -> Result<[f64; 3], String> {
683 let values = pose.get(key).and_then(|value| value.as_array());
684 let Some(values) = values else { return Ok([0.0; 3]) };
685 let mut out = [0.0; 3];
686 for (slot, value) in out.iter_mut().zip(values) {
687 *slot = value.as_f64().ok_or_else(|| format!("pose {key}: not a number"))?;
688 }
689 Ok(out)
690 };
691 let translate = triple("translate")?;
692 let degrees = triple("rotateEulerDeg")?;
693 AffineTransform::new(crate::feature_pipeline::features::common::compose_trs_matrix(
694 translate,
695 [degrees[0].to_radians(), degrees[1].to_radians(), degrees[2].to_radians()],
696 [1.0, 1.0, 1.0],
697 [0.0, 0.0, 0.0],
698 ))
699}
700
701pub fn transform_to_pose_params(transform: &AffineTransform) -> serde_json::Value {
715 let m = &transform.elements;
716 let sb = m[2].clamp(-1.0, 1.0);
719 let (a, b, c) = if sb.abs() < 1.0 - 1e-9 {
720 (
721 (-m[6]).atan2(m[10]),
722 sb.asin(),
723 (-m[1]).atan2(m[0]),
724 )
725 } else {
726 (m[9].atan2(m[5]), sb.asin(), 0.0)
727 };
728 serde_json::json!({
729 "translate": [m[3], m[7], m[11]],
730 "rotateEulerDeg": [a.to_degrees(), b.to_degrees(), c.to_degrees()],
731 })
732}