use crate::font;
use crate::Point;
use serde::{Deserialize, Serialize};
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub enum GraphicLayer {
#[serde(rename = "F.SilkS")]
FrontSilk,
#[serde(rename = "B.SilkS")]
BackSilk,
#[serde(rename = "F.Fab")]
FrontFab,
#[serde(rename = "B.Fab")]
BackFab,
#[serde(rename = "F.CrtYd")]
FrontCourtyard,
#[serde(rename = "B.CrtYd")]
BackCourtyard,
}
impl GraphicLayer {
pub const ALL: [Self; 6] = [
Self::FrontSilk,
Self::BackSilk,
Self::FrontFab,
Self::BackFab,
Self::FrontCourtyard,
Self::BackCourtyard,
];
pub fn name(self) -> &'static str {
match self {
Self::FrontSilk => "F.SilkS",
Self::BackSilk => "B.SilkS",
Self::FrontFab => "F.Fab",
Self::BackFab => "B.Fab",
Self::FrontCourtyard => "F.CrtYd",
Self::BackCourtyard => "B.CrtYd",
}
}
pub fn from_name(name: &str) -> Option<Self> {
Some(match name {
"F.SilkS" | "F.Silkscreen" => Self::FrontSilk,
"B.SilkS" | "B.Silkscreen" => Self::BackSilk,
"F.Fab" => Self::FrontFab,
"B.Fab" => Self::BackFab,
"F.CrtYd" | "F.Courtyard" => Self::FrontCourtyard,
"B.CrtYd" | "B.Courtyard" => Self::BackCourtyard,
_ => return None,
})
}
pub fn front(self) -> bool {
matches!(self, Self::FrontSilk | Self::FrontFab | Self::FrontCourtyard)
}
pub fn flipped(self) -> Self {
match self {
Self::FrontSilk => Self::BackSilk,
Self::BackSilk => Self::FrontSilk,
Self::FrontFab => Self::BackFab,
Self::BackFab => Self::FrontFab,
Self::FrontCourtyard => Self::BackCourtyard,
Self::BackCourtyard => Self::FrontCourtyard,
}
}
pub fn is_silk(self) -> bool {
matches!(self, Self::FrontSilk | Self::BackSilk)
}
pub fn is_courtyard(self) -> bool {
matches!(self, Self::FrontCourtyard | Self::BackCourtyard)
}
pub fn default_width(self) -> i32 {
match self {
Self::FrontSilk | Self::BackSilk => crate::fabrication::SILK_WIDTH,
Self::FrontFab | Self::BackFab => 100,
Self::FrontCourtyard | Self::BackCourtyard => 50,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum GraphicShape {
Polyline { points: Vec<Point> },
Arc { start: Point, mid: Point, end: Point },
Circle { center: Point, radius: i32 },
Text { at: Point, text: String, height: i32 },
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct LayerGraphic {
pub layer: GraphicLayer,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub width: Option<i32>,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub filled: bool,
#[serde(flatten)]
pub shape: GraphicShape,
}
const LIMIT: i32 = 100_000_000;
pub const MAX_TEXT: usize = 200;
const CIRCLE_FACETS: i32 = 64;
impl LayerGraphic {
pub fn new(layer: GraphicLayer, shape: GraphicShape) -> Self {
Self { layer, width: None, filled: false, shape }
}
pub fn width(&self) -> i32 {
self.width.unwrap_or(self.layer.default_width())
}
pub fn closed(&self) -> bool {
match &self.shape {
GraphicShape::Polyline { points } => points.len() >= 4 && points.first() == points.last(),
GraphicShape::Circle { .. } => true,
_ => false,
}
}
pub fn problem(&self) -> Option<&'static str> {
let inside = |p: &Point| p.x.abs_diff(0) <= LIMIT as u32 && p.y.abs_diff(0) <= LIMIT as u32;
if !(1..=10_000).contains(&self.width()) && !(self.filled && self.width() == 0) {
return Some("needs a line width between 0.001 and 10 mm");
}
match &self.shape {
GraphicShape::Polyline { points } => {
if points.len() < 2 {
return Some("needs at least two points");
}
if points.len() > 100_000 {
return Some("has more than 100000 points");
}
if !points.iter().all(inside) {
return Some("is outside the drawing area");
}
}
GraphicShape::Arc { start, mid, end } => {
if ![start, mid, end].into_iter().all(inside)
|| !arc_points(*start, *mid, *end).iter().all(inside)
{
return Some("is outside the drawing area");
}
}
GraphicShape::Circle { center, radius } => {
if !inside(center) {
return Some("is outside the drawing area");
}
if !(1..=LIMIT).contains(radius) {
return Some("needs a radius between 0.001 mm and 100 m");
}
}
GraphicShape::Text { at, text, height } => {
if !inside(at) {
return Some("is outside the drawing area");
}
if text.trim().is_empty() || text.chars().count() > MAX_TEXT {
return Some("needs text of 1 to 200 characters");
}
if !(100..=100_000).contains(height) {
return Some("needs a text height between 0.1 and 100 mm");
}
}
}
if self.filled && !self.closed() {
return Some("is filled but not closed");
}
None
}
pub fn strokes(&self, mirrored: bool) -> Vec<Vec<Point>> {
match &self.shape {
GraphicShape::Polyline { points } => vec![points.clone()],
GraphicShape::Arc { start, mid, end } => vec![arc_points(*start, *mid, *end)],
GraphicShape::Circle { center, radius } => {
let r = f64::from(*radius);
vec![(0..=CIRCLE_FACETS)
.map(|i| {
let t = std::f64::consts::TAU * f64::from(i) / f64::from(CIRCLE_FACETS);
Point::new(center.x + (r * t.cos()).round() as i32, center.y + (r * t.sin()).round() as i32)
})
.collect()]
}
GraphicShape::Text { at, text, height } => {
font::text_strokes(text, *at, *height, mirrored, &mut Default::default())
}
}
}
pub fn points(&self) -> Vec<Point> {
self.strokes(false).into_iter().flatten().collect()
}
}
pub fn arc_points(a: Point, m: Point, b: Point) -> Vec<Point> {
let (ax, ay, mx, my, bx, by) = (
a.x as f64, a.y as f64, m.x as f64, m.y as f64, b.x as f64, b.y as f64,
);
let d = 2. * (ax * (my - by) + mx * (by - ay) + bx * (ay - my));
if d.abs() < 0.01 {
return vec![a, m, b];
}
let (aa, mm, bb) = (ax * ax + ay * ay, mx * mx + my * my, bx * bx + by * by);
let cx = (aa * (my - by) + mm * (by - ay) + bb * (ay - my)) / d;
let cy = (aa * (bx - mx) + mm * (ax - bx) + bb * (mx - ax)) / d;
let start = (ay - cy).atan2(ax - cx);
let mid = (my - cy).atan2(mx - cx);
let end = (by - cy).atan2(bx - cx);
let tau = std::f64::consts::TAU;
let ccw = (end - start).rem_euclid(tau);
let sweep = if (mid - start).rem_euclid(tau) <= ccw {
ccw
} else {
ccw - tau
};
let r = ((ax - cx).powi(2) + (ay - cy).powi(2)).sqrt();
(0..=32)
.map(|i| {
let t = start + sweep * i as f64 / 32.;
Point::new(
(cx + r * t.cos()).round() as i32,
(cy + r * t.sin()).round() as i32,
)
})
.collect()
}