1pub use crate::{make_arc, make_revolution, NurbsCurve, NurbsSurface, SurfaceProjection, Vec3};
15
16const RECOGNITION_TOLERANCE: f64 = 1e-9;
17
18#[derive(Clone, Debug)]
19pub struct RevolutionFrame {
20 pub origin: Vec3,
22 pub axis: Vec3,
24 pub x_axis: Vec3,
26 pub y_axis: Vec3,
28}
29
30impl RevolutionFrame {
31 fn cylindrical(&self, point: Vec3) -> (Option<f64>, f64, f64) {
35 let d = point.sub(self.origin);
36 let axial = d.dot(self.axis);
37 let radial_vector = d.sub(self.axis.scale(axial));
38 let radius = radial_vector.length();
39 if radius <= 1e-14 * (1.0 + axial.abs()) {
40 return (None, radius, axial);
41 }
42 let mut theta = radial_vector
43 .dot(self.y_axis)
44 .atan2(radial_vector.dot(self.x_axis));
45 if theta < 0.0 {
46 theta += std::f64::consts::TAU;
47 }
48 (Some(theta), radius, axial)
49 }
50}
51
52#[derive(Clone, Debug)]
53pub enum AnalyticSurface {
54 Plane {
56 origin: Vec3,
57 u_dir: Vec3,
58 v_dir: Vec3,
59 u_domain: [f64; 2],
60 v_domain: [f64; 2],
61 },
62 RuledRevolution {
65 frame: RevolutionFrame,
66 rho0: f64,
67 rho1: f64,
68 height: f64,
69 },
70 Sphere { frame: RevolutionFrame, radius: f64 },
72 Torus {
74 frame: RevolutionFrame,
75 major_radius: f64,
76 minor_radius: f64,
77 },
78 Revolution {
88 frame: RevolutionFrame,
89 spans: usize,
90 sweep: f64,
91 generatrix: NurbsCurve,
92 },
93}
94
95impl AnalyticSurface {
96 pub fn kind_label(&self) -> &'static str {
106 match self {
107 AnalyticSurface::Plane { .. } => "Plane",
108 AnalyticSurface::RuledRevolution { rho0, rho1, .. } => {
109 let scale = rho0.abs().max(rho1.abs()).max(1.0);
110 if (rho0 - rho1).abs() <= RECOGNITION_TOLERANCE * scale {
111 "Cylinder"
112 } else {
113 "Cone"
114 }
115 }
116 AnalyticSurface::Sphere { .. } => "Sphere",
117 AnalyticSurface::Torus { .. } => "Torus",
118 AnalyticSurface::Revolution { .. } => "Surface of revolution",
119 }
120 }
121}
122
123pub fn circle_angle_to_parameter(spans: usize, sweep: f64, angle: f64) -> f64 {
128 let segment = sweep / spans as f64;
129 let clamped = angle.clamp(0.0, sweep);
130 let mut span = (clamped / segment).floor() as usize;
131 if span >= spans {
132 span = spans - 1;
133 }
134 let local = clamped - span as f64 * segment;
135 let half = (0.5 * local).tan();
139 let s = (0.5 * segment).sin();
140 let c = (0.5 * segment).cos();
141 let t = half / (s + half * (1.0 - c));
142 (span as f64 + t.clamp(0.0, 1.0)) / spans as f64
143}
144
145#[path = "analytic_surface/recognition.rs"]
146mod recognition;
147#[path = "analytic_surface/intersect.rs"]
148mod intersect;
149#[path = "analytic_surface/revolution.rs"]
150mod revolution;
151
152pub use intersect::{intersect_analytic_pair, plane_ruled_section_arc};
153pub use intersect::{intersect_analytic_pair_with, ruled_gate, ruled_gate_census, RuledGate};
154pub use recognition::recognize;
155#[path = "analytic_surface/extrusion.rs"]
156mod extrusion;
157pub use extrusion::{extrusion_structure, plane_extrusion_section, parallel_extrusion_sections, ExtrusionStructure};
158pub(crate) use extrusion::ReducedProfile;
159pub use revolution::{revolution_structure, RevolutionStructure};
160pub use revolution::circumcenter;
161pub use recognition::generatrix_is_meridional_half_ray;
162
163impl AnalyticSurface {
164 pub fn project(&self, surface: &NurbsSurface, point: Vec3) -> Option<SurfaceProjection> {
168 let (u, v) = match self {
169 AnalyticSurface::Plane {
170 origin,
171 u_dir,
172 v_dir,
173 u_domain,
174 v_domain,
175 } => {
176 let d = point.sub(*origin);
179 let a = u_dir.dot(*u_dir);
180 let b = u_dir.dot(*v_dir);
181 let c = v_dir.dot(*v_dir);
182 let determinant = a * c - b * b;
183 if determinant.abs() <= 1e-16 * (a * c).max(1.0) {
184 return None;
185 }
186 let fu = u_dir.dot(d);
187 let fv = v_dir.dot(d);
188 let u =
189 ((fu * c - fv * b) / determinant + u_domain[0]).clamp(u_domain[0], u_domain[1]);
190 let v =
191 ((fv * a - fu * b) / determinant + v_domain[0]).clamp(v_domain[0], v_domain[1]);
192 (u, v)
193 }
194 AnalyticSurface::RuledRevolution {
195 frame,
196 rho0,
197 rho1,
198 height,
199 } => {
200 let (theta, rho, z) = frame.cylindrical(point);
201 let u = theta
202 .map(|angle| circle_angle_to_parameter(4, std::f64::consts::TAU, angle))
203 .unwrap_or(0.0);
204 let delta_rho = rho1 - rho0;
207 let length_squared = delta_rho * delta_rho + height * height;
208 let t = (((rho - rho0) * delta_rho + z * height) / length_squared).clamp(0.0, 1.0);
209 (u, t)
210 }
211 AnalyticSurface::Sphere { frame, radius: _ } => {
212 let (theta, rho, z) = frame.cylindrical(point);
213 let u = theta
214 .map(|angle| circle_angle_to_parameter(4, std::f64::consts::TAU, angle))
215 .unwrap_or(0.0);
216 let beta = rho.atan2(-z);
218 let v = circle_angle_to_parameter(2, std::f64::consts::PI, beta);
219 (u, v)
220 }
221 AnalyticSurface::Torus {
222 frame,
223 major_radius,
224 minor_radius: _,
225 } => {
226 let (theta, rho, z) = frame.cylindrical(point);
227 let u = theta
228 .map(|angle| circle_angle_to_parameter(4, std::f64::consts::TAU, angle))
229 .unwrap_or(0.0);
230 let mut psi = z.atan2(rho - major_radius);
231 if psi < 0.0 {
232 psi += std::f64::consts::TAU;
233 }
234 let v = circle_angle_to_parameter(4, std::f64::consts::TAU, psi);
235 (u, v)
236 }
237 AnalyticSurface::Revolution {
238 frame,
239 spans,
240 sweep,
241 generatrix,
242 } => {
243 if !generatrix_is_meridional_half_ray(generatrix, frame) {
244 return None;
245 }
246 let (theta, rho, z) = frame.cylindrical(point);
247 let full = *sweep >= std::f64::consts::TAU - 1e-9;
248 let point_at_angle = |angle: f64| {
252 let radial = frame
253 .x_axis
254 .scale(angle.cos())
255 .add(frame.y_axis.scale(angle.sin()));
256 frame.origin.add(radial.scale(rho)).add(frame.axis.scale(z))
257 };
258 let mut candidates: Vec<(f64, Vec3)> = Vec::with_capacity(2);
259 match theta {
260 None => candidates.push((0.0, point)),
261 Some(angle) if full || angle <= *sweep => {
262 candidates.push((
264 circle_angle_to_parameter(*spans, *sweep, angle),
265 point_at_angle(0.0),
266 ));
267 }
268 Some(angle) => {
269 candidates.push((0.0, point));
275 candidates.push((1.0, point_at_angle(angle - *sweep)));
276 }
277 }
278 let mut best: Option<(f64, f64, f64)> = None;
279 for (u, query) in candidates {
280 let Ok(projection) = crate::project_point_to_curve(generatrix, query) else {
281 return None;
282 };
283 if best
284 .map(|(_, _, distance)| projection.distance < distance)
285 .unwrap_or(true)
286 {
287 best = Some((u, projection.u, projection.distance));
288 }
289 }
290 let (u, v, _) = best?;
291 (u, v)
292 }
293 };
294 let projected = surface.evaluate(u, v).ok()?;
295 Some(SurfaceProjection {
296 u,
297 v,
298 point: projected,
299 distance: projected.sub(point).length(),
300 })
301 }
302
303 pub fn frame(&self) -> Option<&RevolutionFrame> {
306 match self {
307 AnalyticSurface::Plane { .. } => None,
308 AnalyticSurface::RuledRevolution { frame, .. }
309 | AnalyticSurface::Sphere { frame, .. }
310 | AnalyticSurface::Torus { frame, .. }
311 | AnalyticSurface::Revolution { frame, .. } => Some(frame),
312 }
313 }
314}
315
316pub use recognition::curve_scale;
317
318pub fn circumcenter_2d(a: [f64; 2], b: [f64; 2], c: [f64; 2]) -> Option<[f64; 2]> {
320 let scale = (b[0] - a[0]).abs().max((b[1] - a[1]).abs())
321 .max((c[0] - a[0]).abs()).max((c[1] - a[1]).abs());
322 let d = 2.0 * (a[0] * (b[1] - c[1]) + b[0] * (c[1] - a[1]) + c[0] * (a[1] - b[1]));
323 if !d.is_finite() || d.abs() <= 1e-12 * scale * scale { return None; }
324 let aa = a[0] * a[0] + a[1] * a[1];
325 let bb = b[0] * b[0] + b[1] * b[1];
326 let cc = c[0] * c[0] + c[1] * c[1];
327 Some([
328 (aa * (b[1] - c[1]) + bb * (c[1] - a[1]) + cc * (a[1] - b[1])) / d,
329 (aa * (c[0] - b[0]) + bb * (a[0] - c[0]) + cc * (b[0] - a[0])) / d,
330 ])
331}
332
333#[derive(Clone, Copy, Debug)]
334pub struct RecognizedCircle {
335 pub centre: Vec3,
336 pub axis: Vec3,
337 pub radius: f64,
338 pub worst: f64,
340}
341
342pub fn recognize_circle(curve: &NurbsCurve, t0: f64, t1: f64, tolerance: f64) -> Option<RecognizedCircle> {
344 if !(tolerance >= 0.0) || !t0.is_finite() || !t1.is_finite() || t0 == t1 {
345 return None;
346 }
347 let a = curve.evaluate(t0).ok()?;
348 let b = curve.evaluate(t0 + (t1 - t0) / 3.0).ok()?;
349 let c = curve.evaluate(t0 + 2.0 * (t1 - t0) / 3.0).ok()?;
350 let centre = circumcenter(a, b, c)?;
351 let normal = b.sub(a).cross(c.sub(a));
352 let axis = normal.scale(1.0 / normal.length());
353 let radius = a.sub(centre).length();
354 if !(radius > 0.0) || !radius.is_finite() { return None; }
355 let mut worst = 0.0_f64;
356 for i in 0..=64 {
357 let d = curve.evaluate(t0 + (t1 - t0) * i as f64 / 64.0).ok()?.sub(centre);
358 let error = (d.length() - radius).abs().max(d.dot(axis).abs());
359 if !error.is_finite() || error > tolerance { return None; }
360 worst = worst.max(error);
361 }
362 Some(RecognizedCircle { centre, axis, radius, worst })
363}
364