Compare commits

...
8 Commits
5 changed files with 224 additions and 68 deletions
+6 -4
View File
@@ -253,14 +253,16 @@ fn run_grip_rotate(s: &mut Session, p: &Value) -> Result<Value> {
fn run_grip_scale(s: &mut Session, p: &Value) -> Result<Value> {
let hs = targets(s, p)?;
let base = base_point(s, "grip.scale", p, &hs)?;
let m = match p.get("factor").and_then(Value::as_f64).filter(|a| a.is_finite()) {
Some(f) if f > 0.0 => Mat3::scale_about(base, f),
let f = match p.get("factor").and_then(Value::as_f64).filter(|a| a.is_finite()) {
Some(f) if f > 1e-12 => f,
Some(_) => return Err(bad("grip.scale", "factor must be positive")),
None => {
mode_matrix(GripMode::Scale, base, point_req("grip.scale", p, "to")?).ok_or_else(|| bad("grip.scale", "scale factor would be zero"))?
let f = base.dist(point_req("grip.scale", p, "to")?);
if f.is_finite() && f > 1e-12 { f } else { return Err(bad("grip.scale", "scale factor would be zero")) }
}
};
apply(s, &hs, &m, bool_or(p, "copy", false))
let r = super::modify::scale_entities(s, &hs, super::modify::at_elevation(s, base), f, bool_or(p, "copy", false))?;
Ok(json!({ "handles": r.iter().map(|h| h.hex()).collect::<Vec<_>>() }))
}
fn run_grip_mirror(s: &mut Session, p: &Value) -> Result<Value> {
+48 -19
View File
@@ -14,7 +14,7 @@ use cadcraft_geom::{Mat3, Vec2};
use super::gripcmds::stretch_grips;
use super::helpers::line;
use super::machines::number;
use super::modify::transform_entities;
use super::modify::{at_elevation, scale_entities, transform_entities};
use crate::grips::{GripAction, GripMode, grip_action, grip_actions, mode_matrix};
use crate::{Accept, EngineError, Input, Interactive, Prompt, Result, Running, Session, Step};
@@ -220,14 +220,7 @@ impl GripEdit {
}
}
/// Edit with the dragged point `to` (STRETCH) or the transform `m` (the other modes).
fn edit(&mut self, s: &mut Session, to: Vec2, m: Option<Mat3>) -> Result<Step> {
let before = s.state()?.doc.clone();
let changed = match (self.mode, m) {
(GripMode::Stretch, _) => !stretch_grips(s, &self.hot, &self.targets, to - self.base, self.copy)?.is_empty(),
(_, Some(m)) => !transform_entities(s, &self.targets, &m, self.copy)?.is_empty(),
(_, None) => return Err(other("Invalid point.")),
};
fn finish_edit(&mut self, before: Arc<Drawing>, changed: bool) -> Result<Step> {
if !changed {
return Err(other("The objects can't be edited that way (locked, or the result would be degenerate)."));
}
@@ -240,6 +233,27 @@ impl GripEdit {
}
}
/// Edit with the dragged point `to` (STRETCH) or the transform `m` (the other modes).
fn edit(&mut self, s: &mut Session, to: Vec2, m: Option<Mat3>) -> Result<Step> {
let before = s.state()?.doc.clone();
let changed = match (self.mode, m) {
(GripMode::Stretch, _) => !stretch_grips(s, &self.hot, &self.targets, to - self.base, self.copy)?.is_empty(),
(_, Some(m)) => !transform_entities(s, &self.targets, &m, self.copy)?.is_empty(),
(_, None) => return Err(other("Invalid point.")),
};
self.finish_edit(before, changed)
}
/// Scale `targets` uniformly about `base` in 3D, scaling text heights, elevations and thickness.
fn edit_scale(&mut self, s: &mut Session, f: f64) -> Result<Step> {
if !f.is_finite() || f <= 1e-12 {
return Err(other("Invalid point."));
}
let before = s.state()?.doc.clone();
let changed = !scale_entities(s, &self.targets, at_elevation(s, self.base), f, self.copy)?.is_empty();
self.finish_edit(before, changed)
}
fn mode_input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
match i {
Input::Keyword(k) => match k.as_str() {
@@ -286,12 +300,20 @@ impl GripEdit {
Ok(Step::Continue)
}
Input::Point(p) => {
let m = self.matrix(p);
self.edit(s, p, m)
if self.mode == GripMode::Scale {
self.edit_scale(s, self.base.dist(p))
} else {
let m = self.matrix(p);
self.edit(s, p, m)
}
}
Input::Deferred(d) => {
let m = self.matrix(d.at);
self.edit(s, d.at, m)
if self.mode == GripMode::Scale {
self.edit_scale(s, self.base.dist(d.at))
} else {
let m = self.matrix(d.at);
self.edit(s, d.at, m)
}
}
Input::Text(t) => match self.mode {
GripMode::Rotate => {
@@ -300,7 +322,7 @@ impl GripEdit {
}
GripMode::Scale => {
let f = positive(number(&t))?;
self.edit(s, self.base, Some(Mat3::scale_about(self.base, f)))
self.edit_scale(s, f)
}
_ => Err(other("Requires a point or an option keyword.")),
},
@@ -327,14 +349,21 @@ impl GripEdit {
(Ask::RefFirst, Input::Text(t)) => self.ask = Ask::RefNew(value(&t)?),
(Ask::RefFirst, Input::Enter) => self.ask = Ask::RefNew(if rotate { 0.0 } else { 1.0 }),
(Ask::RefSecond(a), Input::Point(p)) => self.ask = Ask::RefNew(between(a, p)?),
(Ask::RefNew(_), Input::Point(p)) => {
let m = self.matrix(p).ok_or_else(|| other("Requires a positive length."))?;
return self.edit(s, p, Some(m));
(Ask::RefNew(r), Input::Point(p)) => {
if rotate {
let m = self.matrix(p).ok_or_else(|| other("Requires a positive length."))?;
return self.edit(s, p, Some(m));
}
let f = positive(Some(self.base.dist(p) / r))?;
return self.edit_scale(s, f);
}
(Ask::RefNew(r), Input::Text(t)) => {
let v = value(&t)?;
let m = if rotate { Mat3::rotate_about(self.base, v - r) } else { Mat3::scale_about(self.base, positive(Some(v / r))?) };
return self.edit(s, self.base, Some(m));
if rotate {
return self.edit(s, self.base, Some(Mat3::rotate_about(self.base, v - r)));
}
let f = positive(Some(v / r))?;
return self.edit_scale(s, f);
}
(_, Input::Enter) => self.ask = Ask::Mode,
_ => {}
+1 -1
View File
@@ -36,7 +36,7 @@ use oops::run_oops;
pub(crate) use oops::{Erased, erase_kept};
use select_then::{DisplaceM, Op, SelectThen};
use stretch::{StretchM, run_stretch};
pub(crate) use transform::{holds_ole_frame, ole_refusal, refuse_ole_frames, transform_entities};
pub(crate) use transform::{at_elevation, holds_ole_frame, ole_refusal, refuse_ole_frames, scale_entities, transform_entities};
use transform::{mirror_entities, mirror_kind, run_copy, run_erase, run_mirror, run_move, run_rotate, run_scale};
pub(crate) use trim::{
CUT_ONCE, Edges, Overlay, edge_segments, edge_segments_over, extend, extend_kind, extended, json_pick_error, trim, trim_kind, trimmed,
+78 -44
View File
@@ -27,12 +27,11 @@ pub(super) struct SelectThen {
objs: Vec<Handle>,
pts: Vec<Vec2>,
reference: bool,
/// ROTATE Reference: the reference angle (radians), once known. Its first point, and the
/// first of the two new-angle points, are kept in `ref_from`.
/// ROTATE Reference: the reference angle (radians), once known.
ref_angle: Option<f64>,
/// ROTATE Reference: the new angle is given by two points (the `Points` option).
/// ROTATE/SCALE Reference: the new angle/length is given by two points (the `Points` option).
ref_points: bool,
/// SCALE Reference: first point of a reference length given by two points.
/// ROTATE/SCALE Reference: first point of a reference or `Points` pair given by two points.
ref_from: Option<Vec2>,
/// SCALE Reference: the reference length, once known.
ref_len: Option<f64>,
@@ -127,30 +126,47 @@ impl SelectThen {
}
}
/// SCALE Reference: reference length (typed, or two points), then new length (typed, or a
/// point measured from the base point). The scale factor is new length / reference length.
/// SCALE Reference: reference length (typed, or two points), then new length (typed, a point
/// measured from the base point, or two points after `Points`). The scale factor is new length /
/// reference length.
fn scale_reference(&mut self, s: &mut Session, i: Input) -> Result<Step> {
let Some(base) = self.pts.first().copied() else { return Ok(Step::Done) };
match (self.ref_len, self.ref_from, i) {
(None, None, Input::Point(p)) => {
if matches!(&i, Input::Keyword(k) if k == "Copy") {
self.copy_mode = true;
s.echo("Scaling a copy of the selected objects.");
return Ok(Step::Continue);
}
let Some(r) = self.ref_len else {
match (self.ref_from, i) {
(None, Input::Point(p)) => self.ref_from = Some(p),
(None, Input::Text(t)) => self.ref_len = Some(require_length(number(&t))?),
(None, Input::Enter) => self.ref_len = Some(1.0),
(Some(a), Input::Point(p)) => {
self.ref_len = Some(require_length(Some(a.dist(p)))?);
self.ref_from = None;
}
(_, Input::Enter) => return Ok(Step::Done),
_ => {}
}
return Ok(Step::Continue);
};
match (self.ref_points, self.ref_from, i) {
(false, _, Input::Keyword(k)) if k == "Points" => {
self.ref_points = true;
self.ref_from = None;
Ok(Step::Continue)
}
(false, _, Input::Point(p)) => self.scale_by(s, base, base.dist(p) / r),
(false, _, Input::Text(t)) => {
let n = require_length(number(&t))?;
self.scale_by(s, base, n / r)
}
(true, None, Input::Point(p)) => {
self.ref_from = Some(p);
Ok(Step::Continue)
}
(None, None, Input::Text(t)) => {
self.ref_len = Some(require_length(number(&t))?);
Ok(Step::Continue)
}
(None, None, Input::Enter) => {
self.ref_len = Some(1.0);
Ok(Step::Continue)
}
(None, Some(a), Input::Point(p)) => {
self.ref_len = Some(require_length(Some(a.dist(p)))?);
Ok(Step::Continue)
}
(Some(r), _, Input::Point(p)) => self.scale_by(s, base, base.dist(p) / r),
(Some(r), _, Input::Text(t)) => {
let n = require_length(number(&t))?;
(true, Some(a), Input::Point(p)) => {
let n = require_length(Some(a.dist(p)))?;
self.scale_by(s, base, n / r)
}
(_, _, Input::Enter) => Ok(Step::Done),
@@ -158,6 +174,26 @@ impl SelectThen {
}
}
/// The prompt while SCALE Reference collects its lengths.
fn scale_reference_prompt(&self) -> Prompt {
let base = self.pts.first().copied();
match (self.ref_len, self.ref_points, self.ref_from) {
(None, _, None) => Prompt::new("Specify reference length", Accept::POINT_OR_NUMBER).kw(&["Copy"]).default("1"),
(None, _, Some(p)) | (Some(_), true, Some(p)) => Prompt::new("Specify second point", Accept::POINT).base(p),
(Some(_), false, _) => Prompt::new("Specify new length", Accept::POINT_OR_NUMBER).kw(&["Points", "Copy"]).base_opt(base).distance(),
(Some(_), true, None) => Prompt::new("Specify first point", Accept::POINT),
}
}
/// Live factor and rubber-band anchor while SCALE Reference previews with the cursor at `c`.
fn scale_reference_factor(&self, base: Vec2, c: Vec2) -> Option<(f64, Vec2)> {
match (self.ref_len, self.ref_points, self.ref_from) {
(Some(r), false, _) => positive_length(Some(base.dist(c) / r)).map(|f| (f, base)),
(Some(r), true, Some(a)) => positive_length(Some(a.dist(c) / r)).map(|f| (f, a)),
_ => None,
}
}
/// ROTATE Reference: reference angle (typed, or two points), then the new angle (typed, a
/// point measured from the base point, or two points after `Points`). The objects turn by the
/// new angle minus the reference angle.
@@ -316,11 +352,7 @@ impl Interactive for SelectThen {
let k = self.pts.len();
let base = self.pts.first().copied();
if self.op == Op::Scale && self.reference {
return match (self.ref_len, self.ref_from) {
(Some(_), _) => Prompt::new("Specify new length", Accept::POINT_OR_NUMBER).base_opt(base),
(None, Some(p)) => Prompt::new("Specify second point", Accept::POINT).base(p),
(None, None) => Prompt::new("Specify reference length", Accept::POINT_OR_NUMBER).default("1"),
};
return self.scale_reference_prompt();
}
if self.op == Op::Rotate && self.reference {
return self.rotate_reference_prompt();
@@ -468,16 +500,15 @@ impl Interactive for SelectThen {
return Vec::new();
}
let Some(base) = self.pts.first().copied() else { return Vec::new() };
let m = match self.op {
Op::Move | Op::Copy => Mat3::translate(c - base),
Op::Rotate => Mat3::rotate_about(base, base.angle_to(c)),
Op::Scale if !self.reference => Mat3::scale_about(base, base.dist(c).max(1e-9)),
Op::Scale => match self.ref_len.and_then(|r| positive_length(Some(base.dist(c) / r))) {
Some(f) => Mat3::scale_about(base, f),
None if self.ref_len.is_some() => return Vec::new(),
let (m, rubber_from) = match self.op {
Op::Move | Op::Copy => (Mat3::translate(c - base), base),
Op::Rotate => (Mat3::rotate_about(base, base.angle_to(c)), base),
Op::Scale if !self.reference => (Mat3::scale_about(base, base.dist(c).max(1e-9)), base),
Op::Scale => match self.scale_reference_factor(base, c) {
Some((f, from)) => (Mat3::scale_about(base, f), from),
None => return self.ref_from.map(|a| vec![line(a, c)]).unwrap_or_default(),
},
Op::Mirror if !self.ask_erase => Mat3::mirror(base, c),
Op::Mirror if !self.ask_erase => (Mat3::mirror(base, c), base),
_ => return Vec::new(),
};
let Ok(d) = s.doc() else { return Vec::new() };
@@ -496,7 +527,7 @@ impl Interactive for SelectThen {
k
})
.collect();
out.push(line(base, c));
out.push(line(rubber_from, c));
out
}
/// Separate shared GPU transforms from objects that need an individual MIRROR preview.
@@ -505,15 +536,18 @@ impl Interactive for SelectThen {
return None;
}
let base = self.pts.first().copied()?;
let matrix = match self.op {
Op::Move | Op::Copy => Mat3::translate(c - base),
Op::Rotate => Mat3::rotate_about(base, base.angle_to(c)),
Op::Scale if !self.reference => Mat3::scale_about(base, base.dist(c).max(1e-9)),
Op::Scale => Mat3::scale_about(base, self.ref_len.and_then(|r| positive_length(Some(base.dist(c) / r)))?),
Op::Mirror if !self.ask_erase => Mat3::mirror(base, c),
let (matrix, rubber_from) = match self.op {
Op::Move | Op::Copy => (Mat3::translate(c - base), base),
Op::Rotate => (Mat3::rotate_about(base, base.angle_to(c)), base),
Op::Scale if !self.reference => (Mat3::scale_about(base, base.dist(c).max(1e-9)), base),
Op::Scale => {
let (f, from) = self.scale_reference_factor(base, c)?;
(Mat3::scale_about(base, f), from)
}
Op::Mirror if !self.ask_erase => (Mat3::mirror(base, c), base),
_ => return None,
};
let mut extra = vec![line(base, c)];
let mut extra = vec![line(rubber_from, c)];
if self.op != Op::Mirror {
return Some(crate::prompt::Drag { handles: self.objs.clone(), matrix, extra, clipboard: false });
}
+91
View File
@@ -532,6 +532,97 @@ fn scale_reference_typed_and_picked() {
assert!(end(&s).near(Vec2::new(50.0, 0.0), 1e-9));
}
#[test]
fn scale_reference_points_and_copy() {
fn line_ends(s: &Session) -> Vec<Vec2> {
s.doc()
.unwrap()
.model
.iter()
.filter_map(|e| match &e.kind {
EntityKind::Line(l) => Some(l.b.xy()),
_ => None,
})
.collect()
}
let mut s = Session::new();
s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap();
// Reference 10 via two points, then Points option with two points of length 30 -> (30, 0).
for t in ["scale", "all", "", "0,0", "r", "0,0", "10,0"] {
s.cmdline(t).unwrap();
}
let p = s.current_prompt().unwrap();
assert_eq!(p.message, "Specify new length");
assert!(p.keywords.contains(&"Points".to_string()));
assert!(p.keywords.contains(&"Copy".to_string()));
s.cmdline("p").unwrap();
assert_eq!(s.current_prompt().unwrap().message, "Specify first point");
s.cmdline("5,5").unwrap();
assert_eq!(s.current_prompt().unwrap().message, "Specify second point");
s.cmdline("5,35").unwrap();
assert!(s.running.is_none());
assert!(line_ends(&s)[0].near(Vec2::new(30.0, 0.0), 1e-9));
// Coinciding Points are rejected without leaving the second-point prompt; a valid point completes.
for t in ["scale", "all", "", "0,0", "r", "30", "p", "5,5", "5,5"] {
s.cmdline(t).unwrap();
}
assert!(s.running.is_some());
assert_eq!(s.current_prompt().unwrap().message, "Specify second point");
s.cmdline("5,25").unwrap();
assert!(s.running.is_none());
assert!(line_ends(&s)[0].near(Vec2::new(20.0, 0.0), 1e-9));
// Copy entered inside Reference mode before reference length keeps the original and adds a scaled copy.
for t in ["scale", "all", "", "0,0", "r", "c", "20", "40"] {
s.cmdline(t).unwrap();
}
assert!(s.running.is_none());
let ends = line_ends(&s);
assert_eq!(ends.len(), 2);
assert!(ends.iter().any(|p| p.near(Vec2::new(20.0, 0.0), 1e-9)));
assert!(ends.iter().any(|p| p.near(Vec2::new(40.0, 0.0), 1e-9)));
// Copy entered at "Specify new length" combined with Points scales a copy.
for t in ["scale", "l", "", "0,0", "r", "40", "c", "p", "0,0", "10,0"] {
s.cmdline(t).unwrap();
}
assert!(s.running.is_none());
let ends = line_ends(&s);
assert_eq!(ends.len(), 3);
assert!(ends.iter().any(|p| p.near(Vec2::new(10.0, 0.0), 1e-9)));
}
#[test]
fn hot_grip_scale_scales_heights_and_thickness() {
let mut s = Session::new();
let r = s.execute("text", &json!({"at": [10, 0], "height": 2.0, "text": "H"})).unwrap();
let h = cadcraft_doc::Handle::parse_hex(r["handle"].as_str().unwrap()).unwrap();
s.doc_mut()
.unwrap()
.modify_entity(h, |e| {
e.common.thickness = 3.0;
if let EntityKind::Text(t) = &mut e.kind {
t.insert.z = 5.0;
}
})
.unwrap();
s.set_selection(vec![h]);
s.start_grip_edit(&[(h, 0)]).unwrap();
// STRETCH -> MOVE -> ROTATE -> SCALE
for _ in 0..3 {
s.input(Input::Enter).unwrap();
}
assert!(s.current_prompt().unwrap().message.contains("** SCALE **"));
s.cmdline("2").unwrap();
assert!(s.running.is_none());
let e = s.doc().unwrap().entity(h).unwrap();
assert_eq!(e.common.thickness, 6.0);
let EntityKind::Text(t) = &e.kind else { panic!("expected text") };
assert_eq!(t.height, 4.0);
assert_eq!(t.insert.z, 10.0);
}
#[test]
fn layers_and_properties() {
let mut s = Session::new();