Skip to main content

brep_render/sketch/
mod.rs

1//! Sketch documents, constraint solving, interaction state, and overlay geometry.
2
3use crate::json_support::vec3_or as read_vec3;
4use crate::geometry3d::{cross3 as cross, dot3 as dot, sub3 as sub};
5
6pub mod constraint_glyphs;
7pub mod corner;
8pub mod dimensions;
9pub mod doc;
10pub mod external_ref;
11pub mod freedom;
12pub mod handdraw;
13pub mod infer;
14pub mod session;
15pub mod solve;
16pub mod spline;
17pub mod tessellate;
18pub mod trim;
19
20pub use doc::{SketchConstraint, SketchDiagnostics, SketchDoc, SketchGeometry, SketchPoint};
21pub use external_ref::{classify_uv, EdgeLink, ExternalRef};
22pub use session::{
23    constraint_ref, entity_ref_eq, geometry_ref, point_ref, refs_equal, RefSelection, SketchSession,
24};
25pub use solve::SketchSolverSettings;
26pub use tessellate::SketchTessellation;
27
28/// An orthonormal placement frame for a sketch plane — origin + in-plane `x`/`y`
29/// axes + the `z` normal, all in world space (`f64`). A plane `(u, v)` coordinate
30/// maps to world `origin + u·x + v·y` (via [`to_world`](Self::to_world)).
31///
32/// Uses double precision to match the sketch solver's coordinates.
33#[derive(Clone, Copy, Debug, PartialEq)]
34pub struct PlaneFrame {
35    pub origin: [f64; 3],
36    pub x_axis: [f64; 3],
37    pub y_axis: [f64; 3],
38    pub z_axis: [f64; 3],
39}
40
41impl PlaneFrame {
42    /// The world XY plane (identity frame): `u → +x`, `v → +y`, normal `+z`.
43    pub fn xy() -> Self {
44        Self {
45            origin: [0.0, 0.0, 0.0],
46            x_axis: [1.0, 0.0, 0.0],
47            y_axis: [0.0, 1.0, 0.0],
48            z_axis: [0.0, 0.0, 1.0],
49        }
50    }
51
52    /// The world XZ base plane (`datum.rs` normal `(0, -1, 0)`), resolved through
53    /// the same worldUp convention the kernel uses (see [`from_normal`](Self::from_normal)).
54    pub fn xz() -> Self {
55        Self::from_normal([0.0, 0.0, 0.0], [0.0, -1.0, 0.0])
56    }
57
58    /// The world YZ base plane (`datum.rs` normal `(1, 0, 0)`), resolved through
59    /// the same worldUp convention the kernel uses (see [`from_normal`](Self::from_normal)).
60    pub fn yz() -> Self {
61        Self::from_normal([0.0, 0.0, 0.0], [1.0, 0.0, 0.0])
62    }
63
64    /// Derive an orthonormal frame from an `origin` + plane `normal`, a faithful
65    /// port of `feature_pipeline::Frame::from_origin_normal` — the kernel's SINGLE
66    /// source of truth for how a plane reference becomes in-plane axes:
67    ///
68    /// ```text
69    /// refUp = |n·(0,1,0)| > 0.9 ? (1,0,0) : (0,1,0)
70    /// x = norm(refUp × n);  y = norm(n × x);  z = n
71    /// ```
72    ///
73    /// A degenerate (zero / non-finite) normal — or a normal collinear with the
74    /// picked `refUp` — returns the XY identity axes (at `origin`) rather than
75    /// erroring, so callers always get a usable frame.
76    pub fn from_normal(origin: [f64; 3], normal: [f64; 3]) -> Self {
77        let identity = Self {
78            origin,
79            ..Self::xy()
80        };
81        let Some(z) = normalize(normal) else {
82            return identity;
83        };
84        let world_up = [0.0, 1.0, 0.0];
85        let ref_up = if dot(z, world_up).abs() > 0.9 {
86            [1.0, 0.0, 0.0]
87        } else {
88            world_up
89        };
90        let Some(x) = normalize(cross(ref_up, z)) else {
91            return identity;
92        };
93        let Some(y) = normalize(cross(z, x)) else {
94            return identity;
95        };
96        Self {
97            origin,
98            x_axis: x,
99            y_axis: y,
100            z_axis: z,
101        }
102    }
103
104    /// Read a persisted `persistentData.basis` object (`{origin, x, y, z}`, each a
105    /// `[x, y, z]` array) into a frame, mirroring the kernel's `persisted_basis_frame`
106    /// (`features/sketch.rs`). Missing keys default to the identity components, so a
107    /// partial / absent basis still yields a usable XY-ish frame.
108    pub fn from_basis_json(basis: &serde_json::Value) -> Self {
109        Self {
110            origin: read_vec3(basis.get("origin"), [0.0, 0.0, 0.0]),
111            x_axis: read_vec3(basis.get("x"), [1.0, 0.0, 0.0]),
112            y_axis: read_vec3(basis.get("y"), [0.0, 1.0, 0.0]),
113            z_axis: read_vec3(basis.get("z"), [0.0, 0.0, 1.0]),
114        }
115    }
116
117    /// Map a plane `(u, v)` coordinate to world `[x, y, z]`.
118    pub fn to_world(&self, u: f64, v: f64) -> [f64; 3] {
119        [
120            self.origin[0] + self.x_axis[0] * u + self.y_axis[0] * v,
121            self.origin[1] + self.x_axis[1] * u + self.y_axis[1] * v,
122            self.origin[2] + self.x_axis[2] * u + self.y_axis[2] * v,
123        ]
124    }
125
126    /// Project a world point onto the plane's `(u, v)` frame — the inverse of
127    /// [`to_world`](Self::to_world). With orthonormal axes this is plain dot
128    /// products against the offset from the origin (`d = world − origin`;
129    /// `u = d·x_axis`, `v = d·y_axis`); a point off the plane projects orthogonally
130    /// (its normal component is dropped). Mirrors the previous sketcher's
131    /// world→UV projection.
132    pub fn to_uv(&self, world: [f64; 3]) -> (f64, f64) {
133        let d = [
134            world[0] - self.origin[0],
135            world[1] - self.origin[1],
136            world[2] - self.origin[2],
137        ];
138        (dot(d, self.x_axis), dot(d, self.y_axis))
139    }
140}
141
142impl Default for PlaneFrame {
143    fn default() -> Self {
144        Self::xy()
145    }
146}
147
148/// Intersect a world-space ray (`origin` + `dir`) with a sketch `plane` and return
149/// the hit's in-plane `(u, v)` coordinate, or `None` when the ray is parallel to
150/// the plane (`|dir·n| < 1e-9`) or the hit is behind the ray origin (`t <= 0`).
151///
152/// This is the pure pixel→plane math behind
153/// [`EngineState::sketch_uv_at`](crate::engine_state::EngineState::sketch_uv_at):
154/// the caller supplies the camera ray (`camera.pick_ray(x, y)`); the plane's axes
155/// are assumed orthonormal, so the world→uv projection is plain dot products.
156pub fn ray_plane_uv(plane: &PlaneFrame, origin: [f64; 3], dir: [f64; 3]) -> Option<(f64, f64)> {
157    let n = plane.z_axis;
158    let denom = dot(dir, n);
159    if denom.abs() < 1e-9 {
160        return None; // ray parallel to the plane
161    }
162    let t = dot(sub(plane.origin, origin), n) / denom;
163    if t <= 0.0 {
164        return None; // plane is behind the ray origin
165    }
166    let hit = [
167        origin[0] + t * dir[0],
168        origin[1] + t * dir[1],
169        origin[2] + t * dir[2],
170    ];
171    let w = sub(hit, plane.origin);
172    Some((dot(w, plane.x_axis), dot(w, plane.y_axis)))
173}
174
175/// The BASE overlay color for one constraint's annotation — the shared constraint
176/// green, or the conflict red while the solver names this constraint in a conflict.
177/// The ONE place that decision is made, so a glyph and a dimension leader in the
178/// same conflict are never colored differently. Selection / hover emphasis is
179/// layered ON TOP of this by
180/// [`tessellate::interaction_color`](crate::sketch::tessellate), so a picked
181/// conflicting constraint still reads as picked.
182pub(crate) fn constraint_base_color(
183    colors: &crate::style::SketchColors,
184    diag: &SketchDiagnostics,
185    id: &serde_json::Value,
186) -> u32 {
187    if diag.constraint_conflicting(id) {
188        colors.conflict
189    } else if diag.constraint_redundant(id) {
190        REDUNDANT_CONSTRAINT_COLOR
191    } else {
192        colors.constraint
193    }
194}
195
196/// A redundant constraint's glyph / dimension colour: the over-constrained yellow
197/// of the sketch status readout, so the readout and the marks it counts agree.
198pub const REDUNDANT_CONSTRAINT_COLOR: u32 = 0xffcf5c;
199
200/// Normalize `v`, or `None` when it is (near) zero / non-finite.
201fn normalize(v: [f64; 3]) -> Option<[f64; 3]> {
202    let len = (v[0] * v[0] + v[1] * v[1] + v[2] * v[2]).sqrt();
203    if len.is_finite() && len > 1e-12 {
204        Some([v[0] / len, v[1] / len, v[2] / len])
205    } else {
206        None
207    }
208}
209
210
211pub mod text;
212
213