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;
22pub const MAX_STROKE_DASH_SUBSEGMENTS: usize = 1_000_000;
24
25#[derive(Debug, Clone, Copy, PartialEq, Eq)]
27pub enum ScenePrimitive {
28 Circle,
30 Rect,
32 Line,
34 Polyline,
36}
37
38#[derive(Debug, Clone, Copy, PartialEq, Eq)]
40#[non_exhaustive]
41pub enum SceneBudgetResource {
42 Commands,
44 Points,
46 TessellatedVertices,
48 RetainedBytes,
50 AllocationBytes,
52 UploadBytes,
54 DrawBatches,
56}
57
58#[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 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 pub const fn max_commands(self) -> usize {
101 self.max_commands
102 }
103
104 pub const fn max_points(self) -> usize {
106 self.max_points
107 }
108
109 pub const fn max_tessellated_vertices(self) -> usize {
111 self.max_tessellated_vertices
112 }
113
114 pub const fn max_retained_bytes(self) -> usize {
116 self.max_retained_bytes
117 }
118
119 pub const fn max_allocation_bytes(self) -> usize {
121 self.max_allocation_bytes
122 }
123
124 pub const fn max_upload_bytes(self) -> usize {
126 self.max_upload_bytes
127 }
128
129 pub const fn max_draw_batches(self) -> usize {
131 self.max_draw_batches
132 }
133}
134
135#[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 pub const fn requested_commands(self) -> usize {
154 self.requested_commands
155 }
156
157 pub const fn accepted_commands(self) -> usize {
159 self.accepted_commands
160 }
161
162 pub const fn rejected_commands(self) -> usize {
164 self.rejected_commands
165 }
166
167 pub const fn requested_by_primitive(self) -> PrimitiveCommandCounts {
169 self.requested_by_primitive
170 }
171
172 pub const fn accepted_by_primitive(self) -> PrimitiveCommandCounts {
174 self.accepted_by_primitive
175 }
176
177 pub const fn rejected_by_primitive(self) -> PrimitiveCommandCounts {
179 self.rejected_by_primitive
180 }
181
182 pub const fn retained_points(self) -> usize {
184 self.retained_points
185 }
186
187 pub const fn estimated_tessellated_vertices(self) -> usize {
189 self.estimated_tessellated_vertices
190 }
191
192 pub const fn retained_bytes(self) -> usize {
194 self.retained_bytes
195 }
196
197 pub const fn estimated_upload_bytes(self) -> usize {
199 self.estimated_upload_bytes
200 }
201
202 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#[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 pub const fn circles(self) -> usize {
237 self.circles
238 }
239
240 pub const fn rectangles(self) -> usize {
242 self.rectangles
243 }
244
245 pub const fn lines(self) -> usize {
247 self.lines
248 }
249
250 pub const fn polylines(self) -> usize {
252 self.polylines
253 }
254
255 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
283pub enum SceneError {
284 InvalidBackground,
286 NonFiniteGeometry(ScenePrimitive),
288 InvalidDimension(ScenePrimitive),
290 DegenerateGeometry(ScenePrimitive),
292 DegenerateStrokeTurn {
298 primitive: ScenePrimitive,
300 vertex_index: usize,
302 },
303 MissingStyle(ScenePrimitive),
305 InvalidFill(ScenePrimitive),
307 InvalidStroke(ScenePrimitive),
309 StrokeExpansionLimitExceeded {
312 primitive: ScenePrimitive,
314 limit: usize,
316 required: usize,
318 },
319 UnrepresentableStrokePattern(ScenePrimitive),
321 UnsupportedTipMarkerPath(ScenePrimitive),
324 InvalidShadow(ScenePrimitive),
326 InvalidScreenClip,
328 NonFiniteDepth,
330 BudgetExceeded {
332 resource: SceneBudgetResource,
334 limit: usize,
336 requested: usize,
338 },
339 AllocationFailed {
341 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#[derive(Debug)]
364pub struct Scene {
365 background: Color,
366 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 pub fn new(background: Color) -> Result<Self, SceneError> {
408 Self::create(background, None)
409 }
410
411 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 pub fn background(&self) -> Color {
434 self.background
435 }
436
437 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 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 pub fn commands(&self) -> &[SceneCommand] {
458 &self.commands
459 }
460
461 pub fn command_count(&self) -> usize {
463 self.commands.len()
464 }
465
466 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 pub const fn budget(&self) -> Option<SceneBudget> {
518 self.budget
519 }
520
521 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 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 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 pub fn set_depth(&mut self, depth: f32) -> bool {
587 self.try_set_depth(depth).is_ok()
588 }
589
590 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 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 pub fn push(&mut self, command: DrawCommand) -> bool {
628 self.try_push(command).is_ok()
629 }
630
631 pub fn try_push(&mut self, command: DrawCommand) -> Result<(), SceneError> {
633 self.try_push_to_layer(Layer::DEFAULT, command)
634 }
635
636 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 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 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 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 pub fn circle(&mut self, center: Vec2, radius: f32, style: ShapeStyle) -> bool {
994 self.try_circle(center, radius, style).is_ok()
995 }
996
997 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 pub fn styled_polyline(&mut self, points: Vec<Vec2>, style: StrokeStyle2d) -> bool {
1228 self.try_styled_polyline(points, style).is_ok()
1229 }
1230
1231 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 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 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#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
1266pub struct Layer {
1267 order: i32,
1268}
1269
1270impl Layer {
1271 pub const DEFAULT: Self = Self::new(0);
1273 pub const BACKGROUND: Self = Self::new(-100);
1275 pub const FOREGROUND: Self = Self::new(100);
1277
1278 pub const fn new(order: i32) -> Self {
1280 Self { order }
1281 }
1282
1283 pub const fn order(self) -> i32 {
1285 self.order
1286 }
1287}
1288
1289#[derive(Debug, Clone, Copy, PartialEq)]
1295pub struct ScreenClipRect {
1296 rect: Rect,
1297}
1298
1299impl ScreenClipRect {
1300 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 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 pub fn min(self) -> LogicalScreenPosition {
1329 LogicalScreenPosition::from_vec2(self.rect.normalized().min)
1330 }
1331
1332 pub fn max(self) -> LogicalScreenPosition {
1334 LogicalScreenPosition::from_vec2(self.rect.normalized().max)
1335 }
1336
1337 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#[derive(Debug, Clone)]
1364pub struct SceneCommand {
1365 layer: Layer,
1367 order: u64,
1369 depth: f32,
1371 screen_clip: Option<ScreenClipRect>,
1373 command: DrawCommand,
1375}
1376
1377impl SceneCommand {
1378 pub fn layer(&self) -> Layer {
1380 self.layer
1381 }
1382
1383 pub fn order(&self) -> u64 {
1385 self.order
1386 }
1387
1388 pub fn depth(&self) -> f32 {
1393 self.depth
1394 }
1395
1396 pub fn screen_clip(&self) -> Option<ScreenClipRect> {
1398 self.screen_clip
1399 }
1400
1401 pub fn command(&self) -> &DrawCommand {
1403 &self.command
1404 }
1405}
1406
1407#[derive(Debug, Clone)]
1409#[non_exhaustive]
1410pub enum DrawCommand {
1411 Circle(Circle),
1413 Rect(RectShape),
1415 Line(Line),
1417 Polyline(Polyline),
1419}
1420
1421impl DrawCommand {
1422 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 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 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 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 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 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 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
1641pub(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
1713pub(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 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 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 (
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#[derive(Debug, Clone)]
1943pub struct Circle {
1944 center: Vec2,
1945 radius: f32,
1946 style: ShapeStyle,
1947}
1948
1949impl Circle {
1950 pub const fn center(&self) -> Vec2 {
1952 self.center
1953 }
1954 pub const fn radius(&self) -> f32 {
1956 self.radius
1957 }
1958 pub const fn style(&self) -> ShapeStyle {
1960 self.style
1961 }
1962}
1963
1964#[derive(Debug, Clone)]
1966pub struct RectShape {
1967 rect: Rect,
1968 corner_radius: f32,
1969 style: ShapeStyle,
1970}
1971
1972impl RectShape {
1973 pub const fn rect(&self) -> Rect {
1975 self.rect
1976 }
1977 pub const fn corner_radius(&self) -> f32 {
1979 self.corner_radius
1980 }
1981 pub const fn style(&self) -> ShapeStyle {
1983 self.style
1984 }
1985}
1986
1987#[derive(Debug, Clone)]
1989pub struct Line {
1990 from: Vec2,
1991 to: Vec2,
1992 style: StrokeStyle2d,
1993}
1994
1995impl Line {
1996 pub const fn from(&self) -> Vec2 {
1998 self.from
1999 }
2000 pub const fn to(&self) -> Vec2 {
2002 self.to
2003 }
2004 pub const fn stroke(&self) -> Stroke {
2006 self.style.stroke
2007 }
2008 pub const fn stroke_style(&self) -> StrokeStyle2d {
2010 self.style
2011 }
2012}
2013
2014#[derive(Debug, Clone)]
2016pub struct Polyline {
2017 points: Vec<Vec2>,
2018 style: StrokeStyle2d,
2019}
2020
2021impl Polyline {
2022 pub fn points(&self) -> &[Vec2] {
2024 &self.points
2025 }
2026 pub const fn stroke(&self) -> Stroke {
2028 self.style.stroke
2029 }
2030 pub const fn stroke_style(&self) -> StrokeStyle2d {
2032 self.style
2033 }
2034}
2035
2036#[cfg(test)]
2037mod tests;