//! Sprites: the unit of the depth sort. A sprite owns world-space //! primitives and the extent points its sort box is computed from. //! //! Every drawing method takes coordinates in the sprite's frame ([`Xf`]): //! an object placed at (x, y, z) and turned in 90 degree steps draws around //! its own origin, and the sprite stores world coordinates. use crate::prim::{Prim, Style, Zs, P2, P3}; use crate::proj::C; use serde::{Deserialize, Serialize}; /// Placement frame: translate by (x, y, z) after turning `q` quarter turns /// counter-clockwise (seen from above). #[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)] pub struct Xf { pub x: f64, pub y: f64, pub z: f64, pub q: u8, } impl Xf { /// Frame at (x, y, z) turned by `deg` (rounded to a multiple of 90). pub fn new(x: f64, y: f64, z: f64, deg: f64) -> Self { let q = ((deg / 90.0).round() as i64).rem_euclid(4) as u8; Xf { x, y, z, q } } /// Turn a plan vector into the world. #[inline] pub fn v(&self, x: f64, y: f64) -> P2 { match self.q { 0 => [x, y], 1 => [-y, x], 2 => [-x, -y], _ => [y, -x], } } /// World plan vector back into the frame. #[inline] pub fn v_inv(&self, x: f64, y: f64) -> P2 { match self.q { 0 => [x, y], 1 => [y, -x], 2 => [-x, -y], _ => [-y, x], } } #[inline] pub fn p(&self, x: f64, y: f64) -> P2 { let v = self.v(x, y); [v[0] + self.x, v[1] + self.y] } #[inline] pub fn p3(&self, p: P3) -> P3 { let q = self.p(p[0], p[1]); [q[0], q[1], p[2] + self.z] } #[inline] pub fn z(&self, z: f64) -> f64 { z + self.z } /// An axis-aligned rectangle in the frame as a world rectangle. pub fn rect(&self, x0: f64, y0: f64, x1: f64, y1: f64) -> [f64; 4] { let a = self.p(x0, y0); let b = self.p(x1, y1); [ a[0].min(b[0]), a[1].min(b[1]), a[0].max(b[0]), a[1].max(b[1]), ] } pub fn pts(&self, pts: &[P2]) -> Vec { pts.iter().map(|q| self.p(q[0], q[1])).collect() } /// World point back into the frame. pub fn inv(&self, x: f64, y: f64) -> P2 { self.v_inv(x - self.x, y - self.y) } } #[derive(Clone, Debug)] enum Frame { Group { cls: String, style: String, items: Vec, }, Seq { items: Vec<(P2, Vec)>, cur: Option<(P2, Vec)>, }, } #[derive(Clone, Debug, Default, Serialize, Deserialize)] pub struct Sprite { /// Pick id; every element of the sprite carries it unless it has its own. pub id: String, /// Extra class on the sprite's `` (e.g. `iso-dim`). pub cls: String, /// Where the sprite was created ("scene.rhai:42"), shown by the dev viewer. pub src: Option, /// Scene-document object the sprite belongs to (the Studio selects and /// drags by this, tooltips use `id`). pub obj: Option, pub prims: Vec, /// Points that span the sprite's sort box (world coordinates). pub ext: Vec, /// Frame the drawing methods' coordinates are in. #[serde(skip)] pub xf: Xf, #[serde(skip)] frames: Vec, } /// One item of [`Sprite::seq`]: a plan anchor and the drawing. pub type SeqItem<'a> = (P2, Box); /// Points of an axis-aligned rectangle, counter-clockwise from (x0, y0). pub fn rect(x0: f64, y0: f64, x1: f64, y1: f64) -> Vec { vec![[x0, y0], [x1, y0], [x1, y1], [x0, y1]] } impl Sprite { pub fn new(id: impl Into, cls: impl Into) -> Self { Sprite { id: id.into(), cls: cls.into(), ..Default::default() } } pub fn with_frame(mut self, xf: Xf) -> Self { self.xf = xf; self } /// Add a world-space primitive to the open group / sequence item, or to /// the sprite. pub fn push(&mut self, p: Prim) -> &mut Self { match self.frames.last_mut() { Some(Frame::Group { items, .. }) => items.push(p), Some(Frame::Seq { cur, .. }) => match cur { Some((_, items)) => items.push(p), // a primitive before the first seq_item starts an item at the origin None => *cur = Some(([0.0, 0.0], vec![p])), }, None => self.prims.push(p), } self } // ---------------------------------------------------------- extents (frame coordinates) pub fn ext(&mut self, x: f64, y: f64, z: f64) -> &mut Self { let w = self.xf.p3([x, y, z]); self.ext.push(w); self } pub fn ext_box(&mut self, x0: f64, y0: f64, x1: f64, y1: f64, z0: f64, z1: f64) -> &mut Self { for z in [z0, z1] { self.ext(x0, y0, z) .ext(x1, y0, z) .ext(x1, y1, z) .ext(x0, y1, z); } self } fn ext_world(&mut self, pts: &[P2], z: f64) { for p in pts { self.ext.push([p[0], p[1], z]); } } // ---------------------------------------------------------- solids /// Axis-aligned box (`box` in scripts; `box` is a Rust keyword). #[allow(clippy::too_many_arguments)] pub fn cuboid( &mut self, x0: f64, y0: f64, x1: f64, y1: f64, z0: f64, z1: f64, st: Style, ) -> &mut Self { let r = self.xf.rect(x0, y0, x1, y1); let (z0, z1) = (self.xf.z(z0), self.xf.z(z1)); let pts = rect(r[0], r[1], r[2], r[3]); self.ext_world(&pts, z0); self.ext_world(&pts, z1); self.push(Prim::Prism { pts, z0: Zs::One(z0), z1: Zs::One(z1), st, }) } pub fn prism(&mut self, pts: Vec, z0: Zs, z1: Zs, st: Style) -> &mut Self { let pts = self.xf.pts(&pts); let dz = self.xf.z; let sh = |z: Zs| match z { Zs::One(v) => Zs::One(v + dz), Zs::Each(v) => Zs::Each(v.into_iter().map(|q| q + dz).collect()), }; let (z0, z1) = (sh(z0), sh(z1)); for (i, p) in pts.iter().enumerate() { self.ext.push([p[0], p[1], z0.at(i)]); self.ext.push([p[0], p[1], z1.at(i)]); } self.push(Prim::Prism { pts, z0, z1, st }) } pub fn cyl(&mut self, cx: f64, cy: f64, r: f64, z0: f64, z1: f64, st: Style) -> &mut Self { self.ext_box(cx - r, cy - r, cx + r, cy + r, z0, z1); let c = self.xf.p(cx, cy); let (z0, z1) = (self.xf.z(z0), self.xf.z(z1)); self.push(Prim::Cyl { c, r, z0, z1, st }) } #[allow(clippy::too_many_arguments)] pub fn frust( &mut self, cx: f64, cy: f64, r0: f64, r1: f64, z0: f64, z1: f64, n: u32, st: Style, ) -> &mut Self { let r = r0.max(r1); self.ext_box(cx - r, cy - r, cx + r, cy + r, z0, z1); let c = self.xf.p(cx, cy); let (z0, z1) = (self.xf.z(z0), self.xf.z(z1)); self.push(Prim::Frust { c, r0, r1, z0, z1, n: n.max(3), st, }) } /// Sloped slab (stair flight, ramp) over x0..x1, rising from y0 (za) to /// y1 (zb), th thick. #[allow(clippy::too_many_arguments)] pub fn slope( &mut self, x0: f64, x1: f64, y0: f64, y1: f64, za: f64, zb: f64, th: f64, mat: &str, ) -> &mut Self { let zt = vec![za, za, zb, zb]; let zb_: Vec = zt.iter().map(|z| z - th).collect(); self.prism( rect(x0, y0, x1, y1), Zs::Each(zb_), Zs::Each(zt), Style::mat(mat), ) } // ---------------------------------------------------------- surfaces /// Openings on the vertical face a -> b (outward normal on the right). pub fn open( &mut self, a: P2, b: P2, list: Vec<[f64; 4]>, cls: &str, id: Option, ) -> &mut Self { let (a, b) = (self.xf.p(a[0], a[1]), self.xf.p(b[0], b[1])); let dz = self.xf.z; let list: Vec<[f64; 4]> = list .into_iter() .map(|q| [q[0], q[1], q[2] + dz, q[3] + dz]) .collect(); let (dx, dy) = (b[0] - a[0], b[1] - a[1]); let l = (dx * dx + dy * dy).sqrt().max(1e-9); let (ux, uy) = (dx / l, dy / l); for q in &list { self.ext.push([a[0] + ux * q[0], a[1] + uy * q[0], q[2]]); self.ext.push([a[0] + ux * q[1], a[1] + uy * q[1], q[3]]); } self.push(Prim::Open { a, b, list, cls: cls.into(), id, }) } pub fn flat( &mut self, polys: Vec>, z: f64, cls: &str, id: Option, ) -> &mut Self { let polys: Vec> = polys.iter().map(|p| self.xf.pts(p)).collect(); let z = self.xf.z(z); for p in &polys { self.ext_world(p, z); } self.push(Prim::Flat { polys, z, cls: cls.into(), id, }) } pub fn lines(&mut self, segs: Vec<[f64; 4]>, z: f64, cls: &str) -> &mut Self { let segs: Vec<[f64; 4]> = segs .into_iter() .map(|s| { let a = self.xf.p(s[0], s[1]); let b = self.xf.p(s[2], s[3]); [a[0], a[1], b[0], b[1]] }) .collect(); let z = self.xf.z(z); for s in &segs { self.ext.push([s[0], s[1], z]); self.ext.push([s[2], s[3], z]); } self.push(Prim::Lines { segs, z, cls: cls.into(), id: None, }) } pub fn disc( &mut self, cx: f64, cy: f64, z: f64, r: f64, cls: &str, id: Option, ) -> &mut Self { self.ext_box(cx - r, cy - r, cx + r, cy + r, z, z); let c = self.xf.p(cx, cy); let z = self.xf.z(z); self.push(Prim::Disc { c, z, r, cls: cls.into(), id, }) } /// Planar 3D polygon shaded by its normal (see [`Prim::Face`]). pub fn face( &mut self, pts: Vec, mat: &str, id: Option, two_sided: bool, ) -> &mut Self { let pts: Vec = pts.into_iter().map(|p| self.xf.p3(p)).collect(); self.ext.extend(pts.iter().copied()); self.push(Prim::Face { pts, mat: mat.into(), id, two_sided, }) } /// 3D polygons as one path with a fixed class. pub fn poly(&mut self, polys: Vec>, cls: &str, id: Option) -> &mut Self { let polys: Vec> = polys .into_iter() .map(|p| p.into_iter().map(|q| self.xf.p3(q)).collect()) .collect(); for p in &polys { self.ext.extend(p.iter().copied()); } self.push(Prim::Poly { polys, cls: cls.into(), id, }) } // ---------------------------------------------------------- screen-space details /// Circle of r screen units (not part of the sort box: add `ext` if it /// sticks out of the sprite). pub fn circle(&mut self, at: P3, r: f64, off: P2, cls: &str) -> &mut Self { let at = self.xf.p3(at); self.push(Prim::Circle { at, r, off, cls: cls.into(), id: None, }) } pub fn stem(&mut self, x: f64, y: f64, z0: f64, z1: f64, w: f64, cls: &str) -> &mut Self { self.ext(x, y, z0).ext(x, y, z1); let at = self.xf.p(x, y); let (z0, z1) = (self.xf.z(z0), self.xf.z(z1)); self.push(Prim::Stem { at, z0, z1, w, cls: cls.into(), id: None, }) } /// A head (ball of radius r metres) centred at z. pub fn head(&mut self, x: f64, y: f64, z: f64, r: f64) -> &mut Self { self.ext(x, y, z + r); self.circle([x, y, z], r * C * 1.2, [0.0, 0.0], "iso-headc") } /// Standing figure: torso cylinder and head. pub fn person(&mut self, x: f64, y: f64, z: f64, cls: &str) -> &mut Self { self.cyl(x, y, 0.2, z, z + 1.2, Style::mat(cls).no_top()); self.ext(x, y, z + 1.65); self.circle([x, y, z + 1.45], 0.2 * C * 1.2, [0.0, 0.0], "iso-headc") } /// Seated figure: torso and head. pub fn sit(&mut self, x: f64, y: f64, z: f64, cls: &str) -> &mut Self { self.cyl(x, y, 0.21, z + 0.42, z + 1.12, Style::mat(cls).no_top()); self.head(x, y, z + 1.32, 0.2) } pub fn led(&mut self, x: f64, y: f64, z: f64, cls: &str) -> &mut Self { let c = if cls.is_empty() { "iso-led".to_string() } else { format!("iso-led {cls}") }; self.circle([x, y, z], 0.9, [0.0, 0.0], &c) } pub fn puffs(&mut self, x: f64, y: f64, z: f64, kind: &str, n: u32, dur: f64) -> &mut Self { let at = self.xf.p3([x, y, z]); self.push(Prim::Puffs { at, kind: kind.into(), n: n.max(1), dur, }) } pub fn fan(&mut self, x: f64, y: f64, z: f64, r: f64) -> &mut Self { let at = self.xf.p3([x, y, z]); self.push(Prim::Fan { at, r }) } pub fn raw(&mut self, at: Option, svg: impl Into) -> &mut Self { let at = at.map(|a| self.xf.p3(a)); self.push(Prim::Raw { at, svg: svg.into(), }) } // ---------------------------------------------------------- structure /// Open a ``; close it with [`Sprite::end_group`]. pub fn begin_group(&mut self, cls: &str, style: &str) -> &mut Self { self.frames.push(Frame::Group { cls: cls.into(), style: style.into(), items: vec![], }); self } pub fn end_group(&mut self) -> &mut Self { if let Some(Frame::Group { cls, style, items }) = self.frames.pop() { self.push(Prim::Group { cls, style, items }); } self } /// Start a back-to-front sequence; each [`Sprite::seq_item`] starts an /// item anchored at a plan point; [`Sprite::end_seq`] closes it. pub fn begin_seq(&mut self) -> &mut Self { self.frames.push(Frame::Seq { items: vec![], cur: None, }); self } pub fn seq_item(&mut self, at: P2) -> &mut Self { let at = self.xf.p(at[0], at[1]); if let Some(Frame::Seq { items, cur }) = self.frames.last_mut() { if let Some(c) = cur.take() { items.push(c); } *cur = Some((at, vec![])); } self } pub fn end_seq(&mut self) -> &mut Self { if let Some(Frame::Seq { mut items, cur }) = self.frames.pop() { if let Some(c) = cur { items.push(c); } self.push(Prim::Seq { items }); } self } /// Draw items back to front by the depth of their anchor. pub fn seq(&mut self, items: Vec>) -> &mut Self { self.begin_seq(); for (at, f) in items { self.seq_item(at); f(self); } self.end_seq() } /// Close any group or sequence left open (returns how many were open). pub fn finish(&mut self) -> usize { let n = self.frames.len(); while let Some(f) = self.frames.last() { match f { Frame::Group { .. } => { self.end_group(); } Frame::Seq { .. } => { self.end_seq(); } } } n } pub fn is_empty(&self) -> bool { self.prims.is_empty() } /// World bounding box of the extent points: [x0, y0, z0, x1, y1, z1]. pub fn world_box(&self) -> Option<[f64; 6]> { if self.ext.is_empty() { return None; } let mut b = [f64::MAX, f64::MAX, f64::MAX, f64::MIN, f64::MIN, f64::MIN]; for e in &self.ext { for k in 0..3 { b[k] = b[k].min(e[k]); b[k + 3] = b[k + 3].max(e[k]); } } Some(b) } } #[cfg(test)] mod tests { use super::*; #[test] fn box_extents_span_eight_corners() { let mut s = Sprite::new("a", ""); s.cuboid(0.0, 0.0, 2.0, 3.0, 0.0, 4.0, Style::mat("iso-wall")); assert_eq!(s.ext.len(), 8); assert_eq!(s.prims.len(), 1); } #[test] fn frame_moves_and_turns_a_box() { let mut s = Sprite::new("a", "").with_frame(Xf::new(10.0, 20.0, 1.0, 90.0)); // 4 m along local x, 2 m along local y, centred: after a quarter turn 2 m along x, 4 m along y s.cuboid(-2.0, -1.0, 2.0, 1.0, 0.0, 3.0, Style::mat("x")); let b = s.world_box().unwrap(); assert_eq!(b, [9.0, 18.0, 1.0, 11.0, 22.0, 4.0]); } #[test] fn frame_round_trips_points() { for deg in [0.0, 90.0, 180.0, 270.0, -90.0, 450.0] { let f = Xf::new(3.0, -4.0, 0.0, deg); let w = f.p(1.5, 2.5); let l = f.inv(w[0], w[1]); assert!( (l[0] - 1.5).abs() < 1e-12 && (l[1] - 2.5).abs() < 1e-12, "{deg}" ); } } #[test] fn groups_and_sequences_nest() { let mut s = Sprite::new("a", ""); s.begin_group("iso-a", ""); s.begin_seq(); s.seq_item([0.0, 0.0]); s.cuboid(0.0, 0.0, 1.0, 1.0, 0.0, 1.0, Style::mat("x")); s.seq_item([5.0, 0.0]); s.cuboid(5.0, 0.0, 6.0, 1.0, 0.0, 1.0, Style::mat("x")); s.end_seq(); s.end_group(); assert_eq!(s.prims.len(), 1); match &s.prims[0] { Prim::Group { items, .. } => match &items[0] { Prim::Seq { items } => assert_eq!(items.len(), 2), p => panic!("{p:?}"), }, p => panic!("{p:?}"), } } #[test] fn finish_closes_open_frames() { let mut s = Sprite::new("a", ""); s.begin_group("g", ""); s.cuboid(0.0, 0.0, 1.0, 1.0, 0.0, 1.0, Style::mat("x")); assert_eq!(s.finish(), 1); assert!(matches!(s.prims[0], Prim::Group { .. })); } }