1use super::doc::{id_key, SketchDoc, SketchGeometry, SketchPoint};
20use serde_json::{Map, Value};
21
22#[derive(Clone, Copy, Debug, PartialEq)]
24pub enum ChamferSize {
25 Equal { distance: f64 },
27 DistanceAngle { distance: f64, angle_degrees: f64 },
30}
31
32#[derive(Clone, Copy, Debug, PartialEq)]
34pub struct CornerOptions {
35 pub radius: f64,
37 pub chamfer_by_angle: bool,
40 pub chamfer_distance: f64,
42 pub chamfer_angle_degrees: f64,
44}
45
46impl Default for CornerOptions {
47 fn default() -> Self {
48 Self { radius: 1.0, chamfer_by_angle: false, chamfer_distance: 1.0, chamfer_angle_degrees: 45.0 }
49 }
50}
51
52impl CornerOptions {
53 pub fn chamfer_size(&self) -> ChamferSize {
55 if self.chamfer_by_angle {
56 ChamferSize::DistanceAngle { distance: self.chamfer_distance, angle_degrees: self.chamfer_angle_degrees }
57 } else {
58 ChamferSize::Equal { distance: self.chamfer_distance }
59 }
60 }
61}
62
63#[derive(Clone, Debug, PartialEq)]
65pub struct CornerEdit {
66 pub edge: Value,
68 pub constraints: Vec<Value>,
70}
71
72struct Corner {
74 corner: (f64, f64),
75 lines: [(Value, Value, (f64, f64)); 2],
76}
77
78fn point_xy(doc: &SketchDoc, id: &Value) -> Option<(f64, f64)> {
79 doc.point(id).map(|p| (p.x, p.y))
80}
81
82fn corner_lines(doc: &SketchDoc, corner: &Value) -> Result<Corner, String> {
85 let key = id_key(corner);
86 let at = point_xy(doc, corner).ok_or_else(|| "the corner point is not in the sketch".to_string())?;
87 let touching: Vec<&SketchGeometry> = doc.geometries.iter().filter(|g| g.points.iter().any(|p| id_key(p) == key)).collect();
88 if touching.len() != 2 {
89 return Err(format!("no shared corner: {} curves meet at this point (a corner is two)", touching.len()));
90 }
91 let mut lines = Vec::new();
92 for geometry in touching {
93 if geometry.geom_type != "line" {
94 return Err(format!("only corners of two lines are supported yet (this one has a {})", geometry.geom_type));
95 }
96 if geometry.points.len() != 2 {
97 return Err("a line of the corner is malformed".to_string());
98 }
99 let far = if id_key(&geometry.points[0]) == key { &geometry.points[1] } else { &geometry.points[0] };
100 if id_key(far) == key {
101 return Err("a line of the corner has no length".to_string());
102 }
103 let far_xy = point_xy(doc, far).ok_or_else(|| "a corner line's endpoint is missing".to_string())?;
104 if (far_xy.0 - at.0).hypot(far_xy.1 - at.1) <= 1e-9 {
105 return Err("a line of the corner has no length".to_string());
106 }
107 lines.push((geometry.id.clone(), far.clone(), far_xy));
108 }
109 let [first, second]: [(Value, Value, (f64, f64)); 2] = lines.try_into().map_err(|_| "no shared corner".to_string())?;
110 Ok(Corner { corner: at, lines: [first, second] })
111}
112
113pub fn corner_near(doc: &SketchDoc, u: f64, v: f64, radius: f64) -> Option<Value> {
116 doc.points
117 .iter()
118 .filter(|p| (p.x - u).hypot(p.y - v) <= radius)
119 .filter(|p| corner_lines(doc, &p.id).is_ok())
120 .min_by(|a, b| (a.x - u).hypot(a.y - v).total_cmp(&(b.x - u).hypot(b.y - v)))
121 .map(|p| p.id.clone())
122}
123
124fn add_point(doc: &mut SketchDoc, (x, y): (f64, f64)) -> Value {
125 let id = doc.next_point_id();
126 doc.points.push(SketchPoint { id: id.clone(), x, y, fixed: false, construction: false, external_reference: false });
127 id
128}
129
130fn add_geometry(doc: &mut SketchDoc, geom_type: &str, points: Vec<Value>) -> Value {
131 let id = doc.next_geometry_id();
132 let mut extra = Map::new();
133 extra.insert("construction".to_string(), Value::Bool(false));
134 doc.geometries.push(SketchGeometry { id: id.clone(), geom_type: geom_type.to_string(), points, extra });
135 id
136}
137
138fn add_constraint(doc: &mut SketchDoc, ctype: &str, points: Vec<Value>, display_style: &str) -> Value {
141 let id = doc.next_constraint_id();
142 let mut raw = Map::new();
143 raw.insert("id".to_string(), id.clone());
144 raw.insert("type".to_string(), Value::String(ctype.to_string()));
145 raw.insert("points".to_string(), Value::Array(points));
146 raw.insert("labelX".to_string(), Value::from(0));
147 raw.insert("labelY".to_string(), Value::from(0));
148 raw.insert("displayStyle".to_string(), Value::String(display_style.to_string()));
149 raw.insert("value".to_string(), Value::Null);
150 raw.insert("valueNeedsSetup".to_string(), Value::Bool(true));
151 doc.constraints.push(super::doc::SketchConstraint { raw });
152 id
153}
154
155fn retarget_line(doc: &mut SketchDoc, line: &Value, corner: &Value, with: &Value) {
157 let key = id_key(corner);
158 if let Some(geometry) = doc.geometry_mut(line) {
159 for point in geometry.points.iter_mut() {
160 if id_key(point) == key {
161 *point = with.clone();
162 }
163 }
164 }
165}
166
167fn keep_virtual_sharp(doc: &mut SketchDoc, corner: &Value, on: [(&Value, &Value); 2], constraints: &mut Vec<Value>) {
170 if let Some(point) = doc.point_mut(corner) {
171 point.construction = true;
172 }
173 for (far, cut) in on {
174 constraints.push(add_constraint(doc, "⏛", vec![far.clone(), cut.clone(), corner.clone()], ""));
175 }
176}
177
178fn unit((x, y): (f64, f64)) -> (f64, f64) {
179 let length = x.hypot(y);
180 (x / length, y / length)
181}
182
183fn directions(corner: &Corner) -> Result<([(f64, f64); 2], f64, [f64; 2]), String> {
186 let (px, py) = corner.corner;
187 let vectors = corner.lines.each_ref().map(|(_, _, (x, y))| (x - px, y - py));
188 let lengths = vectors.map(|(x, y)| x.hypot(y));
189 let units = vectors.map(unit);
190 let cross = units[0].0 * units[1].1 - units[0].1 * units[1].0;
191 let dot = units[0].0 * units[1].0 + units[0].1 * units[1].1;
192 let angle = cross.abs().atan2(dot);
193 if angle <= 1e-6 || angle >= std::f64::consts::PI - 1e-6 {
194 return Err("the two lines are parallel: there is no corner to round or cut".to_string());
195 }
196 Ok((units, angle, lengths))
197}
198
199pub fn fillet_corner(doc: &mut SketchDoc, corner: &Value, radius: f64) -> Result<CornerEdit, String> {
201 if !(radius.is_finite() && radius > 1e-9) {
202 return Err("the fillet radius must be positive".to_string());
203 }
204 let shape = corner_lines(doc, corner)?;
205 let (units, angle, lengths) = directions(&shape)?;
206 let back = radius / (angle / 2.0).tan();
207 let shorter = lengths[0].min(lengths[1]);
208 if back >= shorter {
209 return Err(format!(
210 "the radius is too large for this corner: it needs {back:.6} along each line, the shorter is {shorter:.6} (largest radius {:.6})",
211 shorter * (angle / 2.0).tan()
212 ));
213 }
214 let (px, py) = shape.corner;
215 let tangent = units.map(|(x, y)| (px + x * back, py + y * back));
216 let bisector = unit((units[0].0 + units[1].0, units[0].1 + units[1].1));
217 let reach = radius / (angle / 2.0).sin();
218 let centre = (px + bisector.0 * reach, py + bisector.1 * reach);
219 let [(first, first_far, _), (second, second_far, _)] = shape.lines;
220 let first_cut = add_point(doc, tangent[0]);
221 let second_cut = add_point(doc, tangent[1]);
222 let centre_id = add_point(doc, centre);
223 retarget_line(doc, &first, corner, &first_cut);
224 retarget_line(doc, &second, corner, &second_cut);
225 let turn = (tangent[0].0 - centre.0) * (tangent[1].1 - centre.1) - (tangent[0].1 - centre.1) * (tangent[1].0 - centre.0);
227 let (start, end) = if turn > 0.0 { (first_cut.clone(), second_cut.clone()) } else { (second_cut.clone(), first_cut.clone()) };
228 let edge = add_geometry(doc, "arc", vec![centre_id.clone(), start.clone(), end]);
229 let mut constraints = Vec::new();
230 constraints.push(add_constraint(doc, "⟂", vec![centre_id.clone(), first_cut.clone(), first_cut.clone(), first_far.clone()], ""));
239 constraints.push(add_constraint(doc, "⟂", vec![centre_id.clone(), second_cut.clone(), second_cut.clone(), second_far.clone()], ""));
240 constraints.push(add_constraint(doc, "⟺", vec![centre_id, start], "radius"));
241 keep_virtual_sharp(doc, corner, [(&first_far, &first_cut), (&second_far, &second_cut)], &mut constraints);
242 Ok(CornerEdit { edge, constraints })
243}
244
245pub fn fillet_corners(doc: &mut SketchDoc, corners: &[Value], radius: f64) -> (Vec<(Value, CornerEdit)>, Vec<(Value, String)>) {
253 let mut done: Vec<(Value, CornerEdit)> = Vec::new();
254 let mut refused = Vec::new();
255 let mut first: Option<(Value, Value)> = None;
256 for corner in corners {
257 match fillet_corner(doc, corner, radius) {
258 Ok(mut edit) => {
259 let arc = doc.geometries.iter().find(|g| id_key(&g.id) == id_key(&edit.edge)).map(|g| g.points.clone());
260 if let Some([centre, start, _end]) = arc.as_deref() {
261 match &first {
262 None => first = Some((centre.clone(), start.clone())),
263 Some((first_centre, first_start)) => {
264 if let Some(radius_id) = edit.constraints.iter().find(|id| {
266 doc.constraints.iter().any(|c| {
267 c.raw.get("id").map(id_key) == Some(id_key(id))
268 && c.ctype() == Some("⟺")
269 && c.raw.get("displayStyle").and_then(Value::as_str) == Some("radius")
270 })
271 }) {
272 let radius_id = radius_id.clone();
273 doc.constraints.retain(|c| c.raw.get("id").map(id_key) != Some(id_key(&radius_id)));
274 edit.constraints.retain(|id| id_key(id) != id_key(&radius_id));
275 }
276 let equal = add_constraint(
277 doc,
278 "⊜",
279 vec![first_centre.clone(), first_start.clone(), centre.clone(), start.clone()],
280 "",
281 );
282 edit.constraints.push(equal);
283 }
284 }
285 }
286 done.push((corner.clone(), edit));
287 }
288 Err(message) => refused.push((corner.clone(), message)),
289 }
290 }
291 (done, refused)
292}
293
294pub fn chamfer_corner(doc: &mut SketchDoc, corner: &Value, size: ChamferSize) -> Result<CornerEdit, String> {
296 let shape = corner_lines(doc, corner)?;
297 let (units, angle, lengths) = directions(&shape)?;
298 let (first_back, second_back) = match size {
299 ChamferSize::Equal { distance } => {
300 if !(distance.is_finite() && distance > 1e-9) {
301 return Err("the chamfer distance must be positive".to_string());
302 }
303 (distance, distance)
304 }
305 ChamferSize::DistanceAngle { distance, angle_degrees } => {
306 if !(distance.is_finite() && distance > 1e-9) {
307 return Err("the chamfer distance must be positive".to_string());
308 }
309 let cut = angle_degrees.to_radians();
310 let far = std::f64::consts::PI - angle - cut;
313 if !(cut > 1e-6 && far > 1e-6) {
314 return Err(format!(
315 "the chamfer angle must lie between 0 and {:.4} degrees at this corner",
316 (std::f64::consts::PI - angle).to_degrees()
317 ));
318 }
319 (distance, distance * cut.sin() / far.sin())
320 }
321 };
322 for (back, length) in [(first_back, lengths[0]), (second_back, lengths[1])] {
323 if back >= length {
324 return Err(format!("the chamfer is too large for this corner: it needs {back:.6} along a line {length:.6} long"));
325 }
326 }
327 let (px, py) = shape.corner;
328 let cuts = [(px + units[0].0 * first_back, py + units[0].1 * first_back), (px + units[1].0 * second_back, py + units[1].1 * second_back)];
329 let [(first, first_far, _), (second, second_far, _)] = shape.lines;
330 let first_cut = add_point(doc, cuts[0]);
331 let second_cut = add_point(doc, cuts[1]);
332 retarget_line(doc, &first, corner, &first_cut);
333 retarget_line(doc, &second, corner, &second_cut);
334 let edge = add_geometry(doc, "line", vec![first_cut.clone(), second_cut.clone()]);
335 let mut constraints = Vec::new();
336 constraints.push(add_constraint(doc, "⟺", vec![corner.clone(), first_cut.clone()], ""));
337 match size {
338 ChamferSize::Equal { .. } => {
339 constraints.push(add_constraint(doc, "⇌", vec![corner.clone(), first_cut.clone(), corner.clone(), second_cut.clone()], ""));
340 }
341 ChamferSize::DistanceAngle { .. } => {
342 constraints.push(add_constraint(doc, "∠", vec![first_cut.clone(), corner.clone(), first_cut.clone(), second_cut.clone()], ""));
345 }
346 }
347 keep_virtual_sharp(doc, corner, [(&first_far, &first_cut), (&second_far, &second_cut)], &mut constraints);
348 Ok(CornerEdit { edge, constraints })
349}
350