From efb4e94c2f2a5a3a384f7ee2fb6f9ee3e34aceb0 Mon Sep 17 00:00:00 2001 From: HaikuZen Date: Sun, 29 Nov 2026 19:11:20 +0100 Subject: [PATCH] Add fit-to-area scaling and machine bed-size check Fit to area (`fit_to_area`, `--fit-to-area W,H`): - Uniformly scales the drawing so its plotted strokes fit within W x H mm, preserving aspect ratio, and places its corner at `origin`. - Either axis may be left empty to leave it unconstrained. - Measures strokes only, since fills and images are not plotted. - `fit_shrink_only` / `--fit-shrink-only true` never enlarges drawings. Bed-size check (`machine.bed_size`, `--bed-size W,H`): - After conversion, checks every stroke against a bed from (0,0) to W x H mm. - `bed_check` is `error` by default (no g-code is written, exit code 1); `warn` / `--bed-check warn` writes g-code and prints a warning. - Error messages report how far the drawing overshoots each edge. - New `svg_to_gcode_with_bounds` and `check_bed_bounds` in the library; `svg_to_gcode` is unchanged. Web UI: new settings fields for fit area, shrink-only, bed size and warn-only; out-of-bed drawings show an alert and are skipped unless warn-only is enabled. Settings without the new fields load unchanged. Co-Authored-By: Claude Opus 5.5 --- cli/src/main.rs | 86 ++++++++++++++++++++++-- g_code/src/bounds.rs | 122 ++++++++++++++++++++++++++++++++++ g_code/src/config/mod.rs | 19 ++++++ g_code/src/lib.rs | 29 ++++++-- g_code/src/turtle.rs | 9 ++- star/src/lower/mod.rs | 109 +++++++++++++++++++++++------- star/src/turtle/mod.rs | 85 +++++++++++++++++++++++ star/src/turtle/preprocess.rs | 23 +++++-- web/src/forms/inputs.rs | 24 +++++++ web/src/forms/mod.rs | 51 +++++++++++++- web/src/main.rs | 45 +++++++++++-- web/src/state.rs | 31 ++++++++- 12 files changed, 588 insertions(+), 45 deletions(-) create mode 100644 g_code/src/bounds.rs diff --git a/cli/src/main.rs b/cli/src/main.rs index 25a72d17..5d5aa194 100644 --- a/cli/src/main.rs +++ b/cli/src/main.rs @@ -13,12 +13,12 @@ use g_code::{ emit::{FormatOptions, format_gcode_io}, parse::snippet_parser, }; -use log::{error, info}; +use log::{error, info, warn}; use roxmltree::ParsingOptions; use svg2gcode::{ - Machine, - config::{ConversionOptions, Settings, SupportedFunctionality, Version}, - svg_to_gcode, + Machine, check_bed_bounds, + config::{BedCheck, ConversionOptions, Settings, SupportedFunctionality, Version}, + svg_to_gcode_with_bounds, }; use svgtypes::LengthListParser; @@ -111,6 +111,57 @@ struct Opt { /// Starting point , usefull only if try optimize path #[arg(long)] starting_point: Option, + /// Scale the drawing to fit within an area of this width and height in mm (i.e. 200,150) + /// + /// The aspect ratio is preserved and the drawing's corner is placed at `--origin`. + /// Leave an axis empty to leave it unconstrained (i.e. "200," or ",150"). + #[arg(long)] + fit_to_area: Option, + /// With `--fit-to-area`, only shrink drawings that are too large; never enlarge small ones + #[arg(long)] + fit_shrink_only: Option, + /// Width and height of the machine's bed in mm (i.e. 300,200), starting at 0,0 + /// + /// The drawing is checked against it after conversion; see `--bed-check`. + /// Leave an axis empty to skip checking it (i.e. "300," or ",200"). + #[arg(long)] + bed_size: Option, + /// What to do when the drawing goes past the edges of `--bed-size` + #[arg(long, value_enum)] + bed_check: Option, +} + +#[derive(Debug, Clone, Copy, clap::ValueEnum)] +enum BedCheckArg { + /// Refuse to write g-code (default) + Error, + /// Write g-code anyway and print a warning + Warn, +} + +impl From for BedCheck { + fn from(arg: BedCheckArg) -> Self { + match arg { + BedCheckArg::Error => BedCheck::Error, + BedCheckArg::Warn => BedCheck::Warn, + } + } +} + +/// Parses "width,height" in mm, where either may be empty. +fn parse_area(value: &str, what: &str) -> [Option; 2] { + let mut area = [None; 2]; + for (i, dimension) in value.split(',').take(2).enumerate() { + let dimension = dimension.trim(); + if !dimension.is_empty() { + let dimension = dimension + .parse::() + .unwrap_or_else(|_| panic!("could not parse {what} dimension")); + assert!(dimension > 0., "{what} dimensions must be positive"); + area[i] = Some(dimension); + } + } + area } fn main() -> io::Result<()> { @@ -191,6 +242,18 @@ fn main() -> io::Result<()> { } } } + if let Some(fit_to_area) = opt.fit_to_area { + settings.conversion.inner.fit_to_area = parse_area(&fit_to_area, "area"); + } + if let Some(fit_shrink_only) = opt.fit_shrink_only { + settings.conversion.inner.fit_shrink_only = fit_shrink_only; + } + if let Some(bed_size) = opt.bed_size { + settings.machine.bed_size = parse_area(&bed_size, "bed"); + } + if let Some(bed_check) = opt.bed_check { + settings.machine.bed_check = bed_check.into(); + } if let Some(line_numbers) = opt.line_numbers { settings.postprocess.line_numbers = line_numbers; @@ -358,7 +421,20 @@ fn main() -> io::Result<()> { ) .unwrap(); - let program = svg_to_gcode(&document, &settings.conversion, options, machine); + let (program, bounds) = + svg_to_gcode_with_bounds(&document, &settings.conversion, options, machine); + + if let Err(out_of_bounds) = check_bed_bounds(bounds, settings.machine.bed_size) { + match settings.machine.bed_check { + BedCheck::Error => { + error!( + "{out_of_bounds}. No g-code was written. Try --fit-to-area or --origin to move the drawing onto the bed, or --bed-check warn to write it anyway." + ); + std::process::exit(1); + } + BedCheck::Warn => warn!("{out_of_bounds}"), + } + } if let Some(out_path) = opt.out { format_gcode_io( diff --git a/g_code/src/bounds.rs b/g_code/src/bounds.rs new file mode 100644 index 00000000..9ddc9282 --- /dev/null +++ b/g_code/src/bounds.rs @@ -0,0 +1,122 @@ +use std::fmt; + +use lyon_geom::Box2D; + +/// Allowance for floating point noise, in millimeters. +const EPSILON: f64 = 1e-6; + +/// The drawing extends past the edges of the machine's bed. +#[derive(Debug, Clone, PartialEq)] +pub struct OutOfBounds { + /// Bounding box of the drawing in millimeters. + pub bounds: Box2D, + /// Bed width and height in millimeters (see [`crate::config::MachineConfig::bed_size`]). + pub bed_size: [Option; 2], + /// How far the drawing goes past each edge, in millimeters, as `(edge, overshoot)`. + pub overshoot: Vec<(&'static str, f64)>, +} + +impl fmt::Display for OutOfBounds { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let bed = self + .bed_size + .map(|dim| dim.map_or_else(|| "any".to_owned(), |d| format!("{d}"))); + write!( + f, + "drawing spans X {:.3}..{:.3} mm, Y {:.3}..{:.3} mm, which does not fit the {} x {} mm bed (", + self.bounds.min.x, + self.bounds.max.x, + self.bounds.min.y, + self.bounds.max.y, + bed[0], + bed[1], + )?; + for (i, (edge, overshoot)) in self.overshoot.iter().enumerate() { + if i > 0 { + f.write_str(", ")?; + } + write!(f, "{overshoot:.3} mm past the {edge} edge")?; + } + f.write_str(")") + } +} + +impl std::error::Error for OutOfBounds {} + +/// Checks that `bounds` lies within a bed spanning from `(0, 0)` to `bed_size`, in millimeters. +/// +/// An axis of `bed_size` that is `None` is not checked. Nothing drawn (`bounds` is `None`) always fits. +pub fn check_bed_bounds( + bounds: Option>, + bed_size: [Option; 2], +) -> Result<(), OutOfBounds> { + let Some(bounds) = bounds else { + return Ok(()); + }; + let [width, height] = bed_size; + let mut overshoot = vec![]; + if let Some(width) = width { + if bounds.min.x < -EPSILON { + overshoot.push(("left", -bounds.min.x)); + } + if bounds.max.x > width + EPSILON { + overshoot.push(("right", bounds.max.x - width)); + } + } + if let Some(height) = height { + if bounds.min.y < -EPSILON { + overshoot.push(("bottom", -bounds.min.y)); + } + if bounds.max.y > height + EPSILON { + overshoot.push(("top", bounds.max.y - height)); + } + } + if overshoot.is_empty() { + Ok(()) + } else { + Err(OutOfBounds { + bounds, + bed_size, + overshoot, + }) + } +} + +#[cfg(test)] +mod tests { + use lyon_geom::point; + + use super::*; + + fn bbox(min: (f64, f64), max: (f64, f64)) -> Box2D { + Box2D::new(point(min.0, min.1), point(max.0, max.1)) + } + + #[test] + fn inside_bed_is_ok() { + assert!( + check_bed_bounds(Some(bbox((0., 0.), (300., 200.))), [Some(300.), Some(200.)]).is_ok() + ); + assert!(check_bed_bounds(None, [Some(1.), Some(1.)]).is_ok()); + assert!(check_bed_bounds(Some(bbox((-5., -5.), (900., 900.))), [None, None]).is_ok()); + } + + #[test] + fn outside_bed_reports_each_edge() { + let err = check_bed_bounds( + Some(bbox((-2., 1.), (310., 250.))), + [Some(300.), Some(200.)], + ) + .unwrap_err(); + assert_eq!( + err.overshoot, + vec![("left", 2.), ("right", 10.), ("top", 50.)] + ); + assert!(err.to_string().contains("10.000 mm past the right edge")); + } + + #[test] + fn unchecked_axis_is_ignored() { + assert!(check_bed_bounds(Some(bbox((0., -50.), (100., 500.))), [Some(100.), None]).is_ok()); + } +} diff --git a/g_code/src/config/mod.rs b/g_code/src/config/mod.rs index 728f3a68..ca91a451 100644 --- a/g_code/src/config/mod.rs +++ b/g_code/src/config/mod.rs @@ -109,6 +109,25 @@ pub struct MachineConfig { serde(default, deserialize_with = "deserialize_string_or_strings") )] pub end_sequence: Option, + /// Width and height of the machine's bed in millimeters, starting at `(0, 0)`. + /// + /// When set, the drawing is checked against it after conversion (see [`MachineConfig::bed_check`]). + /// Setting an axis to `None` disables the check for that axis. + pub bed_size: [Option; 2], + /// What to do when the drawing extends past [`MachineConfig::bed_size`]. + pub bed_check: BedCheck, +} + +/// What to do when the drawing does not fit on the machine's bed. +#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] +#[cfg_attr(feature = "serde", serde(rename_all = "lowercase"))] +#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] +pub enum BedCheck { + /// Refuse to produce g-code. + #[default] + Error, + /// Produce g-code anyway, but warn about it. + Warn, } #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] diff --git a/g_code/src/lib.rs b/g_code/src/lib.rs index 62fa8723..073d0af5 100644 --- a/g_code/src/lib.rs +++ b/g_code/src/lib.rs @@ -3,6 +3,7 @@ #![cfg_attr(not(test), deny(unused_crate_dependencies))] use g_code::emit::Token; +use lyon_geom::Box2D; use roxmltree::Document; use rust_decimal::{Decimal, prelude::FromPrimitive}; use svg2star::{ @@ -10,9 +11,15 @@ use svg2star::{ turtle::CoordinateSystem, }; -pub use self::{machine::Machine, turtle::GCodeTurtle}; +pub use self::{ + bounds::{OutOfBounds, check_bed_bounds}, + machine::Machine, + turtle::GCodeTurtle, +}; use crate::config::GCodeConfig; +/// Checks that generated paths stay within the machine's bed. +mod bounds; pub mod config; /// Emulates the generic state of an arbitrary machine that runs G-Code. pub mod machine; @@ -29,6 +36,19 @@ pub fn svg_to_gcode<'a, 'input: 'a>( options: ConversionOptions, machine: Machine<'input>, ) -> Vec> { + svg_to_gcode_with_bounds(doc, config, options, machine).0 +} + +/// Like [`svg_to_gcode`], but also returns the bounding box (in mm) of everything drawn with the tool on. +/// +/// Pass the bounding box to [`check_bed_bounds`] to verify it fits on the machine's bed. +/// It is `None` when nothing was drawn. +pub fn svg_to_gcode_with_bounds<'a, 'input: 'a>( + doc: &'a Document, + config: &GCodeConfig, + options: ConversionOptions, + machine: Machine<'input>, +) -> (Vec>, Option>) { let gcode_turtle = self::turtle::GCodeTurtle { machine, tolerance: Decimal::from_f64(config.tolerance) @@ -38,13 +58,14 @@ pub fn svg_to_gcode<'a, 'input: 'a>( .unwrap_or_default() .normalize(), program: vec![], + bounds: None, }; - svg_to_turtle( + let turtle = svg_to_turtle( doc, &config.inner, options, gcode_turtle, CoordinateSystem::YUp, - ) - .program + ); + (turtle.program, turtle.bounds) } diff --git a/g_code/src/turtle.rs b/g_code/src/turtle.rs index bb2903de..b7ac5a0f 100644 --- a/g_code/src/turtle.rs +++ b/g_code/src/turtle.rs @@ -1,7 +1,7 @@ use std::{borrow::Cow, fmt::Debug}; use ::g_code::{command, emit::Token}; -use lyon_geom::{LineSegment, Point, SvgArc}; +use lyon_geom::{Box2D, LineSegment, Point, SvgArc}; use rust_decimal::{Decimal, prelude::*}; use svg2star::turtle::{ Turtle, @@ -17,6 +17,8 @@ pub struct GCodeTurtle<'input> { pub tolerance: Decimal, pub feedrate: Decimal, pub program: Vec>, + /// Bounding box of everything drawn with the tool on, in millimeters. + pub bounds: Option>, } impl<'input> GCodeTurtle<'input> { @@ -146,6 +148,11 @@ impl Turtle for GCodeTurtle<'_> { fn stroke(&mut self, stroke: Stroke) { let start = stroke.start_point(); + let stroke_bounds = stroke.bounding_box(); + self.bounds = Some(match self.bounds { + Some(b) => Box2D::from_points([b.min, b.max, stroke_bounds.min, stroke_bounds.max]), + None => stroke_bounds, + }); self.tool_off(); diff --git a/star/src/lower/mod.rs b/star/src/lower/mod.rs index d54d3733..15195594 100644 --- a/star/src/lower/mod.rs +++ b/star/src/lower/mod.rs @@ -56,6 +56,17 @@ pub struct ConversionConfig { /// pub selector_filter: Option, pub starting_point: [Option; 2], + /// Uniformly scale the drawing so it fits within an area of this width and height in millimeters. + /// + /// The drawing's tight bounding box is scaled (up or down) while preserving its aspect ratio, + /// then placed with its corner at [`ConversionConfig::origin`] (an empty origin axis is treated as `0`). + /// + /// Setting an axis to `None` leaves that axis unconstrained. Setting both to `None` disables the behavior. + pub fit_to_area: [Option; 2], + /// Only shrink drawings that are too large for [`ConversionConfig::fit_to_area`]. + /// + /// Drawings that already fit keep their size, but are still moved to the origin. + pub fit_shrink_only: bool, } const fn zero_origin() -> [Option; 2] { @@ -71,6 +82,8 @@ impl Default for ConversionConfig { optimize_path_order: false, selector_filter: None, starting_point: zero_origin(), + fit_to_area: [None; 2], + fit_shrink_only: false, } } } @@ -183,15 +196,7 @@ pub fn svg_to_turtle( visit::depth_first_visit(doc, &mut visitor); visitor.end(); - visitor - .terrarium - .finish() - .into_inner() - .into_inner() - // Include the origin so drawings within the page keep their layout. - .map_or_else(Box2D::default, |bb| { - Box2D::from_points([Point::zero(), bb.min, bb.max]) - }) + visitor.terrarium.finish().into_inner() }; // Convert from millimeters to user units @@ -199,23 +204,41 @@ pub fn svg_to_turtle( let starting_point = config.starting_point.map(|dim| dim.map(mm_to_user_units)); - let origin_transform = match config.origin { - [None, Some(origin_y)] => { - let bb = bounding_box_generator(); - Transform2D::translation(0., mm_to_user_units(origin_y - bb.min.y)) - } - [Some(origin_x), None] => { - let bb = bounding_box_generator(); - Transform2D::translation(mm_to_user_units(origin_x - bb.min.x), 0.) - } - [Some(origin_x), Some(origin_y)] => { - let bb = bounding_box_generator(); - Transform2D::translation( - mm_to_user_units(origin_x - bb.min.x), - mm_to_user_units(origin_y - bb.min.y), - ) + let origin_transform = if config.fit_to_area.iter().any(Option::is_some) { + fit_to_area_transform( + bounding_box_generator().into_stroke_bounding_box(), + config.fit_to_area, + config.fit_shrink_only, + config.origin, + mm_to_user_units, + ) + } else { + // Include the origin so drawings within the page keep their layout. + let page_bounding_box = || { + bounding_box_generator() + .into_inner() + .map_or_else(Box2D::default, |bb| { + Box2D::from_points([Point::zero(), bb.min, bb.max]) + }) + }; + match config.origin { + [None, Some(origin_y)] => { + let bb = page_bounding_box(); + Transform2D::translation(0., mm_to_user_units(origin_y - bb.min.y)) + } + [Some(origin_x), None] => { + let bb = page_bounding_box(); + Transform2D::translation(mm_to_user_units(origin_x - bb.min.x), 0.) + } + [Some(origin_x), Some(origin_y)] => { + let bb = page_bounding_box(); + Transform2D::translation( + mm_to_user_units(origin_x - bb.min.x), + mm_to_user_units(origin_y - bb.min.y), + ) + } + [None, None] => Transform2D::identity(), } - [None, None] => Transform2D::identity(), }; let mut conversion_visitor = ConversionVisitor { @@ -260,6 +283,42 @@ pub fn svg_to_turtle( conversion_visitor.terrarium.finish().into_inner() } +/// Builds a transform (in user units) that uniformly scales the drawing's bounding box `bb` (in mm) +/// to fit within `area` (in mm) and moves its corner to `origin` (in mm). +/// +/// Axes of `area` that are `None` do not constrain the scale. Degenerate (zero-size) axes are ignored. +/// With `shrink_only`, the scale never exceeds `1`. +fn fit_to_area_transform( + bb: Option>, + area: [Option; 2], + shrink_only: bool, + origin: [Option; 2], + mm_to_user_units: impl Fn(f64) -> f64, +) -> Transform2D { + let Some(bb) = bb else { + return Transform2D::identity(); + }; + let size = [bb.width(), bb.height()]; + let scale = area + .iter() + .zip(size) + .filter_map(|(target, actual)| match target { + Some(target) if *target > 0. && actual > f64::EPSILON => Some(target / actual), + _ => None, + }) + .reduce(f64::min) + .unwrap_or(1.); + let scale = if shrink_only { scale.min(1.) } else { scale }; + let [origin_x, origin_y] = origin.map(|o| o.unwrap_or(0.)); + + Transform2D::translation(-mm_to_user_units(bb.min.x), -mm_to_user_units(bb.min.y)) + .then_scale(scale, scale) + .then_translate(lyon_geom::vector( + mm_to_user_units(origin_x), + mm_to_user_units(origin_y), + )) +} + #[allow(clippy::too_many_arguments)] fn svg_to_optimized_strokes<'a, 'input>( doc: &Document<'input>, diff --git a/star/src/turtle/mod.rs b/star/src/turtle/mod.rs index 49215808..b3c1755e 100644 --- a/star/src/turtle/mod.rs +++ b/star/src/turtle/mod.rs @@ -770,6 +770,91 @@ mod tests { } } + /// [`ConversionConfig::fit_to_area`] uniformly scales the drawing into the area at the origin. + #[test] + fn test_fit_to_area_scales_and_positions_drawing() { + #[derive(Debug, Default)] + struct BoundsTurtle { + bounds: Option>, + } + impl Turtle for BoundsTurtle { + fn begin(&mut self) {} + fn end(&mut self) {} + fn stroke(&mut self, stroke: Stroke) { + let b = stroke.bounding_box(); + self.bounds = Some(match self.bounds { + Some(old) => lyon_geom::Box2D::from_points([old.min, old.max, b.min, b.max]), + None => b, + }); + } + fn fill(&mut self, _shape: Shape) {} + #[cfg(feature = "image")] + fn image(&mut self, _image: super::elements::RasterImage) {} + } + + // A 40mm x 20mm rectangle offset inside a 100mm page. + let doc = roxmltree::Document::parse( + r#" + "#, + ) + .unwrap(); + + for (area, origin, expected_min, expected_max) in [ + // Width-limited: 40 -> 200 (scale 5), height becomes 100 + ( + [Some(200.), Some(150.)], + [Some(0.), Some(0.)], + point(0., 0.), + point(200., 100.), + ), + // Height-limited, scaling down: 20 -> 10 (scale 0.5) + ( + [Some(200.), Some(10.)], + [Some(5.), Some(7.)], + point(5., 7.), + point(25., 17.), + ), + // Only width constrained, empty origin axes treated as 0 + ( + [Some(80.), None], + [None, None], + point(0., 0.), + point(80., 40.), + ), + ] { + for shrink_only in [false, true] { + // Shrink-only keeps the 40mm x 20mm size when the drawing already fits. + let (expected_min, expected_max) = + if shrink_only && expected_max.x - expected_min.x > 40. { + (expected_min, expected_min + lyon_geom::vector(40., 20.)) + } else { + (expected_min, expected_max) + }; + let config = ConversionConfig { + fit_to_area: area, + fit_shrink_only: shrink_only, + origin, + ..ConversionConfig::default() + }; + let bounds = svg_to_turtle( + &doc, + &config, + ConversionOptions::default(), + BoundsTurtle::default(), + CoordinateSystem::YUp, + ) + .bounds + .unwrap(); + assert!( + (bounds.min - expected_min).length() < 1e-6 + && (bounds.max - expected_max).length() < 1e-6, + "{area:?} {origin:?} shrink_only={shrink_only}: expected {expected_min:?}..{expected_max:?}, got {bounds:?}" + ); + } + } + } + /// [`ConversionConfig::origin`] shifts overflowing geometry relative to the coordinate system. #[test] fn test_origin_adheres_to_coordinate_system() { diff --git a/star/src/turtle/preprocess.rs b/star/src/turtle/preprocess.rs index cf62661b..ac5e6dbd 100644 --- a/star/src/turtle/preprocess.rs +++ b/star/src/turtle/preprocess.rs @@ -7,6 +7,8 @@ use super::{Turtle, elements::Shape}; #[derive(Debug, Default)] pub struct PreprocessTurtle { bounding_box: Option>, + /// Bounding box of strokes only, i.e. what a plotter actually draws. + stroke_bounding_box: Option>, } impl PreprocessTurtle { @@ -14,11 +16,22 @@ impl PreprocessTurtle { self.bounding_box } - fn expand(&mut self, bbox: Box2D) { - self.bounding_box = Some(match self.bounding_box { + /// Bounding box of strokes only, falling back to the bounding box of everything when there are none. + /// + /// Used by [`crate::lower::ConversionConfig::fit_to_area`] since fills and images are not plotted. + pub fn into_stroke_bounding_box(self) -> Option> { + self.stroke_bounding_box.or(self.bounding_box) + } + + fn union(existing: Option>, bbox: Box2D) -> Box2D { + match existing { Some(existing) => Box2D::from_points([existing.min, existing.max, bbox.min, bbox.max]), None => bbox, - }); + } + } + + fn expand(&mut self, bbox: Box2D) { + self.bounding_box = Some(Self::union(self.bounding_box, bbox)); } } @@ -37,6 +50,8 @@ impl Turtle for PreprocessTurtle { } fn stroke(&mut self, stroke: super::elements::Stroke) { - self.expand(stroke.bounding_box()); + let bbox = stroke.bounding_box(); + self.stroke_bounding_box = Some(Self::union(self.stroke_bounding_box, bbox)); + self.expand(bbox); } } diff --git a/web/src/forms/inputs.rs b/web/src/forms/inputs.rs index 4d3af7e7..e23f6a5f 100644 --- a/web/src/forms/inputs.rs +++ b/web/src/forms/inputs.rs @@ -80,4 +80,28 @@ form_input! { origin => 1, settings.conversion.inner.origin => 1, } + FitAreaWidth { + "Fit to area width (mm)", + "Scale the drawing to fit within this width, preserving aspect ratio. Leave empty to disable.", + fit_to_area => 0, + settings.conversion.inner.fit_to_area => 0, + } + FitAreaHeight { + "Fit to area height (mm)", + "Scale the drawing to fit within this height, preserving aspect ratio. Leave empty to disable.", + fit_to_area => 1, + settings.conversion.inner.fit_to_area => 1, + } + BedWidth { + "Bed width (mm)", + "Width of the machine's bed, starting at X 0. Leave empty to skip checking.", + bed_size => 0, + settings.machine.bed_size => 0, + } + BedHeight { + "Bed height (mm)", + "Height of the machine's bed, starting at Y 0. Leave empty to skip checking.", + bed_size => 1, + settings.machine.bed_size => 1, + } } diff --git a/web/src/forms/mod.rs b/web/src/forms/mod.rs index 725cd612..db685a79 100644 --- a/web/src/forms/mod.rs +++ b/web/src/forms/mod.rs @@ -25,7 +25,10 @@ mod editors; mod inputs; use editors::{BeginSequenceInput, EndSequenceInput, ToolOffSequenceInput, ToolOnSequenceInput}; -use inputs::{DpiInput, FeedrateInput, OriginXInput, OriginYInput, ToleranceInput}; +use inputs::{ + BedHeightInput, BedWidthInput, DpiInput, FeedrateInput, FitAreaHeightInput, FitAreaWidthInput, + OriginXInput, OriginYInput, ToleranceInput, +}; #[function_component(SettingsForm)] pub fn settings_form() -> Html { @@ -39,6 +42,11 @@ pub fn settings_form() -> Html { .origin .iter() .all(|opt| opt.as_ref().is_some_and(Result::is_err)) + || form_state + .fit_to_area + .iter() + .chain(form_state.bed_size.iter()) + .any(|opt| opt.as_ref().is_some_and(Result::is_err)) || form_state .tool_on_sequence .as_ref() @@ -68,6 +76,15 @@ pub fn settings_form() -> Html { form.optimize_path_order = event.target_unchecked_into::().checked(); }); + let on_fit_shrink_only_change = form_dispatch.reduce_mut_callback_with(|form, event: Event| { + form.fit_shrink_only = event.target_unchecked_into::().checked(); + }); + + let on_bed_check_warn_only_change = + form_dispatch.reduce_mut_callback_with(|form, event: Event| { + form.bed_check_warn_only = event.target_unchecked_into::().checked(); + }); + let on_checksums_change = form_dispatch.reduce_mut_callback_with(|form, event: Event| { form.checksums = event.target_unchecked_into::().checked(); }); @@ -130,6 +147,38 @@ pub fn settings_form() -> Html {
+
+ +
+
+ +
+
+ + + +
+
+ +
+
+ +
+
+ + + +
Html { let mut zip = ZipWriter::new(Cursor::new(vec![])); let opts = SimpleFileOptions::default().compression_method(CompressionMethod::Stored); + let mut bed_messages = vec![]; + let mut zipped_files = 0; + if app_store.svgs.len() > 1 { zip.add_directory("svg2gcode_output", opts).unwrap(); } @@ -118,8 +121,31 @@ fn app() -> Html { ) .unwrap(); - let program = - svg_to_gcode(&document, &app_store.settings.conversion, options, machine); + let (program, bounds) = svg_to_gcode_with_bounds( + &document, + &app_store.settings.conversion, + options, + machine, + ); + + if let Err(out_of_bounds) = + check_bed_bounds(bounds, app_store.settings.machine.bed_size) + { + match app_store.settings.machine.bed_check { + BedCheck::Error => { + bed_messages.push(format!( + "{}: {out_of_bounds}. Skipped, no G-Code was generated.", + svg.filename + )); + continue; + } + BedCheck::Warn => { + log::warn!("{}: {out_of_bounds}", svg.filename); + bed_messages + .push(format!("Warning for {}: {out_of_bounds}.", svg.filename)); + } + } + } let filepath = if app_store.svgs.len() > 1 { PathBuf::from("svg2gcode_output") @@ -152,6 +178,7 @@ fn app() -> Html { prompt_download(filepath, gcode.as_bytes()); } _multiple => { + zipped_files += 1; zip.start_file(filepath.to_string_lossy(), opts).unwrap(); format_gcode_io( @@ -172,7 +199,17 @@ fn app() -> Html { } } - if app_store.svgs.len() > 1 { + if !bed_messages.is_empty() { + let message = format!( + "The drawing does not fit on the machine's bed.\n\n{}\n\nAdjust the bed size, origin, or fit to area in Settings.", + bed_messages.join("\n\n") + ); + if let Some(window) = web_sys::window() { + let _ = window.alert_with_message(&message); + } + } + + if app_store.svgs.len() > 1 && zipped_files > 0 { zip.set_comment(format!( "Created with svg2gcode: https://sameer.github.io/svg2gcode/\n{}", env!("CARGO_PKG_DESCRIPTION") diff --git a/web/src/state.rs b/web/src/state.rs index ec3cd34a..b53315da 100644 --- a/web/src/state.rs +++ b/web/src/state.rs @@ -2,7 +2,8 @@ use std::{convert::TryInto, num::ParseFloatError}; use serde::{Deserialize, Serialize}; use svg2gcode::config::{ - ConversionConfig, MachineConfig, PostprocessConfig, Settings, SupportedFunctionality, Version, + BedCheck, ConversionConfig, MachineConfig, PostprocessConfig, Settings, SupportedFunctionality, + Version, }; use svgtypes::Length; use thiserror::Error; @@ -25,6 +26,10 @@ pub struct FormState { pub line_numbers: bool, pub newline_before_comment: bool, pub starting_point: [Option>; 2], + pub fit_to_area: [Option>; 2], + pub fit_shrink_only: bool, + pub bed_size: [Option>; 2], + pub bed_check_warn_only: bool, } impl Default for FormState { @@ -61,6 +66,11 @@ impl TryInto for &FormState { self.starting_point[0].clone().transpose()?, self.starting_point[1].clone().transpose()?, ], + fit_to_area: [ + self.fit_to_area[0].clone().transpose()?, + self.fit_to_area[1].clone().transpose()?, + ], + fit_shrink_only: self.fit_shrink_only, }, tolerance: self.tolerance.clone()?, feedrate: self.feedrate.clone()?, @@ -89,6 +99,15 @@ impl TryInto for &FormState { .clone() .transpose() .map_err(FormStateConversionError::GCode)?, + bed_size: [ + self.bed_size[0].clone().transpose()?, + self.bed_size[1].clone().transpose()?, + ], + bed_check: if self.bed_check_warn_only { + BedCheck::Warn + } else { + BedCheck::Error + }, }, postprocess: PostprocessConfig { checksums: self.checksums, @@ -126,6 +145,16 @@ impl From<&Settings> for FormState { settings.conversion.inner.starting_point[0].map(Ok), settings.conversion.inner.starting_point[1].map(Ok), ], + fit_to_area: [ + settings.conversion.inner.fit_to_area[0].map(Ok), + settings.conversion.inner.fit_to_area[1].map(Ok), + ], + fit_shrink_only: settings.conversion.inner.fit_shrink_only, + bed_size: [ + settings.machine.bed_size[0].map(Ok), + settings.machine.bed_size[1].map(Ok), + ], + bed_check_warn_only: settings.machine.bed_check == BedCheck::Warn, } } }