Skip to main content

sim_engine/scene/
mod.rs

1use std::{
2    error::Error,
3    fmt,
4    mem::size_of,
5    panic::{AssertUnwindSafe, catch_unwind, resume_unwind},
6};
7
8use crate::{Color, LogicalScreenPosition, LogicalScreenVector, Rect, Vec2};
9
10mod styles;
11pub use styles::{
12    Fill, LinearGradient, RadialGradient, Shadow, ShapeStyle, Stroke, StrokeCap2d,
13    StrokeDashPattern2d, StrokeJoin2d, StrokeMarker2d, StrokeMarkerAnchor2d, StrokeStyle2d,
14    StrokeStyleError, StrokeWidthMode2d,
15};
16
17pub(crate) const CIRCLE_SEGMENTS: usize = 64;
18pub(crate) const ROUND_CAP_SEGMENTS: usize = 16;
19pub(crate) const CORNER_SEGMENTS: usize = 12;
20pub(crate) const TESSELLATED_VERTEX_BYTES: usize = 20 * size_of::<f32>();
21const MIN_STROKE_TURN_SINE: f64 = 0.000_1;
22/// Maximum visible dash pieces one command may request from tessellation.
23pub const MAX_STROKE_DASH_SUBSEGMENTS: usize = 1_000_000;
24
25/// Primitive category attached to structured scene validation errors.
26#[derive(Debug, Clone, Copy, PartialEq, Eq)]
27pub enum ScenePrimitive {
28    /// Circle geometry or style.
29    Circle,
30    /// Rectangle geometry or style.
31    Rect,
32    /// Single line geometry or stroke.
33    Line,
34    /// Connected polyline geometry or stroke.
35    Polyline,
36}
37
38/// Work category constrained by a [`SceneBudget`].
39#[derive(Debug, Clone, Copy, PartialEq, Eq)]
40#[non_exhaustive]
41pub enum SceneBudgetResource {
42    /// Accepted scene commands.
43    Commands,
44    /// Points retained by polyline commands.
45    Points,
46    /// Conservative upper bound for generated triangle-list vertices.
47    TessellatedVertices,
48    /// Command payload bytes retained by the scene.
49    RetainedBytes,
50    /// Committed command-vector and owned polyline allocation bytes.
51    AllocationBytes,
52    /// Bytes uploaded for generated scene vertices.
53    UploadBytes,
54    /// Draw batches caused by ordering and clip changes.
55    DrawBatches,
56}
57
58/// Explicit upper bounds for engine-owned ordinary-scene work.
59///
60/// Limits may be zero to construct a background-only scene. Retained bytes
61/// count logical command values and owned polyline storage. Allocation bytes
62/// additionally bound committed spare command-vector capacity; allocator
63/// bookkeeping and transactional replacement overlap are excluded. Vertex and
64/// upload limits use the renderer's conservative
65/// triangle-list estimate, which is checked again after tessellation.
66#[derive(Debug, Clone, Copy, PartialEq, Eq)]
67pub struct SceneBudget {
68    max_commands: usize,
69    max_points: usize,
70    max_tessellated_vertices: usize,
71    max_retained_bytes: usize,
72    max_allocation_bytes: usize,
73    max_upload_bytes: usize,
74    max_draw_batches: usize,
75}
76
77impl SceneBudget {
78    /// Builds a complete budget for ordinary scene construction and rendering.
79    pub const fn new(
80        max_commands: usize,
81        max_points: usize,
82        max_tessellated_vertices: usize,
83        max_retained_bytes: usize,
84        max_allocation_bytes: usize,
85        max_upload_bytes: usize,
86        max_draw_batches: usize,
87    ) -> Self {
88        Self {
89            max_commands,
90            max_points,
91            max_tessellated_vertices,
92            max_retained_bytes,
93            max_allocation_bytes,
94            max_upload_bytes,
95            max_draw_batches,
96        }
97    }
98
99    /// Returns the maximum accepted command count.
100    pub const fn max_commands(self) -> usize {
101        self.max_commands
102    }
103
104    /// Returns the maximum retained polyline point count.
105    pub const fn max_points(self) -> usize {
106        self.max_points
107    }
108
109    /// Returns the maximum conservatively estimated vertex count.
110    pub const fn max_tessellated_vertices(self) -> usize {
111        self.max_tessellated_vertices
112    }
113
114    /// Returns the maximum retained command payload bytes.
115    pub const fn max_retained_bytes(self) -> usize {
116        self.max_retained_bytes
117    }
118
119    /// Returns the maximum committed command and polyline allocation bytes.
120    pub const fn max_allocation_bytes(self) -> usize {
121        self.max_allocation_bytes
122    }
123
124    /// Returns the maximum generated vertex upload bytes.
125    pub const fn max_upload_bytes(self) -> usize {
126        self.max_upload_bytes
127    }
128
129    /// Returns the maximum draw-batch count.
130    pub const fn max_draw_batches(self) -> usize {
131        self.max_draw_batches
132    }
133}
134
135/// Construction and conservative rendering work accumulated by a scene.
136#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
137pub struct SceneStatistics {
138    requested_commands: usize,
139    accepted_commands: usize,
140    rejected_commands: usize,
141    requested_by_primitive: PrimitiveCommandCounts,
142    accepted_by_primitive: PrimitiveCommandCounts,
143    rejected_by_primitive: PrimitiveCommandCounts,
144    retained_points: usize,
145    estimated_tessellated_vertices: usize,
146    retained_bytes: usize,
147    estimated_upload_bytes: usize,
148    estimated_draw_batches: usize,
149}
150
151impl SceneStatistics {
152    /// Returns all insertion attempts, including invalid and over-budget work.
153    pub const fn requested_commands(self) -> usize {
154        self.requested_commands
155    }
156
157    /// Returns commands currently retained by the scene.
158    pub const fn accepted_commands(self) -> usize {
159        self.accepted_commands
160    }
161
162    /// Returns insertion attempts rejected by validation, budget, or allocation.
163    pub const fn rejected_commands(self) -> usize {
164        self.rejected_commands
165    }
166
167    /// Returns insertion attempts grouped by primitive category.
168    pub const fn requested_by_primitive(self) -> PrimitiveCommandCounts {
169        self.requested_by_primitive
170    }
171
172    /// Returns currently retained commands grouped by primitive category.
173    pub const fn accepted_by_primitive(self) -> PrimitiveCommandCounts {
174        self.accepted_by_primitive
175    }
176
177    /// Returns rejected insertion attempts grouped by primitive category.
178    pub const fn rejected_by_primitive(self) -> PrimitiveCommandCounts {
179        self.rejected_by_primitive
180    }
181
182    /// Returns points retained by accepted polyline commands.
183    pub const fn retained_points(self) -> usize {
184        self.retained_points
185    }
186
187    /// Returns the conservative upper bound for tessellated vertices.
188    pub const fn estimated_tessellated_vertices(self) -> usize {
189        self.estimated_tessellated_vertices
190    }
191
192    /// Returns tracked command and owned polyline payload bytes.
193    pub const fn retained_bytes(self) -> usize {
194        self.retained_bytes
195    }
196
197    /// Returns estimated bytes uploaded for generated vertices.
198    pub const fn estimated_upload_bytes(self) -> usize {
199        self.estimated_upload_bytes
200    }
201
202    /// Returns the conservative draw-batch upper bound.
203    pub const fn estimated_draw_batches(self) -> usize {
204        self.estimated_draw_batches
205    }
206
207    fn with_command(mut self, command: &DrawCommand) -> Self {
208        let vertices = command.estimated_tessellated_vertices();
209        self.accepted_commands = self.accepted_commands.saturating_add(1);
210        self.accepted_by_primitive.increment(command.primitive());
211        self.retained_points = self
212            .retained_points
213            .saturating_add(command.retained_point_count());
214        self.estimated_tessellated_vertices =
215            self.estimated_tessellated_vertices.saturating_add(vertices);
216        self.retained_bytes = self.retained_bytes.saturating_add(command.retained_bytes());
217        self.estimated_upload_bytes = self
218            .estimated_upload_bytes
219            .saturating_add(vertices.saturating_mul(TESSELLATED_VERTEX_BYTES));
220        self.estimated_draw_batches = self.estimated_draw_batches.saturating_add(1);
221        self
222    }
223}
224
225/// Command counters grouped by ordinary 2D primitive category.
226#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
227pub struct PrimitiveCommandCounts {
228    circles: usize,
229    rectangles: usize,
230    lines: usize,
231    polylines: usize,
232}
233
234impl PrimitiveCommandCounts {
235    /// Returns circle command count.
236    pub const fn circles(self) -> usize {
237        self.circles
238    }
239
240    /// Returns rectangle command count.
241    pub const fn rectangles(self) -> usize {
242        self.rectangles
243    }
244
245    /// Returns single-line command count.
246    pub const fn lines(self) -> usize {
247        self.lines
248    }
249
250    /// Returns connected-polyline command count.
251    pub const fn polylines(self) -> usize {
252        self.polylines
253    }
254
255    /// Returns all primitive commands represented by these counters.
256    pub const fn total(self) -> usize {
257        self.circles
258            .saturating_add(self.rectangles)
259            .saturating_add(self.lines)
260            .saturating_add(self.polylines)
261    }
262
263    pub(crate) fn increment(&mut self, primitive: ScenePrimitive) {
264        match primitive {
265            ScenePrimitive::Circle => self.circles = self.circles.saturating_add(1),
266            ScenePrimitive::Rect => self.rectangles = self.rectangles.saturating_add(1),
267            ScenePrimitive::Line => self.lines = self.lines.saturating_add(1),
268            ScenePrimitive::Polyline => self.polylines = self.polylines.saturating_add(1),
269        }
270    }
271
272    pub(crate) fn adding(mut self, other: Self) -> Self {
273        self.circles = self.circles.saturating_add(other.circles);
274        self.rectangles = self.rectangles.saturating_add(other.rectangles);
275        self.lines = self.lines.saturating_add(other.lines);
276        self.polylines = self.polylines.saturating_add(other.polylines);
277        self
278    }
279}
280
281/// Reason a command or temporary scene state was rejected.
282#[derive(Debug, Clone, Copy, PartialEq, Eq)]
283pub enum SceneError {
284    /// Clear color is non-finite or outside normalized RGBA.
285    InvalidBackground,
286    /// Primitive coordinates contain NaN or infinity.
287    NonFiniteGeometry(ScenePrimitive),
288    /// Radius, size, corner radius, or stroke width is outside its valid range.
289    InvalidDimension(ScenePrimitive),
290    /// A line segment, or at least one consecutive polyline segment, is not drawable.
291    DegenerateGeometry(ScenePrimitive),
292    /// Consecutive polyline segments form a numerically ambiguous continuation or reversal.
293    ///
294    /// An almost-collinear change of direction cannot select a stable shader
295    /// join branch; a retraced centerline also has no interior-disjoint
296    /// alpha-blended representation. `vertex_index` identifies the path point.
297    DegenerateStrokeTurn {
298        /// Primitive containing the ambiguous turn.
299        primitive: ScenePrimitive,
300        /// Zero-based index of the shared turn point.
301        vertex_index: usize,
302    },
303    /// Shape has no fill, stroke, or shadow.
304    MissingStyle(ScenePrimitive),
305    /// Fill color or gradient configuration is invalid.
306    InvalidFill(ScenePrimitive),
307    /// Stroke width or color is invalid.
308    InvalidStroke(ScenePrimitive),
309    /// A dash pattern would expand into more retained triangle pieces than its
310    /// explicit per-command limit.
311    StrokeExpansionLimitExceeded {
312        /// Primitive whose stroke exceeded the limit.
313        primitive: ScenePrimitive,
314        /// Configured maximum number of emitted visible subsegments.
315        limit: usize,
316        /// Minimum visible-subsegment count that proved the limit was exceeded.
317        required: usize,
318    },
319    /// Dash/gap boundaries collapse at the source path's `f32` coordinate scale.
320    UnrepresentableStrokePattern(ScenePrimitive),
321    /// A tip-anchored arrow was used with dashes or a path containing more than
322    /// two points. Exact-vector markers currently require an undashed segment.
323    UnsupportedTipMarkerPath(ScenePrimitive),
324    /// Shadow offset, spread, or color is invalid.
325    InvalidShadow(ScenePrimitive),
326    /// Active logical screen clip is non-finite or empty.
327    InvalidScreenClip,
328    /// Pseudo-depth must be finite.
329    NonFiniteDepth,
330    /// An accepted command would exceed an explicit scene work limit.
331    BudgetExceeded {
332        /// Work category whose limit was exceeded.
333        resource: SceneBudgetResource,
334        /// Configured maximum for the category.
335        limit: usize,
336        /// Total category usage that the command requested.
337        requested: usize,
338    },
339    /// Engine-owned command storage could not be reserved without mutation.
340    AllocationFailed {
341        /// Conservative byte estimate associated with the failed reservation.
342        ///
343        /// Depending on the transactional path, this can describe one
344        /// command's retained payload or the total replacement/staging
345        /// allocation that could not be reserved. It is diagnostic context,
346        /// not a delta suitable for allocator accounting.
347        requested_bytes: usize,
348    },
349}
350
351impl fmt::Display for SceneError {
352    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
353        write!(formatter, "scene command rejected: {self:?}")
354    }
355}
356
357impl Error for SceneError {}
358
359/// Ordered list of visual draw commands for a single frame.
360///
361/// A scene contains renderable primitives only. It does not own simulation
362/// entities, domain rules, or time stepping.
363#[derive(Debug)]
364pub struct Scene {
365    background: Color,
366    /// Commands stored in draw order.
367    commands: Vec<SceneCommand>,
368    owned_payload_bytes: usize,
369    next_order: u64,
370    current_screen_clip: Option<ScreenClipRect>,
371    current_depth: f32,
372    budget: Option<SceneBudget>,
373    statistics: SceneStatistics,
374}
375
376impl Clone for Scene {
377    fn clone(&self) -> Self {
378        let commands = self.commands.clone();
379        let owned_payload_bytes = commands
380            .iter()
381            .map(|command| command.command.owned_allocation_bytes())
382            .fold(0usize, usize::saturating_add);
383        let mut statistics = self.statistics;
384        statistics.retained_bytes = commands
385            .len()
386            .saturating_mul(size_of::<SceneCommand>())
387            .saturating_add(owned_payload_bytes);
388        Self {
389            background: self.background,
390            commands,
391            owned_payload_bytes,
392            next_order: self.next_order,
393            current_screen_clip: self.current_screen_clip,
394            current_depth: self.current_depth,
395            budget: self.budget,
396            statistics,
397        }
398    }
399}
400
401impl Scene {
402    /// Creates an empty scene with a normalized linear-RGBA background color.
403    ///
404    /// This compatibility constructor is intentionally unbounded. Production
405    /// hosts handling externally sized visual state should prefer
406    /// [`Scene::with_budget`].
407    pub fn new(background: Color) -> Result<Self, SceneError> {
408        Self::create(background, None)
409    }
410
411    /// Creates an empty scene with explicit construction and rendering limits.
412    pub fn with_budget(background: Color, budget: SceneBudget) -> Result<Self, SceneError> {
413        Self::create(background, Some(budget))
414    }
415
416    fn create(background: Color, budget: Option<SceneBudget>) -> Result<Self, SceneError> {
417        if !background.is_normalized() {
418            return Err(SceneError::InvalidBackground);
419        }
420        Ok(Self {
421            background,
422            commands: Vec::new(),
423            owned_payload_bytes: 0,
424            next_order: 0,
425            current_screen_clip: None,
426            current_depth: 0.0,
427            budget,
428            statistics: SceneStatistics::default(),
429        })
430    }
431
432    /// Returns the normalized clear color used before drawing commands.
433    pub fn background(&self) -> Color {
434        self.background
435    }
436
437    /// Replaces the clear color used before drawing commands.
438    pub fn set_background(&mut self, background: Color) -> Result<(), SceneError> {
439        if !background.is_normalized() {
440            return Err(SceneError::InvalidBackground);
441        }
442        self.background = background;
443        Ok(())
444    }
445
446    /// Removes all draw commands and active clipping without changing the background color.
447    pub fn clear(&mut self) {
448        self.commands.clear();
449        self.owned_payload_bytes = 0;
450        self.next_order = 0;
451        self.current_screen_clip = None;
452        self.current_depth = 0.0;
453        self.statistics = SceneStatistics::default();
454    }
455
456    /// Returns accepted commands in stable layer and insertion order.
457    pub fn commands(&self) -> &[SceneCommand] {
458        &self.commands
459    }
460
461    /// Returns the number of accepted render commands.
462    pub fn command_count(&self) -> usize {
463        self.commands.len()
464    }
465
466    /// Returns CPU allocation bytes currently owned by command and polyline storage.
467    ///
468    /// Unlike [`SceneStatistics::retained_bytes`], which is the budgeted payload
469    /// of accepted commands, this includes spare `Vec` capacity retained for
470    /// reuse after insertion or [`Scene::clear`]. Allocator bookkeeping is not
471    /// included.
472    pub fn allocation_bytes(&self) -> usize {
473        self.commands
474            .capacity()
475            .saturating_mul(size_of::<SceneCommand>())
476            .saturating_add(self.owned_payload_bytes)
477    }
478
479    pub(crate) fn preflight_command_storage(
480        &self,
481        additional_commands: usize,
482        additional_owned_bytes: usize,
483    ) -> Result<(), SceneError> {
484        let Some(budget) = self.budget else {
485            return Ok(());
486        };
487        let retained_bytes = self
488            .statistics
489            .retained_bytes
490            .saturating_add(additional_commands.saturating_mul(size_of::<SceneCommand>()))
491            .saturating_add(additional_owned_bytes);
492        if retained_bytes > budget.max_retained_bytes {
493            return Err(SceneError::BudgetExceeded {
494                resource: SceneBudgetResource::RetainedBytes,
495                limit: budget.max_retained_bytes,
496                requested: retained_bytes,
497            });
498        }
499        let required_len = self.commands.len().saturating_add(additional_commands);
500        let owned_payload_bytes = self
501            .owned_payload_bytes
502            .saturating_add(additional_owned_bytes);
503        let capacity = if required_len <= self.commands.capacity() {
504            self.commands.capacity()
505        } else {
506            budgeted_command_capacity(
507                budget,
508                self.commands.capacity(),
509                required_len,
510                owned_payload_bytes,
511            )?
512        };
513        validate_scene_allocation_budget(budget, capacity, owned_payload_bytes)
514    }
515
516    /// Returns the explicit work budget, or `None` for an unbounded scene.
517    pub const fn budget(&self) -> Option<SceneBudget> {
518        self.budget
519    }
520
521    /// Returns requested, accepted, rejected, and estimated scene work.
522    pub const fn statistics(&self) -> SceneStatistics {
523        self.statistics
524    }
525
526    pub(crate) const fn current_screen_clip(&self) -> Option<ScreenClipRect> {
527        self.current_screen_clip
528    }
529
530    /// Replaces the screen-space clipping rectangle captured by new commands.
531    ///
532    /// The rectangle uses logical screen pixels with the origin at the top-left
533    /// of the render surface. Existing commands keep the clip they captured when
534    /// they were appended. `None` disables clipping for subsequent commands.
535    /// The previous clip is returned so callers can restore explicit drawing
536    /// state without tracking it separately. Invalid clips are rejected here,
537    /// before they can affect a later command insertion.
538    pub fn set_screen_clip(
539        &mut self,
540        screen_clip: Option<ScreenClipRect>,
541    ) -> Result<Option<ScreenClipRect>, SceneError> {
542        if screen_clip.is_some_and(|clip| !clip.is_valid()) {
543            return Err(SceneError::InvalidScreenClip);
544        }
545        Ok(std::mem::replace(
546            &mut self.current_screen_clip,
547            screen_clip,
548        ))
549    }
550
551    /// Appends commands from `draw` using a temporary screen-space clip.
552    ///
553    /// The rectangle uses logical screen pixels. Nested clips are intersected,
554    /// so inner drawing cannot escape an outer clip. The previous clip is
555    /// restored after `draw` returns.
556    pub fn with_screen_clip<R>(
557        &mut self,
558        screen_clip: ScreenClipRect,
559        draw: impl FnOnce(&mut Self) -> R,
560    ) -> Result<R, SceneError> {
561        if !screen_clip.is_valid() {
562            return Err(SceneError::InvalidScreenClip);
563        }
564        let previous = self.current_screen_clip;
565        let combined = match previous {
566            Some(outer) => outer.intersection(screen_clip)?,
567            None => screen_clip,
568        };
569        if !combined.is_valid() {
570            return Err(SceneError::InvalidScreenClip);
571        }
572        self.current_screen_clip = Some(combined);
573        let result = catch_unwind(AssertUnwindSafe(|| draw(self)));
574        self.current_screen_clip = previous;
575        match result {
576            Ok(result) => Ok(result),
577            Err(payload) => resume_unwind(payload),
578        }
579    }
580
581    /// Replaces the pseudo-depth captured by subsequently appended commands.
582    ///
583    /// Depth is measured in caller-defined units and converted through
584    /// [`crate::Projection2d::depth_scale`]. It affects projection only, not draw
585    /// order. Non-finite values return `false` and leave the current depth unchanged.
586    pub fn set_depth(&mut self, depth: f32) -> bool {
587        self.try_set_depth(depth).is_ok()
588    }
589
590    /// Replaces pseudo-depth and reports why invalid input was rejected.
591    pub fn try_set_depth(&mut self, depth: f32) -> Result<(), SceneError> {
592        if !depth.is_finite() {
593            return Err(SceneError::NonFiniteDepth);
594        }
595        self.current_depth = depth;
596        Ok(())
597    }
598
599    /// Appends commands with a temporary pseudo-depth value.
600    ///
601    /// The previous depth is restored after `draw` returns or unwinds. Non-finite
602    /// depth returns an error without calling `draw`.
603    pub fn with_depth<R>(
604        &mut self,
605        depth: f32,
606        draw: impl FnOnce(&mut Self) -> R,
607    ) -> Result<R, SceneError> {
608        if !depth.is_finite() {
609            return Err(SceneError::NonFiniteDepth);
610        }
611
612        let previous = self.current_depth;
613        self.current_depth = depth;
614        let result = catch_unwind(AssertUnwindSafe(|| draw(self)));
615        self.current_depth = previous;
616        match result {
617            Ok(result) => Ok(result),
618            Err(payload) => resume_unwind(payload),
619        }
620    }
621
622    /// Appends a valid command to the default layer.
623    ///
624    /// Returns `false` without changing commands, ordering, or retained
625    /// allocation when the primitive is invalid. Requested/rejected diagnostic
626    /// counters still advance for the attempted command.
627    pub fn push(&mut self, command: DrawCommand) -> bool {
628        self.try_push(command).is_ok()
629    }
630
631    /// Appends a command to the default layer with structured rejection diagnostics.
632    pub fn try_push(&mut self, command: DrawCommand) -> Result<(), SceneError> {
633        self.try_push_to_layer(Layer::DEFAULT, command)
634    }
635
636    /// Appends a command to a layer.
637    ///
638    /// Lower layer values are drawn first. Commands on the same layer preserve
639    /// insertion order.
640    /// Returns `false` without changing commands, ordering, or retained
641    /// allocation when `command` is invalid. Requested/rejected diagnostic
642    /// counters still advance for the attempted command.
643    pub fn push_to_layer(&mut self, layer: Layer, command: DrawCommand) -> bool {
644        self.try_push_to_layer(layer, command).is_ok()
645    }
646
647    /// Appends a command to a layer with structured rejection diagnostics.
648    ///
649    /// An incoming layer at or above the last layer appends without searching.
650    /// Out-of-order layers use stable insertion. Both paths perform the same
651    /// validation, budget checks, statistics updates, and capacity reuse.
652    pub fn try_push_to_layer(
653        &mut self,
654        layer: Layer,
655        command: DrawCommand,
656    ) -> Result<(), SceneError> {
657        self.try_push_to_layer_ordered::<true>(layer, command)
658    }
659
660    fn try_push_to_layer_ordered<const FAST_APPEND: bool>(
661        &mut self,
662        layer: Layer,
663        command: DrawCommand,
664    ) -> Result<(), SceneError> {
665        let primitive = command.primitive();
666        self.statistics.requested_commands = self.statistics.requested_commands.saturating_add(1);
667        self.statistics.requested_by_primitive.increment(primitive);
668        let result = self.try_push_to_layer_inner::<FAST_APPEND>(layer, command);
669        if result.is_err() {
670            self.statistics.rejected_commands = self.statistics.rejected_commands.saturating_add(1);
671            self.statistics.rejected_by_primitive.increment(primitive);
672        }
673        result
674    }
675
676    /// Atomically appends many commands and orders the combined scene once.
677    ///
678    /// This is the bounded high-volume construction path for adversarial or
679    /// frequently alternating layers. Validation and budget accounting happen
680    /// before the existing command list is changed. On failure, no command from
681    /// the batch is retained; request and rejection diagnostics still advance.
682    /// The resulting order is stable by layer and by batch insertion order.
683    pub fn try_extend_to_layers(
684        &mut self,
685        commands: impl IntoIterator<Item = (Layer, DrawCommand)>,
686    ) -> Result<(), SceneError> {
687        let mut staged = Vec::new();
688        let mut requested = self.statistics;
689        let mut attempted = 0usize;
690        let mut attempted_by_primitive = PrimitiveCommandCounts::default();
691        let mut next_order = self.next_order;
692        let existing_owned_payload_bytes = self.owned_payload_bytes;
693        let mut staged_owned_payload_bytes = 0usize;
694
695        for (layer, command) in commands {
696            let primitive = command.primitive();
697            attempted = attempted.saturating_add(1);
698            attempted_by_primitive.increment(primitive);
699            requested.requested_commands = requested.requested_commands.saturating_add(1);
700            requested.requested_by_primitive.increment(primitive);
701            if let Err(error) = command.validate() {
702                self.record_batch_rejection(attempted, attempted_by_primitive);
703                return Err(error);
704            }
705            if self
706                .current_screen_clip
707                .is_some_and(|screen_clip| !screen_clip.is_valid())
708            {
709                self.record_batch_rejection(attempted, attempted_by_primitive);
710                return Err(SceneError::InvalidScreenClip);
711            }
712
713            requested = requested.with_command(&command);
714            if let Some(budget) = self.budget
715                && let Err(error) = validate_scene_budget(budget, requested)
716            {
717                self.record_batch_rejection(attempted, attempted_by_primitive);
718                return Err(error);
719            }
720            let command_owned_payload_bytes = command.owned_allocation_bytes();
721            let prospective_owned_payload_bytes = existing_owned_payload_bytes
722                .saturating_add(staged_owned_payload_bytes)
723                .saturating_add(command_owned_payload_bytes);
724            if let Some(budget) = self.budget {
725                let required_total = self
726                    .commands
727                    .len()
728                    .saturating_add(staged.len())
729                    .saturating_add(1);
730                let final_capacity = if required_total <= self.commands.capacity() {
731                    self.commands.capacity()
732                } else {
733                    match budgeted_command_capacity(
734                        budget,
735                        self.commands.capacity(),
736                        required_total,
737                        prospective_owned_payload_bytes,
738                    ) {
739                        Ok(capacity) => capacity,
740                        Err(error) => {
741                            self.record_batch_rejection(attempted, attempted_by_primitive);
742                            return Err(error);
743                        }
744                    }
745                };
746                if let Err(error) = validate_scene_allocation_budget(
747                    budget,
748                    final_capacity,
749                    prospective_owned_payload_bytes,
750                ) {
751                    self.record_batch_rejection(attempted, attempted_by_primitive);
752                    return Err(error);
753                }
754
755                if staged.len() == staged.capacity() {
756                    let staging_capacity = match budgeted_command_capacity(
757                        budget,
758                        staged.capacity(),
759                        staged.len().saturating_add(1),
760                        prospective_owned_payload_bytes,
761                    ) {
762                        Ok(capacity) => capacity,
763                        Err(error) => {
764                            self.record_batch_rejection(attempted, attempted_by_primitive);
765                            return Err(error);
766                        }
767                    };
768                    let mut replacement = Vec::new();
769                    if replacement.try_reserve_exact(staging_capacity).is_err() {
770                        self.record_batch_rejection(attempted, attempted_by_primitive);
771                        return Err(SceneError::AllocationFailed {
772                            requested_bytes: scene_allocation_bytes(
773                                staging_capacity,
774                                prospective_owned_payload_bytes,
775                            ),
776                        });
777                    }
778                    if let Err(error) = validate_scene_allocation_budget(
779                        budget,
780                        replacement.capacity(),
781                        prospective_owned_payload_bytes,
782                    ) {
783                        self.record_batch_rejection(attempted, attempted_by_primitive);
784                        return Err(error);
785                    }
786                    replacement.append(&mut staged);
787                    staged = replacement;
788                } else if let Err(error) = validate_scene_allocation_budget(
789                    budget,
790                    staged.capacity(),
791                    prospective_owned_payload_bytes,
792                ) {
793                    self.record_batch_rejection(attempted, attempted_by_primitive);
794                    return Err(error);
795                }
796            } else if staged.try_reserve(1).is_err() {
797                self.record_batch_rejection(attempted, attempted_by_primitive);
798                return Err(SceneError::AllocationFailed {
799                    requested_bytes: command.retained_bytes(),
800                });
801            }
802            staged.push(SceneCommand {
803                layer,
804                order: next_order,
805                depth: self.current_depth,
806                screen_clip: self.current_screen_clip,
807                command,
808            });
809            staged_owned_payload_bytes =
810                staged_owned_payload_bytes.saturating_add(command_owned_payload_bytes);
811            next_order = next_order.saturating_add(1);
812        }
813
814        if staged.is_empty() {
815            return Ok(());
816        }
817        let total = self.commands.len().saturating_add(staged.len());
818        let owned_payload_bytes =
819            existing_owned_payload_bytes.saturating_add(staged_owned_payload_bytes);
820        let requested_capacity = if let Some(budget) = self.budget {
821            if total <= self.commands.capacity() {
822                self.commands.capacity()
823            } else {
824                match budgeted_command_capacity(
825                    budget,
826                    self.commands.capacity(),
827                    total,
828                    owned_payload_bytes,
829                ) {
830                    Ok(capacity) => capacity,
831                    Err(error) => {
832                        self.record_batch_rejection(attempted, attempted_by_primitive);
833                        return Err(error);
834                    }
835                }
836            }
837        } else {
838            total
839        };
840        if staged.capacity() < requested_capacity
841            && staged
842                .try_reserve_exact(requested_capacity.saturating_sub(staged.len()))
843                .is_err()
844        {
845            self.record_batch_rejection(attempted, attempted_by_primitive);
846            return Err(SceneError::AllocationFailed {
847                requested_bytes: scene_allocation_bytes(requested_capacity, owned_payload_bytes),
848            });
849        }
850        if let Some(budget) = self.budget
851            && let Err(error) =
852                validate_scene_allocation_budget(budget, staged.capacity(), owned_payload_bytes)
853        {
854            self.record_batch_rejection(attempted, attempted_by_primitive);
855            return Err(error);
856        }
857        staged.append(&mut self.commands);
858        staged.sort_unstable_by_key(|command| (command.layer, command.order));
859        self.commands = staged;
860        self.owned_payload_bytes = owned_payload_bytes;
861        self.next_order = next_order;
862        self.statistics = requested;
863        Ok(())
864    }
865
866    fn record_batch_rejection(
867        &mut self,
868        command_count: usize,
869        by_primitive: PrimitiveCommandCounts,
870    ) {
871        self.statistics.requested_commands = self
872            .statistics
873            .requested_commands
874            .saturating_add(command_count);
875        self.statistics.rejected_commands = self
876            .statistics
877            .rejected_commands
878            .saturating_add(command_count);
879        self.statistics.requested_by_primitive =
880            self.statistics.requested_by_primitive.adding(by_primitive);
881        self.statistics.rejected_by_primitive =
882            self.statistics.rejected_by_primitive.adding(by_primitive);
883    }
884
885    pub(crate) fn record_external_rejection(&mut self, primitive: ScenePrimitive) {
886        let mut counts = PrimitiveCommandCounts::default();
887        counts.increment(primitive);
888        self.record_batch_rejection(1, counts);
889    }
890
891    fn try_push_to_layer_inner<const FAST_APPEND: bool>(
892        &mut self,
893        layer: Layer,
894        command: DrawCommand,
895    ) -> Result<(), SceneError> {
896        command.validate()?;
897        if self
898            .current_screen_clip
899            .is_some_and(|screen_clip| !screen_clip.is_valid())
900        {
901            return Err(SceneError::InvalidScreenClip);
902        }
903
904        let command_retained_bytes = command.retained_bytes();
905        let owned_payload_bytes = self
906            .owned_payload_bytes
907            .saturating_add(command.owned_allocation_bytes());
908        let requested = self.statistics.with_command(&command);
909        if let Some(budget) = self.budget {
910            validate_scene_budget(budget, requested)?;
911        }
912
913        let replacement = if self.commands.len() == self.commands.capacity() {
914            if let Some(budget) = self.budget {
915                let required_len = self.commands.len().saturating_add(1);
916                let capacity = budgeted_command_capacity(
917                    budget,
918                    self.commands.capacity(),
919                    required_len,
920                    owned_payload_bytes,
921                )?;
922                let mut replacement = Vec::new();
923                replacement.try_reserve_exact(capacity).map_err(|_| {
924                    SceneError::AllocationFailed {
925                        requested_bytes: scene_allocation_bytes(capacity, owned_payload_bytes),
926                    }
927                })?;
928                validate_scene_allocation_budget(
929                    budget,
930                    replacement.capacity(),
931                    owned_payload_bytes,
932                )?;
933                Some(replacement)
934            } else {
935                self.commands
936                    .try_reserve(1)
937                    .map_err(|_| SceneError::AllocationFailed {
938                        requested_bytes: command_retained_bytes,
939                    })?;
940                None
941            }
942        } else {
943            if let Some(budget) = self.budget {
944                validate_scene_allocation_budget(
945                    budget,
946                    self.commands.capacity(),
947                    owned_payload_bytes,
948                )?;
949            }
950            None
951        };
952
953        if let Some(mut replacement) = replacement {
954            replacement.append(&mut self.commands);
955            self.commands = replacement;
956        }
957
958        let order = self.next_order;
959        let scene_command = SceneCommand {
960            layer,
961            order,
962            depth: self.current_depth,
963            screen_clip: self.current_screen_clip,
964            command,
965        };
966        if FAST_APPEND
967            && self
968                .commands
969                .last()
970                .is_none_or(|existing| existing.layer <= layer)
971        {
972            // Orders are monotonic even at saturation, so equal layers can
973            // append without disturbing stable painter order.
974            self.commands.push(scene_command);
975        } else {
976            let position = self.commands.partition_point(|existing| {
977                existing.layer < scene_command.layer
978                    || (existing.layer == scene_command.layer
979                        && existing.order <= scene_command.order)
980            });
981            self.commands.insert(position, scene_command);
982        }
983        self.owned_payload_bytes = owned_payload_bytes;
984        self.next_order = self.next_order.saturating_add(1);
985        self.statistics = requested;
986        Ok(())
987    }
988
989    /// Appends a circle in world coordinates.
990    ///
991    /// `radius` is in world units. Returns `false` for non-positive or non-finite
992    /// radius, non-finite center, or invalid style values.
993    pub fn circle(&mut self, center: Vec2, radius: f32, style: ShapeStyle) -> bool {
994        self.try_circle(center, radius, style).is_ok()
995    }
996
997    /// Appends a circle and returns a structured validation error on rejection.
998    pub fn try_circle(
999        &mut self,
1000        center: Vec2,
1001        radius: f32,
1002        style: ShapeStyle,
1003    ) -> Result<(), SceneError> {
1004        self.try_circle_on_layer(Layer::DEFAULT, center, radius, style)
1005    }
1006
1007    /// Appends a circle in world coordinates to a layer.
1008    ///
1009    /// `radius` is in world units. Returns `false` for non-positive or non-finite
1010    /// radius, non-finite center, or invalid style values.
1011    pub fn circle_on_layer(
1012        &mut self,
1013        layer: Layer,
1014        center: Vec2,
1015        radius: f32,
1016        style: ShapeStyle,
1017    ) -> bool {
1018        self.try_circle_on_layer(layer, center, radius, style)
1019            .is_ok()
1020    }
1021
1022    /// Appends a circle to a layer with structured rejection diagnostics.
1023    pub fn try_circle_on_layer(
1024        &mut self,
1025        layer: Layer,
1026        center: Vec2,
1027        radius: f32,
1028        style: ShapeStyle,
1029    ) -> Result<(), SceneError> {
1030        self.try_push_to_layer(
1031            layer,
1032            DrawCommand::Circle(Circle {
1033                center,
1034                radius,
1035                style,
1036            }),
1037        )
1038    }
1039
1040    /// Appends an axis-aligned rectangle in world coordinates.
1041    ///
1042    /// `corner_radius` is in world units and renderers clamp it to half the
1043    /// rectangle size. Invalid bounds, negative radius, and invalid styles return
1044    /// `false` without adding a command.
1045    pub fn rect(&mut self, rect: Rect, corner_radius: f32, style: ShapeStyle) -> bool {
1046        self.try_rect(rect, corner_radius, style).is_ok()
1047    }
1048
1049    /// Appends a rectangle and returns a structured validation error on rejection.
1050    pub fn try_rect(
1051        &mut self,
1052        rect: Rect,
1053        corner_radius: f32,
1054        style: ShapeStyle,
1055    ) -> Result<(), SceneError> {
1056        self.try_rect_on_layer(Layer::DEFAULT, rect, corner_radius, style)
1057    }
1058
1059    /// Appends an axis-aligned rectangle in world coordinates to a layer.
1060    ///
1061    /// `corner_radius` is in world units and renderers clamp it to half the
1062    /// rectangle size. Invalid bounds, negative radius, and invalid styles return
1063    /// `false` without adding a command.
1064    pub fn rect_on_layer(
1065        &mut self,
1066        layer: Layer,
1067        rect: Rect,
1068        corner_radius: f32,
1069        style: ShapeStyle,
1070    ) -> bool {
1071        self.try_rect_on_layer(layer, rect, corner_radius, style)
1072            .is_ok()
1073    }
1074
1075    /// Appends a rectangle to a layer with structured rejection diagnostics.
1076    pub fn try_rect_on_layer(
1077        &mut self,
1078        layer: Layer,
1079        rect: Rect,
1080        corner_radius: f32,
1081        style: ShapeStyle,
1082    ) -> Result<(), SceneError> {
1083        self.try_push_to_layer(
1084            layer,
1085            DrawCommand::Rect(RectShape {
1086                rect,
1087                corner_radius,
1088                style,
1089            }),
1090        )
1091    }
1092
1093    /// Appends a stroked line between world-space points.
1094    ///
1095    /// `width` is in logical screen pixels so line thickness stays readable while the
1096    /// camera zooms. Degenerate geometry and invalid width or color return
1097    /// `false`.
1098    pub fn line(&mut self, from: Vec2, to: Vec2, width: f32, color: Color) -> bool {
1099        self.try_line(from, to, width, color).is_ok()
1100    }
1101
1102    /// Appends a line and returns a structured validation error on rejection.
1103    pub fn try_line(
1104        &mut self,
1105        from: Vec2,
1106        to: Vec2,
1107        width: f32,
1108        color: Color,
1109    ) -> Result<(), SceneError> {
1110        self.try_styled_line(from, to, StrokeStyle2d::new(width, color))
1111    }
1112
1113    /// Appends a stroked line between world-space points to a layer.
1114    ///
1115    /// `width` is in logical screen pixels so line thickness stays readable while the
1116    /// camera zooms. Degenerate geometry and invalid width or color return
1117    /// `false`.
1118    pub fn line_on_layer(
1119        &mut self,
1120        layer: Layer,
1121        from: Vec2,
1122        to: Vec2,
1123        width: f32,
1124        color: Color,
1125    ) -> bool {
1126        self.try_line_on_layer(layer, from, to, width, color)
1127            .is_ok()
1128    }
1129
1130    /// Appends a line to a layer with structured rejection diagnostics.
1131    pub fn try_line_on_layer(
1132        &mut self,
1133        layer: Layer,
1134        from: Vec2,
1135        to: Vec2,
1136        width: f32,
1137        color: Color,
1138    ) -> Result<(), SceneError> {
1139        self.try_styled_line_on_layer(layer, from, to, StrokeStyle2d::new(width, color))
1140    }
1141
1142    /// Appends a line with explicit width units, caps, joins, dashes, and markers.
1143    pub fn styled_line(&mut self, from: Vec2, to: Vec2, style: StrokeStyle2d) -> bool {
1144        self.try_styled_line(from, to, style).is_ok()
1145    }
1146
1147    /// Appends an explicitly styled line with structured rejection diagnostics.
1148    pub fn try_styled_line(
1149        &mut self,
1150        from: Vec2,
1151        to: Vec2,
1152        style: StrokeStyle2d,
1153    ) -> Result<(), SceneError> {
1154        self.try_styled_line_on_layer(Layer::DEFAULT, from, to, style)
1155    }
1156
1157    /// Appends an explicitly styled line to a shared draw layer.
1158    pub fn styled_line_on_layer(
1159        &mut self,
1160        layer: Layer,
1161        from: Vec2,
1162        to: Vec2,
1163        style: StrokeStyle2d,
1164    ) -> bool {
1165        self.try_styled_line_on_layer(layer, from, to, style)
1166            .is_ok()
1167    }
1168
1169    /// Appends an explicitly styled line to a layer with structured rejection.
1170    pub fn try_styled_line_on_layer(
1171        &mut self,
1172        layer: Layer,
1173        from: Vec2,
1174        to: Vec2,
1175        style: StrokeStyle2d,
1176    ) -> Result<(), SceneError> {
1177        self.try_push_to_layer(layer, DrawCommand::Line(Line { from, to, style }))
1178    }
1179
1180    /// Appends connected stroked segments through world-space points.
1181    ///
1182    /// `width` is in logical screen pixels. Empty, single-point, non-finite,
1183    /// repeated-adjacent, or numerically ambiguous turn input returns `false`
1184    /// without adding a command; every consecutive segment must be drawable.
1185    pub fn polyline(&mut self, points: Vec<Vec2>, width: f32, color: Color) -> bool {
1186        self.try_polyline(points, width, color).is_ok()
1187    }
1188
1189    /// Appends a polyline and returns a structured validation error on rejection.
1190    pub fn try_polyline(
1191        &mut self,
1192        points: Vec<Vec2>,
1193        width: f32,
1194        color: Color,
1195    ) -> Result<(), SceneError> {
1196        self.try_styled_polyline(points, StrokeStyle2d::new(width, color))
1197    }
1198
1199    /// Appends connected stroked segments through world-space points to a layer.
1200    ///
1201    /// `width` is in logical screen pixels. Empty, single-point, non-finite,
1202    /// repeated-adjacent, or numerically ambiguous turn input returns `false`
1203    /// without adding a command; every consecutive segment must be drawable.
1204    pub fn polyline_on_layer(
1205        &mut self,
1206        layer: Layer,
1207        points: Vec<Vec2>,
1208        width: f32,
1209        color: Color,
1210    ) -> bool {
1211        self.try_polyline_on_layer(layer, points, width, color)
1212            .is_ok()
1213    }
1214
1215    /// Appends a polyline to a layer with structured rejection diagnostics.
1216    pub fn try_polyline_on_layer(
1217        &mut self,
1218        layer: Layer,
1219        points: Vec<Vec2>,
1220        width: f32,
1221        color: Color,
1222    ) -> Result<(), SceneError> {
1223        self.try_styled_polyline_on_layer(layer, points, StrokeStyle2d::new(width, color))
1224    }
1225
1226    /// Appends a connected path with explicit width, caps, joins, dashes, and markers.
1227    pub fn styled_polyline(&mut self, points: Vec<Vec2>, style: StrokeStyle2d) -> bool {
1228        self.try_styled_polyline(points, style).is_ok()
1229    }
1230
1231    /// Appends an explicitly styled path with structured rejection diagnostics.
1232    pub fn try_styled_polyline(
1233        &mut self,
1234        points: Vec<Vec2>,
1235        style: StrokeStyle2d,
1236    ) -> Result<(), SceneError> {
1237        self.try_styled_polyline_on_layer(Layer::DEFAULT, points, style)
1238    }
1239
1240    /// Appends an explicitly styled path to a shared draw layer.
1241    pub fn styled_polyline_on_layer(
1242        &mut self,
1243        layer: Layer,
1244        points: Vec<Vec2>,
1245        style: StrokeStyle2d,
1246    ) -> bool {
1247        self.try_styled_polyline_on_layer(layer, points, style)
1248            .is_ok()
1249    }
1250
1251    /// Appends an explicitly styled path to a layer with structured rejection.
1252    pub fn try_styled_polyline_on_layer(
1253        &mut self,
1254        layer: Layer,
1255        points: Vec<Vec2>,
1256        style: StrokeStyle2d,
1257    ) -> Result<(), SceneError> {
1258        self.try_push_to_layer(layer, DrawCommand::Polyline(Polyline { points, style }))
1259    }
1260}
1261
1262/// Draw layer used to order scene commands.
1263///
1264/// Lower values are drawn first. Higher values appear above lower layers.
1265#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
1266pub struct Layer {
1267    order: i32,
1268}
1269
1270impl Layer {
1271    /// Default layer used by convenience drawing methods.
1272    pub const DEFAULT: Self = Self::new(0);
1273    /// Conventional layer for background guides or grids.
1274    pub const BACKGROUND: Self = Self::new(-100);
1275    /// Conventional layer for foreground annotations or overlays.
1276    pub const FOREGROUND: Self = Self::new(100);
1277
1278    /// Builds a layer from an order value.
1279    pub const fn new(order: i32) -> Self {
1280        Self { order }
1281    }
1282
1283    /// Returns the order value used for sorting.
1284    pub const fn order(self) -> i32 {
1285        self.order
1286    }
1287}
1288
1289/// Axis-aligned clipping rectangle in logical screen pixels.
1290///
1291/// The coordinate origin is the top-left of the render surface and positive y
1292/// points downward. Constructors reject empty and non-finite bounds.
1293/// Renderers clamp valid clips to the target viewport.
1294#[derive(Debug, Clone, Copy, PartialEq)]
1295pub struct ScreenClipRect {
1296    rect: Rect,
1297}
1298
1299impl ScreenClipRect {
1300    /// Builds a non-empty clip from two corners in logical screen pixels.
1301    pub fn new(min: LogicalScreenPosition, max: LogicalScreenPosition) -> Result<Self, SceneError> {
1302        Self::from_rect(Rect::new(min.to_vec2(), max.to_vec2()))
1303    }
1304
1305    /// Builds a clip from its top-left corner and size in logical screen pixels.
1306    ///
1307    /// Negative size components are accepted and normalized before validation.
1308    pub fn from_min_size(
1309        min: LogicalScreenPosition,
1310        size: LogicalScreenVector,
1311    ) -> Result<Self, SceneError> {
1312        Self::from_rect(Rect::from_min_size(min.to_vec2(), size.to_vec2()))
1313    }
1314
1315    fn from_rect(rect: Rect) -> Result<Self, SceneError> {
1316        let clip = Self { rect };
1317        clip.is_valid()
1318            .then_some(clip)
1319            .ok_or(SceneError::InvalidScreenClip)
1320    }
1321
1322    #[cfg(feature = "wgpu")]
1323    pub(crate) fn rect(self) -> Rect {
1324        self.rect
1325    }
1326
1327    /// Returns the normalized top-left corner in logical screen pixels.
1328    pub fn min(self) -> LogicalScreenPosition {
1329        LogicalScreenPosition::from_vec2(self.rect.normalized().min)
1330    }
1331
1332    /// Returns the normalized bottom-right corner in logical screen pixels.
1333    pub fn max(self) -> LogicalScreenPosition {
1334        LogicalScreenPosition::from_vec2(self.rect.normalized().max)
1335    }
1336
1337    /// Returns the overlap between two screen-space clips.
1338    ///
1339    /// Disjoint inputs return [`SceneError::InvalidScreenClip`].
1340    pub fn intersection(self, other: Self) -> Result<Self, SceneError> {
1341        let first = self.rect.normalized();
1342        let second = other.rect.normalized();
1343        let min = Vec2::new(first.min.x.max(second.min.x), first.min.y.max(second.min.y));
1344        let max = Vec2::new(first.max.x.min(second.max.x), first.max.y.min(second.max.y));
1345
1346        Self::new(
1347            LogicalScreenPosition::from_vec2(min),
1348            LogicalScreenPosition::from_vec2(Vec2::new(max.x.max(min.x), max.y.max(min.y))),
1349        )
1350    }
1351
1352    fn is_valid(self) -> bool {
1353        if !self.rect.min.is_finite() || !self.rect.max.is_finite() {
1354            return false;
1355        }
1356
1357        let rect = self.rect.normalized();
1358        rect.width() > 0.0 && rect.height() > 0.0
1359    }
1360}
1361
1362/// Draw command with layer and stable insertion order metadata.
1363#[derive(Debug, Clone)]
1364pub struct SceneCommand {
1365    /// Layer used to sort commands before rendering.
1366    layer: Layer,
1367    /// Monotonic insertion order within the scene.
1368    order: u64,
1369    /// Caller-defined pseudo-depth used by camera projection.
1370    depth: f32,
1371    /// Optional clipping rectangle in logical screen pixels.
1372    screen_clip: Option<ScreenClipRect>,
1373    /// Visual primitive to render.
1374    command: DrawCommand,
1375}
1376
1377impl SceneCommand {
1378    /// Returns the layer used for stable scene ordering.
1379    pub fn layer(&self) -> Layer {
1380        self.layer
1381    }
1382
1383    /// Returns the insertion order assigned by the scene.
1384    pub fn order(&self) -> u64 {
1385        self.order
1386    }
1387
1388    /// Returns caller-defined pseudo-depth captured by this command.
1389    ///
1390    /// Depth affects camera projection only. Commands on one layer retain their
1391    /// insertion order regardless of depth.
1392    pub fn depth(&self) -> f32 {
1393        self.depth
1394    }
1395
1396    /// Returns the optional clip captured when the command was appended.
1397    pub fn screen_clip(&self) -> Option<ScreenClipRect> {
1398        self.screen_clip
1399    }
1400
1401    /// Returns the visual primitive stored by this command.
1402    pub fn command(&self) -> &DrawCommand {
1403        &self.command
1404    }
1405}
1406
1407/// Renderable primitive command.
1408#[derive(Debug, Clone)]
1409#[non_exhaustive]
1410pub enum DrawCommand {
1411    /// Filled and/or stroked circle.
1412    Circle(Circle),
1413    /// Filled and/or stroked rectangle.
1414    Rect(RectShape),
1415    /// Single stroked segment.
1416    Line(Line),
1417    /// Connected stroked segments.
1418    Polyline(Polyline),
1419}
1420
1421impl DrawCommand {
1422    /// Returns the primitive category used by diagnostics and budgets.
1423    pub const fn primitive(&self) -> ScenePrimitive {
1424        match self {
1425            Self::Circle(_) => ScenePrimitive::Circle,
1426            Self::Rect(_) => ScenePrimitive::Rect,
1427            Self::Line(_) => ScenePrimitive::Line,
1428            Self::Polyline(_) => ScenePrimitive::Polyline,
1429        }
1430    }
1431
1432    /// Builds and validates a circle command for batch insertion.
1433    pub fn circle(center: Vec2, radius: f32, style: ShapeStyle) -> Result<Self, SceneError> {
1434        let command = Self::Circle(Circle {
1435            center,
1436            radius,
1437            style,
1438        });
1439        command.validate()?;
1440        Ok(command)
1441    }
1442
1443    /// Builds and validates a rectangle command for batch insertion.
1444    pub fn rect(rect: Rect, corner_radius: f32, style: ShapeStyle) -> Result<Self, SceneError> {
1445        let command = Self::Rect(RectShape {
1446            rect,
1447            corner_radius,
1448            style,
1449        });
1450        command.validate()?;
1451        Ok(command)
1452    }
1453
1454    /// Builds and validates a single line command for batch insertion.
1455    pub fn line(from: Vec2, to: Vec2, width: f32, color: Color) -> Result<Self, SceneError> {
1456        Self::styled_line(from, to, StrokeStyle2d::new(width, color))
1457    }
1458
1459    /// Builds and validates an explicitly styled line command.
1460    pub fn styled_line(from: Vec2, to: Vec2, style: StrokeStyle2d) -> Result<Self, SceneError> {
1461        let command = Self::Line(Line { from, to, style });
1462        command.validate()?;
1463        Ok(command)
1464    }
1465
1466    /// Builds and validates a connected polyline command for batch insertion.
1467    pub fn polyline(points: Vec<Vec2>, width: f32, color: Color) -> Result<Self, SceneError> {
1468        Self::styled_polyline(points, StrokeStyle2d::new(width, color))
1469    }
1470
1471    /// Builds and validates an explicitly styled polyline command.
1472    pub fn styled_polyline(points: Vec<Vec2>, style: StrokeStyle2d) -> Result<Self, SceneError> {
1473        let command = Self::Polyline(Polyline { points, style });
1474        command.validate()?;
1475        Ok(command)
1476    }
1477
1478    fn validate(&self) -> Result<(), SceneError> {
1479        match self {
1480            Self::Circle(circle) => {
1481                if !circle.center.is_finite() {
1482                    return Err(SceneError::NonFiniteGeometry(ScenePrimitive::Circle));
1483                }
1484                if !circle.radius.is_finite() || circle.radius <= 0.0 {
1485                    return Err(SceneError::InvalidDimension(ScenePrimitive::Circle));
1486                }
1487                if !(circle.center + Vec2::splat(circle.radius)).is_finite()
1488                    || !(circle.center - Vec2::splat(circle.radius)).is_finite()
1489                {
1490                    return Err(SceneError::NonFiniteGeometry(ScenePrimitive::Circle));
1491                }
1492                circle.style.validate(ScenePrimitive::Circle)
1493            }
1494            Self::Rect(rectangle) => {
1495                let rect = rectangle.rect.normalized();
1496                if !rect.min.is_finite() || !rect.max.is_finite() {
1497                    return Err(SceneError::NonFiniteGeometry(ScenePrimitive::Rect));
1498                }
1499                let width = rect.width();
1500                let height = rect.height();
1501                if !width.is_finite() || !height.is_finite() {
1502                    return Err(SceneError::NonFiniteGeometry(ScenePrimitive::Rect));
1503                }
1504                if width <= 0.0
1505                    || height <= 0.0
1506                    || !rectangle.corner_radius.is_finite()
1507                    || rectangle.corner_radius < 0.0
1508                {
1509                    return Err(SceneError::InvalidDimension(ScenePrimitive::Rect));
1510                }
1511                rectangle.style.validate(ScenePrimitive::Rect)
1512            }
1513            Self::Line(line) => {
1514                if !line.from.is_finite() || !line.to.is_finite() {
1515                    return Err(SceneError::NonFiniteGeometry(ScenePrimitive::Line));
1516                }
1517                if !(line.to - line.from).is_finite() {
1518                    return Err(SceneError::NonFiniteGeometry(ScenePrimitive::Line));
1519                }
1520                if !drawable_segment(line.from, line.to) {
1521                    return Err(SceneError::DegenerateGeometry(ScenePrimitive::Line));
1522                }
1523                if !line.style.is_valid() {
1524                    return Err(SceneError::InvalidStroke(ScenePrimitive::Line));
1525                }
1526                validate_stroke_path(&[line.from, line.to], line.style, ScenePrimitive::Line)?;
1527                Ok(())
1528            }
1529            Self::Polyline(polyline) => {
1530                validate_styled_polyline(polyline.points.iter().copied(), polyline.style)?;
1531                Ok(())
1532            }
1533        }
1534    }
1535
1536    fn retained_point_count(&self) -> usize {
1537        match self {
1538            Self::Polyline(polyline) => polyline.points.len(),
1539            Self::Circle(_) | Self::Rect(_) | Self::Line(_) => 0,
1540        }
1541    }
1542
1543    fn retained_bytes(&self) -> usize {
1544        size_of::<SceneCommand>().saturating_add(self.owned_allocation_bytes())
1545    }
1546
1547    fn owned_allocation_bytes(&self) -> usize {
1548        match self {
1549            Self::Polyline(polyline) => {
1550                polyline.points.capacity().saturating_mul(size_of::<Vec2>())
1551            }
1552            Self::Circle(_) | Self::Rect(_) | Self::Line(_) => 0,
1553        }
1554    }
1555
1556    fn estimated_tessellated_vertices(&self) -> usize {
1557        match self {
1558            Self::Circle(circle) => {
1559                let fill_vertices = CIRCLE_SEGMENTS * 3;
1560                let stroke_vertices = CIRCLE_SEGMENTS * 6;
1561                let style = circle.style;
1562                usize::from(style.fill.is_some()) * fill_vertices
1563                    + usize::from(style.stroke.is_some()) * stroke_vertices
1564                    + style.shadow.map_or(0, |shadow| {
1565                        fill_vertices + usize::from(shadow.spread > 0.0) * stroke_vertices
1566                    })
1567            }
1568            Self::Rect(rectangle) => {
1569                let rect = rectangle.rect.normalized();
1570                let radius = rectangle
1571                    .corner_radius
1572                    .max(0.0)
1573                    .min(rect.width().abs() * 0.5)
1574                    .min(rect.height().abs() * 0.5);
1575                let boundary_segments = if radius <= 0.0 {
1576                    4
1577                } else {
1578                    4 * (CORNER_SEGMENTS + 1)
1579                };
1580                let fill_vertices = boundary_segments * 3;
1581                let stroke_vertices = boundary_segments * 6;
1582                let style = rectangle.style;
1583                usize::from(style.fill.is_some()) * fill_vertices
1584                    + usize::from(style.stroke.is_some()) * stroke_vertices
1585                    + style.shadow.map_or(0, |shadow| {
1586                        fill_vertices + usize::from(shadow.spread > 0.0) * stroke_vertices
1587                    })
1588            }
1589            Self::Line(line) => estimate_stroke_vertices(&[line.from, line.to], line.style),
1590            Self::Polyline(polyline) => estimate_stroke_vertices(&polyline.points, polyline.style),
1591        }
1592    }
1593}
1594
1595fn validate_stroke_path(
1596    points: &[Vec2],
1597    style: StrokeStyle2d,
1598    primitive: ScenePrimitive,
1599) -> Result<(), SceneError> {
1600    validate_stroke_path_iter(points.iter().copied(), style, primitive)
1601}
1602
1603fn validate_stroke_path_iter<I>(
1604    points: I,
1605    style: StrokeStyle2d,
1606    primitive: ScenePrimitive,
1607) -> Result<(), SceneError>
1608where
1609    I: Iterator<Item = Vec2> + Clone,
1610{
1611    if style.has_tip_marker() && (style.dash.is_some() || points.clone().count() != 2) {
1612        return Err(SceneError::UnsupportedTipMarkerPath(primitive));
1613    }
1614    let maximum_offset = f64::from(style.stroke.width) * 0.5 * f64::from(style.miter_limit);
1615    if !maximum_offset.is_finite() || maximum_offset > f64::from(f32::MAX) {
1616        return Err(SceneError::InvalidStroke(primitive));
1617    }
1618    if style.width_mode == StrokeWidthMode2d::WorldUnits {
1619        let extent = Vec2::splat(maximum_offset as f32);
1620        if points
1621            .clone()
1622            .any(|point| !(point + extent).is_finite() || !(point - extent).is_finite())
1623        {
1624            return Err(SceneError::NonFiniteGeometry(primitive));
1625        }
1626    }
1627    if let Some(dash) = style.dash {
1628        let required = dash_subsegment_count_iter(points, dash, Some(dash.max_subsegments))
1629            .ok_or(SceneError::UnrepresentableStrokePattern(primitive))?;
1630        if required > dash.max_subsegments {
1631            return Err(SceneError::StrokeExpansionLimitExceeded {
1632                primitive,
1633                limit: dash.max_subsegments,
1634                required,
1635            });
1636        }
1637    }
1638    Ok(())
1639}
1640
1641/// Validates caller-owned polyline coordinates without allocating or copying them.
1642///
1643/// Screen-space adapters use this before reserving their converted point buffer,
1644/// so an invalid leading point or segment cannot force work proportional to the
1645/// rest of a caller-sized slice.
1646pub(crate) fn validate_polyline_geometry<I>(points: I) -> Result<(), SceneError>
1647where
1648    I: Iterator<Item = Vec2> + Clone,
1649{
1650    let primitive = ScenePrimitive::Polyline;
1651    if !points.clone().all(|point| point.is_finite()) {
1652        return Err(SceneError::NonFiniteGeometry(primitive));
1653    }
1654
1655    let mut deltas = points.clone();
1656    let Some(mut previous) = deltas.next() else {
1657        return Err(SceneError::DegenerateGeometry(primitive));
1658    };
1659    let mut segment_count = 0usize;
1660    for point in deltas {
1661        let delta = point - previous;
1662        if !delta.is_finite() {
1663            return Err(SceneError::NonFiniteGeometry(primitive));
1664        }
1665        previous = point;
1666        segment_count = segment_count.saturating_add(1);
1667    }
1668    if segment_count == 0 {
1669        return Err(SceneError::DegenerateGeometry(primitive));
1670    }
1671
1672    let mut segments = points.clone();
1673    let mut previous = segments
1674        .next()
1675        .expect("a non-empty path was established above");
1676    for point in segments {
1677        if !drawable_segment(previous, point) {
1678            return Err(SceneError::DegenerateGeometry(primitive));
1679        }
1680        previous = point;
1681    }
1682
1683    let mut turns = points;
1684    let mut first = turns
1685        .next()
1686        .expect("a drawable segment was established above");
1687    let mut second = turns
1688        .next()
1689        .expect("a drawable segment was established above");
1690    for (index, third) in turns.enumerate() {
1691        let incoming = second - first;
1692        let outgoing = third - second;
1693        let cross = f64::from(incoming.x) * f64::from(outgoing.y)
1694            - f64::from(incoming.y) * f64::from(outgoing.x);
1695        let dot = f64::from(incoming.x) * f64::from(outgoing.x)
1696            + f64::from(incoming.y) * f64::from(outgoing.y);
1697        let direction_product = f64::from(incoming.x).hypot(f64::from(incoming.y))
1698            * f64::from(outgoing.x).hypot(f64::from(outgoing.y));
1699        let normalized_cross = cross / direction_product;
1700        if normalized_cross.abs() <= MIN_STROKE_TURN_SINE && (dot < 0.0 || normalized_cross != 0.0)
1701        {
1702            return Err(SceneError::DegenerateStrokeTurn {
1703                primitive,
1704                vertex_index: index + 1,
1705            });
1706        }
1707        first = second;
1708        second = third;
1709    }
1710    Ok(())
1711}
1712
1713/// Validates a complete styled polyline without taking ownership of its points.
1714pub(crate) fn validate_styled_polyline<I>(points: I, style: StrokeStyle2d) -> Result<(), SceneError>
1715where
1716    I: Iterator<Item = Vec2> + Clone,
1717{
1718    validate_polyline_geometry(points.clone())?;
1719    if !style.is_valid() {
1720        return Err(SceneError::InvalidStroke(ScenePrimitive::Polyline));
1721    }
1722    validate_stroke_path_iter(points, style, ScenePrimitive::Polyline)
1723}
1724
1725fn estimate_stroke_vertices(points: &[Vec2], style: StrokeStyle2d) -> usize {
1726    let segment_count = points
1727        .windows(2)
1728        .filter(|pair| drawable_segment(pair[0], pair[1]))
1729        .count();
1730    if segment_count == 0 {
1731        return 0;
1732    }
1733    let body_count = style.dash.map_or(segment_count, |dash| {
1734        dash_subsegment_count(points, dash, None)
1735            .expect("accepted dash paths have representable subsegments")
1736    });
1737    // A visible dash may continue across every geometric vertex. Counting all
1738    // possible joins is conservative without expanding the pattern twice.
1739    let join_count = segment_count.saturating_sub(1);
1740    let cap_count = if style.dash.is_some() {
1741        body_count.saturating_mul(2)
1742    } else {
1743        2
1744    };
1745    let cap_vertices = match style.cap {
1746        StrokeCap2d::Round => cap_count.saturating_mul(ROUND_CAP_SEGMENTS * 3),
1747        StrokeCap2d::Butt | StrokeCap2d::Square => 0,
1748    };
1749    let join_vertices = match style.join {
1750        StrokeJoin2d::Bevel => join_count.saturating_mul(6),
1751        StrokeJoin2d::Miter => join_count.saturating_mul(12),
1752        // Logical round joins carry one candidate fan for each possible screen
1753        // orientation; the shader collapses the inactive fan to zero area.
1754        StrokeJoin2d::Round if style.width_mode == StrokeWidthMode2d::LogicalPixels => {
1755            join_count.saturating_mul(ROUND_CAP_SEGMENTS * 6)
1756        }
1757        StrokeJoin2d::Round => join_count.saturating_mul(ROUND_CAP_SEGMENTS * 3),
1758    };
1759    let marker_vertices = (usize::from(style.start_marker.is_some())
1760        + usize::from(style.end_marker.is_some()))
1761    .saturating_mul(3);
1762    body_count
1763        .saturating_mul(6)
1764        .saturating_add(cap_vertices)
1765        .saturating_add(join_vertices)
1766        .saturating_add(marker_vertices)
1767}
1768
1769fn dash_subsegment_count(
1770    points: &[Vec2],
1771    dash: StrokeDashPattern2d,
1772    stop_after: Option<usize>,
1773) -> Option<usize> {
1774    dash_subsegment_count_iter(points.iter().copied(), dash, stop_after)
1775}
1776
1777fn dash_subsegment_count_iter<I>(
1778    points: I,
1779    dash: StrokeDashPattern2d,
1780    stop_after: Option<usize>,
1781) -> Option<usize>
1782where
1783    I: Iterator<Item = Vec2>,
1784{
1785    let lengths = dash.lengths();
1786    let total: f64 = lengths.iter().map(|length| f64::from(*length)).sum();
1787    let mut phase = f64::from(dash.phase).rem_euclid(total);
1788    let mut pattern_index = 0usize;
1789    while phase >= f64::from(lengths[pattern_index]) {
1790        phase -= f64::from(lengths[pattern_index]);
1791        pattern_index = (pattern_index + 1) % lengths.len();
1792    }
1793    let mut pattern_remaining = f64::from(lengths[pattern_index]) - phase;
1794    let mut count = 0usize;
1795
1796    let mut points = points;
1797    let mut previous = points.next()?;
1798    for point in points {
1799        let delta = point - previous;
1800        let segment_length = f64::from(delta.x).hypot(f64::from(delta.y));
1801        let mut segment_remaining = segment_length;
1802        while segment_remaining > 0.0 {
1803            let consumed = segment_remaining.min(pattern_remaining);
1804            if pattern_index.is_multiple_of(2) && consumed > 0.0 {
1805                count = count.saturating_add(1);
1806                if stop_after.is_some_and(|limit| count > limit) {
1807                    return Some(count);
1808                }
1809            }
1810            let next_remaining = segment_remaining - consumed;
1811            if next_remaining >= segment_remaining {
1812                return None;
1813            }
1814            let amount_start = 1.0 - segment_remaining / segment_length;
1815            let amount_end = 1.0 - next_remaining / segment_length;
1816            if dash_segment_point(previous, point, amount_start)
1817                == dash_segment_point(previous, point, amount_end)
1818            {
1819                return None;
1820            }
1821            segment_remaining = next_remaining;
1822            pattern_remaining -= consumed;
1823            if pattern_remaining <= 0.0 {
1824                pattern_index = (pattern_index + 1) % lengths.len();
1825                pattern_remaining = f64::from(lengths[pattern_index]);
1826            }
1827        }
1828        previous = point;
1829    }
1830    Some(count)
1831}
1832
1833fn dash_segment_point(from: Vec2, to: Vec2, amount: f64) -> Vec2 {
1834    Vec2::new(
1835        (f64::from(from.x) * (1.0 - amount) + f64::from(to.x) * amount) as f32,
1836        (f64::from(from.y) * (1.0 - amount) + f64::from(to.y) * amount) as f32,
1837    )
1838}
1839
1840fn validate_scene_budget(
1841    budget: SceneBudget,
1842    requested: SceneStatistics,
1843) -> Result<(), SceneError> {
1844    let limits = [
1845        (
1846            SceneBudgetResource::Commands,
1847            budget.max_commands,
1848            requested.accepted_commands,
1849        ),
1850        (
1851            SceneBudgetResource::Points,
1852            budget.max_points,
1853            requested.retained_points,
1854        ),
1855        (
1856            SceneBudgetResource::TessellatedVertices,
1857            budget.max_tessellated_vertices,
1858            requested.estimated_tessellated_vertices,
1859        ),
1860        (
1861            SceneBudgetResource::RetainedBytes,
1862            budget.max_retained_bytes,
1863            requested.retained_bytes,
1864        ),
1865        // Actual allocation capacity is validated transactionally at the
1866        // insertion boundary, once the prospective Vec capacity is known.
1867        (
1868            SceneBudgetResource::UploadBytes,
1869            budget.max_upload_bytes,
1870            requested.estimated_upload_bytes,
1871        ),
1872        (
1873            SceneBudgetResource::DrawBatches,
1874            budget.max_draw_batches,
1875            requested.estimated_draw_batches,
1876        ),
1877    ];
1878    for (resource, limit, requested) in limits {
1879        if requested > limit {
1880            return Err(SceneError::BudgetExceeded {
1881                resource,
1882                limit,
1883                requested,
1884            });
1885        }
1886    }
1887    Ok(())
1888}
1889
1890fn scene_allocation_bytes(command_capacity: usize, owned_payload_bytes: usize) -> usize {
1891    command_capacity
1892        .saturating_mul(size_of::<SceneCommand>())
1893        .saturating_add(owned_payload_bytes)
1894}
1895
1896fn validate_scene_allocation_budget(
1897    budget: SceneBudget,
1898    command_capacity: usize,
1899    owned_payload_bytes: usize,
1900) -> Result<(), SceneError> {
1901    let requested = scene_allocation_bytes(command_capacity, owned_payload_bytes);
1902    if requested > budget.max_allocation_bytes {
1903        return Err(SceneError::BudgetExceeded {
1904            resource: SceneBudgetResource::AllocationBytes,
1905            limit: budget.max_allocation_bytes,
1906            requested,
1907        });
1908    }
1909    Ok(())
1910}
1911
1912fn budgeted_command_capacity(
1913    budget: SceneBudget,
1914    current_capacity: usize,
1915    required_len: usize,
1916    owned_payload_bytes: usize,
1917) -> Result<usize, SceneError> {
1918    let available = budget
1919        .max_allocation_bytes
1920        .saturating_sub(owned_payload_bytes);
1921    let maximum_capacity = available / size_of::<SceneCommand>();
1922    if required_len > maximum_capacity {
1923        return Err(SceneError::BudgetExceeded {
1924            resource: SceneBudgetResource::AllocationBytes,
1925            limit: budget.max_allocation_bytes,
1926            requested: scene_allocation_bytes(required_len, owned_payload_bytes),
1927        });
1928    }
1929    Ok(current_capacity
1930        .max(1)
1931        .saturating_mul(2)
1932        .max(required_len)
1933        .min(maximum_capacity))
1934}
1935
1936fn drawable_segment(from: Vec2, to: Vec2) -> bool {
1937    let delta = to - from;
1938    delta.is_finite() && (delta.x != 0.0 || delta.y != 0.0)
1939}
1940
1941/// Circle primitive in world coordinates.
1942#[derive(Debug, Clone)]
1943pub struct Circle {
1944    center: Vec2,
1945    radius: f32,
1946    style: ShapeStyle,
1947}
1948
1949impl Circle {
1950    /// Returns the center in world coordinates.
1951    pub const fn center(&self) -> Vec2 {
1952        self.center
1953    }
1954    /// Returns the radius in world units.
1955    pub const fn radius(&self) -> f32 {
1956        self.radius
1957    }
1958    /// Returns fill, stroke, and shadow styling.
1959    pub const fn style(&self) -> ShapeStyle {
1960        self.style
1961    }
1962}
1963
1964/// Axis-aligned rectangle primitive in world coordinates.
1965#[derive(Debug, Clone)]
1966pub struct RectShape {
1967    rect: Rect,
1968    corner_radius: f32,
1969    style: ShapeStyle,
1970}
1971
1972impl RectShape {
1973    /// Returns rectangle bounds in world coordinates.
1974    pub const fn rect(&self) -> Rect {
1975        self.rect
1976    }
1977    /// Returns corner radius in world units.
1978    pub const fn corner_radius(&self) -> f32 {
1979        self.corner_radius
1980    }
1981    /// Returns fill, stroke, and shadow styling.
1982    pub const fn style(&self) -> ShapeStyle {
1983        self.style
1984    }
1985}
1986
1987/// Stroked line primitive in world coordinates.
1988#[derive(Debug, Clone)]
1989pub struct Line {
1990    from: Vec2,
1991    to: Vec2,
1992    style: StrokeStyle2d,
1993}
1994
1995impl Line {
1996    /// Returns the start point in world coordinates.
1997    pub const fn from(&self) -> Vec2 {
1998        self.from
1999    }
2000    /// Returns the end point in world coordinates.
2001    pub const fn to(&self) -> Vec2 {
2002        self.to
2003    }
2004    /// Returns color and scalar width; inspect [`Self::stroke_style`] for units.
2005    pub const fn stroke(&self) -> Stroke {
2006        self.style.stroke
2007    }
2008    /// Returns the complete cap, join, dash, marker, and width-mode style.
2009    pub const fn stroke_style(&self) -> StrokeStyle2d {
2010        self.style
2011    }
2012}
2013
2014/// Connected line-strip primitive in world coordinates.
2015#[derive(Debug, Clone)]
2016pub struct Polyline {
2017    points: Vec<Vec2>,
2018    style: StrokeStyle2d,
2019}
2020
2021impl Polyline {
2022    /// Returns connected points in world coordinates.
2023    pub fn points(&self) -> &[Vec2] {
2024        &self.points
2025    }
2026    /// Returns color and scalar width; inspect [`Self::stroke_style`] for units.
2027    pub const fn stroke(&self) -> Stroke {
2028        self.style.stroke
2029    }
2030    /// Returns the complete cap, join, dash, marker, and width-mode style.
2031    pub const fn stroke_style(&self) -> StrokeStyle2d {
2032        self.style
2033    }
2034}
2035
2036#[cfg(test)]
2037mod tests;