sim_logic/rendering/screen/
polyline.rs1use super::{ScreenClip, ScreenVisualError, validate_draw_order_depth, vectors::apply_clip};
4use bevy_ecs::prelude::Component;
5use sim_engine::{Color, Layer, LogicalScreenPosition, SceneError, ScreenScene, StrokeStyle2d};
6use std::{error::Error, fmt, sync::Arc};
7
8#[derive(Debug, Clone, PartialEq, Component)]
19pub struct ScreenPolylineVisual {
20 points: Arc<Vec<LogicalScreenPosition>>,
21 style: Arc<StrokeStyle2d>,
24 max_points: usize,
25 layer: Layer,
26 depth: f32,
27 clip: ScreenClip,
28}
29
30impl ScreenPolylineVisual {
31 pub const DEFAULT_MAX_POINTS: usize = 65_536;
33
34 pub fn new(
38 points: &[LogicalScreenPosition],
39 style: StrokeStyle2d,
40 ) -> Result<Self, ScreenPolylineError> {
41 Self::with_point_limit(points, style, Self::DEFAULT_MAX_POINTS)
42 }
43 pub fn with_point_limit(
46 points: &[LogicalScreenPosition],
47 style: StrokeStyle2d,
48 max_points: usize,
49 ) -> Result<Self, ScreenPolylineError> {
50 validate(points, style, max_points)?;
51 Ok(Self {
52 points: copy_points(points)?,
53 style: Arc::new(style),
54 max_points,
55 layer: Layer::DEFAULT,
56 depth: 0.0,
57 clip: ScreenClip::Unclipped,
58 })
59 }
60 pub fn points(&self) -> &[LogicalScreenPosition] {
62 &self.points
63 }
64 pub const fn max_points(&self) -> usize {
66 self.max_points
67 }
68 pub fn style(&self) -> StrokeStyle2d {
70 *self.style
71 }
72 pub fn point_allocation_bytes(&self) -> usize {
75 self.points
76 .capacity()
77 .saturating_mul(size_of::<LogicalScreenPosition>())
78 }
79 pub fn set_points(
81 &mut self,
82 points: &[LogicalScreenPosition],
83 ) -> Result<(), ScreenPolylineError> {
84 if self.points() == points {
85 return Ok(());
86 }
87 validate(points, *self.style, self.max_points)?;
88 self.points = copy_points(points)?;
89 Ok(())
90 }
91 pub fn set_style(&mut self, style: StrokeStyle2d) -> Result<(), ScreenPolylineError> {
93 if *self.style == style {
94 return Ok(());
95 }
96 validate(self.points(), style, self.max_points)?;
97 *Arc::make_mut(&mut self.style) = style;
98 Ok(())
99 }
100 pub const fn layer(&self) -> Layer {
102 self.layer
103 }
104 pub fn set_layer(&mut self, layer: Layer) {
106 self.layer = layer;
107 }
108 pub const fn draw_order_depth(&self) -> f32 {
110 self.depth
111 }
112 pub fn set_draw_order_depth(&mut self, depth: f32) -> Result<(), ScreenVisualError> {
114 validate_draw_order_depth(depth)?;
115 self.depth = depth;
116 Ok(())
117 }
118 pub const fn clip(&self) -> ScreenClip {
120 self.clip
121 }
122 pub fn set_clip(&mut self, clip: ScreenClip) {
124 self.clip = clip;
125 }
126
127 pub fn hit_test_centerline(
134 &self,
135 sample: crate::input::PointerSample,
136 radius: f32,
137 ) -> Result<bool, ScreenPolylineError> {
138 if !radius.is_finite() || radius < 0.0 {
139 return Err(ScreenPolylineError::InvalidPickRadius);
140 }
141 if !self.clip.contains_pointer(sample) {
142 return Ok(false);
143 }
144 let p = sample.position().to_vec2();
145 Ok(self.points.windows(2).any(|pair| {
146 let a = pair[0].to_vec2();
147 let b = pair[1].to_vec2();
148 let dx = f64::from(b.x()) - f64::from(a.x());
149 let dy = f64::from(b.y()) - f64::from(a.y());
150 let px = f64::from(p.x()) - f64::from(a.x());
151 let py = f64::from(p.y()) - f64::from(a.y());
152 let t = ((px * dx + py * dy) / (dx * dx + dy * dy)).clamp(0.0, 1.0);
153 (px - t * dx).hypot(py - t * dy) <= f64::from(radius)
154 }))
155 }
156 pub(crate) fn append(&self, scene: &mut ScreenScene) -> Result<(), SceneError> {
157 if !apply_clip(scene, self.clip)? {
158 return Ok(());
159 }
160 scene.try_styled_polyline_on_layer(self.layer, self.points(), *self.style)
161 }
162}
163
164fn validate(
165 points: &[LogicalScreenPosition],
166 style: StrokeStyle2d,
167 limit: usize,
168) -> Result<(), ScreenPolylineError> {
169 if limit < 2 || points.len() > limit {
170 return Err(ScreenPolylineError::PointLimit {
171 limit,
172 requested: points.len(),
173 });
174 }
175 if points.len() >= 2 && points.first() == points.last() {
176 return Err(ScreenPolylineError::ClosedPathUnsupported);
177 }
178 let mut probe = ScreenScene::new(Color::TRANSPARENT).map_err(ScreenPolylineError::Geometry)?;
181 probe
182 .try_styled_polyline(points, style)
183 .map_err(ScreenPolylineError::Geometry)
184}
185fn copy_points(
186 points: &[LogicalScreenPosition],
187) -> Result<Arc<Vec<LogicalScreenPosition>>, ScreenPolylineError> {
188 let mut owned = Vec::new();
189 owned
190 .try_reserve_exact(points.len())
191 .map_err(|_| ScreenPolylineError::Allocation {
192 requested_bytes: points
193 .len()
194 .saturating_mul(size_of::<LogicalScreenPosition>()),
195 })?;
196 owned.extend_from_slice(points);
197 Ok(Arc::new(owned))
198}
199
200#[derive(Debug)]
202pub enum ScreenPolylineError {
203 PointLimit {
205 limit: usize,
207 requested: usize,
209 },
210 ClosedPathUnsupported,
212 Geometry(SceneError),
214 Allocation {
216 requested_bytes: usize,
218 },
219 InvalidPickRadius,
221}
222impl fmt::Display for ScreenPolylineError {
223 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
224 match self {
225 Self::PointLimit { limit, requested } => write!(
226 f,
227 "screen path requests {requested} points with limit {limit} (minimum limit: 2)"
228 ),
229 Self::ClosedPathUnsupported => {
230 f.write_str("closed styled screen paths require an Engine closed-path API")
231 }
232 Self::Geometry(error) => write!(f, "screen path: {error}"),
233 Self::Allocation { requested_bytes } => {
234 write!(f, "screen path could not reserve {requested_bytes} bytes")
235 }
236 Self::InvalidPickRadius => {
237 f.write_str("path picking radius must be finite and nonnegative")
238 }
239 }
240 }
241}
242impl Error for ScreenPolylineError {
243 fn source(&self) -> Option<&(dyn Error + 'static)> {
244 match self {
245 Self::Geometry(error) => Some(error),
246 _ => None,
247 }
248 }
249}