use std::{
error::Error,
fmt,
mem::size_of,
panic::{AssertUnwindSafe, catch_unwind, resume_unwind},
};
use crate::{Color, LogicalScreenPosition, LogicalScreenVector, Rect, Vec2};
mod styles;
pub use styles::{
Fill, LinearGradient, RadialGradient, Shadow, ShapeStyle, Stroke, StrokeCap2d,
StrokeDashPattern2d, StrokeJoin2d, StrokeMarker2d, StrokeMarkerAnchor2d, StrokeStyle2d,
StrokeStyleError, StrokeWidthMode2d,
};
pub(crate) const CIRCLE_SEGMENTS: usize = 64;
pub(crate) const ROUND_CAP_SEGMENTS: usize = 16;
pub(crate) const CORNER_SEGMENTS: usize = 12;
pub(crate) const TESSELLATED_VERTEX_BYTES: usize = 20 * size_of::<f32>();
const MIN_STROKE_TURN_SINE: f64 = 0.000_1;
pub const MAX_STROKE_DASH_SUBSEGMENTS: usize = 1_000_000;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ScenePrimitive {
Circle,
Rect,
Line,
Polyline,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum SceneBudgetResource {
Commands,
Points,
TessellatedVertices,
RetainedBytes,
AllocationBytes,
UploadBytes,
DrawBatches,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SceneBudget {
max_commands: usize,
max_points: usize,
max_tessellated_vertices: usize,
max_retained_bytes: usize,
max_allocation_bytes: usize,
max_upload_bytes: usize,
max_draw_batches: usize,
}
impl SceneBudget {
pub const fn new(
max_commands: usize,
max_points: usize,
max_tessellated_vertices: usize,
max_retained_bytes: usize,
max_allocation_bytes: usize,
max_upload_bytes: usize,
max_draw_batches: usize,
) -> Self {
Self {
max_commands,
max_points,
max_tessellated_vertices,
max_retained_bytes,
max_allocation_bytes,
max_upload_bytes,
max_draw_batches,
}
}
pub const fn max_commands(self) -> usize {
self.max_commands
}
pub const fn max_points(self) -> usize {
self.max_points
}
pub const fn max_tessellated_vertices(self) -> usize {
self.max_tessellated_vertices
}
pub const fn max_retained_bytes(self) -> usize {
self.max_retained_bytes
}
pub const fn max_allocation_bytes(self) -> usize {
self.max_allocation_bytes
}
pub const fn max_upload_bytes(self) -> usize {
self.max_upload_bytes
}
pub const fn max_draw_batches(self) -> usize {
self.max_draw_batches
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct SceneStatistics {
requested_commands: usize,
accepted_commands: usize,
rejected_commands: usize,
requested_by_primitive: PrimitiveCommandCounts,
accepted_by_primitive: PrimitiveCommandCounts,
rejected_by_primitive: PrimitiveCommandCounts,
retained_points: usize,
estimated_tessellated_vertices: usize,
retained_bytes: usize,
estimated_upload_bytes: usize,
estimated_draw_batches: usize,
}
impl SceneStatistics {
pub const fn requested_commands(self) -> usize {
self.requested_commands
}
pub const fn accepted_commands(self) -> usize {
self.accepted_commands
}
pub const fn rejected_commands(self) -> usize {
self.rejected_commands
}
pub const fn requested_by_primitive(self) -> PrimitiveCommandCounts {
self.requested_by_primitive
}
pub const fn accepted_by_primitive(self) -> PrimitiveCommandCounts {
self.accepted_by_primitive
}
pub const fn rejected_by_primitive(self) -> PrimitiveCommandCounts {
self.rejected_by_primitive
}
pub const fn retained_points(self) -> usize {
self.retained_points
}
pub const fn estimated_tessellated_vertices(self) -> usize {
self.estimated_tessellated_vertices
}
pub const fn retained_bytes(self) -> usize {
self.retained_bytes
}
pub const fn estimated_upload_bytes(self) -> usize {
self.estimated_upload_bytes
}
pub const fn estimated_draw_batches(self) -> usize {
self.estimated_draw_batches
}
fn with_command(mut self, command: &DrawCommand) -> Self {
let vertices = command.estimated_tessellated_vertices();
self.accepted_commands = self.accepted_commands.saturating_add(1);
self.accepted_by_primitive.increment(command.primitive());
self.retained_points = self
.retained_points
.saturating_add(command.retained_point_count());
self.estimated_tessellated_vertices =
self.estimated_tessellated_vertices.saturating_add(vertices);
self.retained_bytes = self.retained_bytes.saturating_add(command.retained_bytes());
self.estimated_upload_bytes = self
.estimated_upload_bytes
.saturating_add(vertices.saturating_mul(TESSELLATED_VERTEX_BYTES));
self.estimated_draw_batches = self.estimated_draw_batches.saturating_add(1);
self
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct PrimitiveCommandCounts {
circles: usize,
rectangles: usize,
lines: usize,
polylines: usize,
}
impl PrimitiveCommandCounts {
pub const fn circles(self) -> usize {
self.circles
}
pub const fn rectangles(self) -> usize {
self.rectangles
}
pub const fn lines(self) -> usize {
self.lines
}
pub const fn polylines(self) -> usize {
self.polylines
}
pub const fn total(self) -> usize {
self.circles
.saturating_add(self.rectangles)
.saturating_add(self.lines)
.saturating_add(self.polylines)
}
pub(crate) fn increment(&mut self, primitive: ScenePrimitive) {
match primitive {
ScenePrimitive::Circle => self.circles = self.circles.saturating_add(1),
ScenePrimitive::Rect => self.rectangles = self.rectangles.saturating_add(1),
ScenePrimitive::Line => self.lines = self.lines.saturating_add(1),
ScenePrimitive::Polyline => self.polylines = self.polylines.saturating_add(1),
}
}
pub(crate) fn adding(mut self, other: Self) -> Self {
self.circles = self.circles.saturating_add(other.circles);
self.rectangles = self.rectangles.saturating_add(other.rectangles);
self.lines = self.lines.saturating_add(other.lines);
self.polylines = self.polylines.saturating_add(other.polylines);
self
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SceneError {
InvalidBackground,
NonFiniteGeometry(ScenePrimitive),
InvalidDimension(ScenePrimitive),
DegenerateGeometry(ScenePrimitive),
DegenerateStrokeTurn {
primitive: ScenePrimitive,
vertex_index: usize,
},
MissingStyle(ScenePrimitive),
InvalidFill(ScenePrimitive),
InvalidStroke(ScenePrimitive),
StrokeExpansionLimitExceeded {
primitive: ScenePrimitive,
limit: usize,
required: usize,
},
UnrepresentableStrokePattern(ScenePrimitive),
UnsupportedTipMarkerPath(ScenePrimitive),
InvalidShadow(ScenePrimitive),
InvalidScreenClip,
NonFiniteDepth,
BudgetExceeded {
resource: SceneBudgetResource,
limit: usize,
requested: usize,
},
AllocationFailed {
requested_bytes: usize,
},
}
impl fmt::Display for SceneError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(formatter, "scene command rejected: {self:?}")
}
}
impl Error for SceneError {}
#[derive(Debug)]
pub struct Scene {
background: Color,
commands: Vec<SceneCommand>,
owned_payload_bytes: usize,
next_order: u64,
current_screen_clip: Option<ScreenClipRect>,
current_depth: f32,
budget: Option<SceneBudget>,
statistics: SceneStatistics,
}
impl Clone for Scene {
fn clone(&self) -> Self {
let commands = self.commands.clone();
let owned_payload_bytes = commands
.iter()
.map(|command| command.command.owned_allocation_bytes())
.fold(0usize, usize::saturating_add);
let mut statistics = self.statistics;
statistics.retained_bytes = commands
.len()
.saturating_mul(size_of::<SceneCommand>())
.saturating_add(owned_payload_bytes);
Self {
background: self.background,
commands,
owned_payload_bytes,
next_order: self.next_order,
current_screen_clip: self.current_screen_clip,
current_depth: self.current_depth,
budget: self.budget,
statistics,
}
}
}
impl Scene {
pub fn new(background: Color) -> Result<Self, SceneError> {
Self::create(background, None)
}
pub fn with_budget(background: Color, budget: SceneBudget) -> Result<Self, SceneError> {
Self::create(background, Some(budget))
}
fn create(background: Color, budget: Option<SceneBudget>) -> Result<Self, SceneError> {
if !background.is_normalized() {
return Err(SceneError::InvalidBackground);
}
Ok(Self {
background,
commands: Vec::new(),
owned_payload_bytes: 0,
next_order: 0,
current_screen_clip: None,
current_depth: 0.0,
budget,
statistics: SceneStatistics::default(),
})
}
pub fn background(&self) -> Color {
self.background
}
pub fn set_background(&mut self, background: Color) -> Result<(), SceneError> {
if !background.is_normalized() {
return Err(SceneError::InvalidBackground);
}
self.background = background;
Ok(())
}
pub fn clear(&mut self) {
self.commands.clear();
self.owned_payload_bytes = 0;
self.next_order = 0;
self.current_screen_clip = None;
self.current_depth = 0.0;
self.statistics = SceneStatistics::default();
}
pub fn commands(&self) -> &[SceneCommand] {
&self.commands
}
pub fn command_count(&self) -> usize {
self.commands.len()
}
pub fn allocation_bytes(&self) -> usize {
self.commands
.capacity()
.saturating_mul(size_of::<SceneCommand>())
.saturating_add(self.owned_payload_bytes)
}
pub(crate) fn preflight_command_storage(
&self,
additional_commands: usize,
additional_owned_bytes: usize,
) -> Result<(), SceneError> {
let Some(budget) = self.budget else {
return Ok(());
};
let retained_bytes = self
.statistics
.retained_bytes
.saturating_add(additional_commands.saturating_mul(size_of::<SceneCommand>()))
.saturating_add(additional_owned_bytes);
if retained_bytes > budget.max_retained_bytes {
return Err(SceneError::BudgetExceeded {
resource: SceneBudgetResource::RetainedBytes,
limit: budget.max_retained_bytes,
requested: retained_bytes,
});
}
let required_len = self.commands.len().saturating_add(additional_commands);
let owned_payload_bytes = self
.owned_payload_bytes
.saturating_add(additional_owned_bytes);
let capacity = if required_len <= self.commands.capacity() {
self.commands.capacity()
} else {
budgeted_command_capacity(
budget,
self.commands.capacity(),
required_len,
owned_payload_bytes,
)?
};
validate_scene_allocation_budget(budget, capacity, owned_payload_bytes)
}
pub const fn budget(&self) -> Option<SceneBudget> {
self.budget
}
pub const fn statistics(&self) -> SceneStatistics {
self.statistics
}
pub(crate) const fn current_screen_clip(&self) -> Option<ScreenClipRect> {
self.current_screen_clip
}
pub fn set_screen_clip(
&mut self,
screen_clip: Option<ScreenClipRect>,
) -> Result<Option<ScreenClipRect>, SceneError> {
if screen_clip.is_some_and(|clip| !clip.is_valid()) {
return Err(SceneError::InvalidScreenClip);
}
Ok(std::mem::replace(
&mut self.current_screen_clip,
screen_clip,
))
}
pub fn with_screen_clip<R>(
&mut self,
screen_clip: ScreenClipRect,
draw: impl FnOnce(&mut Self) -> R,
) -> Result<R, SceneError> {
if !screen_clip.is_valid() {
return Err(SceneError::InvalidScreenClip);
}
let previous = self.current_screen_clip;
let combined = match previous {
Some(outer) => outer.intersection(screen_clip)?,
None => screen_clip,
};
if !combined.is_valid() {
return Err(SceneError::InvalidScreenClip);
}
self.current_screen_clip = Some(combined);
let result = catch_unwind(AssertUnwindSafe(|| draw(self)));
self.current_screen_clip = previous;
match result {
Ok(result) => Ok(result),
Err(payload) => resume_unwind(payload),
}
}
pub fn set_depth(&mut self, depth: f32) -> bool {
self.try_set_depth(depth).is_ok()
}
pub fn try_set_depth(&mut self, depth: f32) -> Result<(), SceneError> {
if !depth.is_finite() {
return Err(SceneError::NonFiniteDepth);
}
self.current_depth = depth;
Ok(())
}
pub fn with_depth<R>(
&mut self,
depth: f32,
draw: impl FnOnce(&mut Self) -> R,
) -> Result<R, SceneError> {
if !depth.is_finite() {
return Err(SceneError::NonFiniteDepth);
}
let previous = self.current_depth;
self.current_depth = depth;
let result = catch_unwind(AssertUnwindSafe(|| draw(self)));
self.current_depth = previous;
match result {
Ok(result) => Ok(result),
Err(payload) => resume_unwind(payload),
}
}
pub fn push(&mut self, command: DrawCommand) -> bool {
self.try_push(command).is_ok()
}
pub fn try_push(&mut self, command: DrawCommand) -> Result<(), SceneError> {
self.try_push_to_layer(Layer::DEFAULT, command)
}
pub fn push_to_layer(&mut self, layer: Layer, command: DrawCommand) -> bool {
self.try_push_to_layer(layer, command).is_ok()
}
pub fn try_push_to_layer(
&mut self,
layer: Layer,
command: DrawCommand,
) -> Result<(), SceneError> {
self.try_push_to_layer_ordered::<true>(layer, command)
}
fn try_push_to_layer_ordered<const FAST_APPEND: bool>(
&mut self,
layer: Layer,
command: DrawCommand,
) -> Result<(), SceneError> {
let primitive = command.primitive();
self.statistics.requested_commands = self.statistics.requested_commands.saturating_add(1);
self.statistics.requested_by_primitive.increment(primitive);
let result = self.try_push_to_layer_inner::<FAST_APPEND>(layer, command);
if result.is_err() {
self.statistics.rejected_commands = self.statistics.rejected_commands.saturating_add(1);
self.statistics.rejected_by_primitive.increment(primitive);
}
result
}
pub fn try_extend_to_layers(
&mut self,
commands: impl IntoIterator<Item = (Layer, DrawCommand)>,
) -> Result<(), SceneError> {
let mut staged = Vec::new();
let mut requested = self.statistics;
let mut attempted = 0usize;
let mut attempted_by_primitive = PrimitiveCommandCounts::default();
let mut next_order = self.next_order;
let existing_owned_payload_bytes = self.owned_payload_bytes;
let mut staged_owned_payload_bytes = 0usize;
for (layer, command) in commands {
let primitive = command.primitive();
attempted = attempted.saturating_add(1);
attempted_by_primitive.increment(primitive);
requested.requested_commands = requested.requested_commands.saturating_add(1);
requested.requested_by_primitive.increment(primitive);
if let Err(error) = command.validate() {
self.record_batch_rejection(attempted, attempted_by_primitive);
return Err(error);
}
if self
.current_screen_clip
.is_some_and(|screen_clip| !screen_clip.is_valid())
{
self.record_batch_rejection(attempted, attempted_by_primitive);
return Err(SceneError::InvalidScreenClip);
}
requested = requested.with_command(&command);
if let Some(budget) = self.budget
&& let Err(error) = validate_scene_budget(budget, requested)
{
self.record_batch_rejection(attempted, attempted_by_primitive);
return Err(error);
}
let command_owned_payload_bytes = command.owned_allocation_bytes();
let prospective_owned_payload_bytes = existing_owned_payload_bytes
.saturating_add(staged_owned_payload_bytes)
.saturating_add(command_owned_payload_bytes);
if let Some(budget) = self.budget {
let required_total = self
.commands
.len()
.saturating_add(staged.len())
.saturating_add(1);
let final_capacity = if required_total <= self.commands.capacity() {
self.commands.capacity()
} else {
match budgeted_command_capacity(
budget,
self.commands.capacity(),
required_total,
prospective_owned_payload_bytes,
) {
Ok(capacity) => capacity,
Err(error) => {
self.record_batch_rejection(attempted, attempted_by_primitive);
return Err(error);
}
}
};
if let Err(error) = validate_scene_allocation_budget(
budget,
final_capacity,
prospective_owned_payload_bytes,
) {
self.record_batch_rejection(attempted, attempted_by_primitive);
return Err(error);
}
if staged.len() == staged.capacity() {
let staging_capacity = match budgeted_command_capacity(
budget,
staged.capacity(),
staged.len().saturating_add(1),
prospective_owned_payload_bytes,
) {
Ok(capacity) => capacity,
Err(error) => {
self.record_batch_rejection(attempted, attempted_by_primitive);
return Err(error);
}
};
let mut replacement = Vec::new();
if replacement.try_reserve_exact(staging_capacity).is_err() {
self.record_batch_rejection(attempted, attempted_by_primitive);
return Err(SceneError::AllocationFailed {
requested_bytes: scene_allocation_bytes(
staging_capacity,
prospective_owned_payload_bytes,
),
});
}
if let Err(error) = validate_scene_allocation_budget(
budget,
replacement.capacity(),
prospective_owned_payload_bytes,
) {
self.record_batch_rejection(attempted, attempted_by_primitive);
return Err(error);
}
replacement.append(&mut staged);
staged = replacement;
} else if let Err(error) = validate_scene_allocation_budget(
budget,
staged.capacity(),
prospective_owned_payload_bytes,
) {
self.record_batch_rejection(attempted, attempted_by_primitive);
return Err(error);
}
} else if staged.try_reserve(1).is_err() {
self.record_batch_rejection(attempted, attempted_by_primitive);
return Err(SceneError::AllocationFailed {
requested_bytes: command.retained_bytes(),
});
}
staged.push(SceneCommand {
layer,
order: next_order,
depth: self.current_depth,
screen_clip: self.current_screen_clip,
command,
});
staged_owned_payload_bytes =
staged_owned_payload_bytes.saturating_add(command_owned_payload_bytes);
next_order = next_order.saturating_add(1);
}
if staged.is_empty() {
return Ok(());
}
let total = self.commands.len().saturating_add(staged.len());
let owned_payload_bytes =
existing_owned_payload_bytes.saturating_add(staged_owned_payload_bytes);
let requested_capacity = if let Some(budget) = self.budget {
if total <= self.commands.capacity() {
self.commands.capacity()
} else {
match budgeted_command_capacity(
budget,
self.commands.capacity(),
total,
owned_payload_bytes,
) {
Ok(capacity) => capacity,
Err(error) => {
self.record_batch_rejection(attempted, attempted_by_primitive);
return Err(error);
}
}
}
} else {
total
};
if staged.capacity() < requested_capacity
&& staged
.try_reserve_exact(requested_capacity.saturating_sub(staged.len()))
.is_err()
{
self.record_batch_rejection(attempted, attempted_by_primitive);
return Err(SceneError::AllocationFailed {
requested_bytes: scene_allocation_bytes(requested_capacity, owned_payload_bytes),
});
}
if let Some(budget) = self.budget
&& let Err(error) =
validate_scene_allocation_budget(budget, staged.capacity(), owned_payload_bytes)
{
self.record_batch_rejection(attempted, attempted_by_primitive);
return Err(error);
}
staged.append(&mut self.commands);
staged.sort_unstable_by_key(|command| (command.layer, command.order));
self.commands = staged;
self.owned_payload_bytes = owned_payload_bytes;
self.next_order = next_order;
self.statistics = requested;
Ok(())
}
fn record_batch_rejection(
&mut self,
command_count: usize,
by_primitive: PrimitiveCommandCounts,
) {
self.statistics.requested_commands = self
.statistics
.requested_commands
.saturating_add(command_count);
self.statistics.rejected_commands = self
.statistics
.rejected_commands
.saturating_add(command_count);
self.statistics.requested_by_primitive =
self.statistics.requested_by_primitive.adding(by_primitive);
self.statistics.rejected_by_primitive =
self.statistics.rejected_by_primitive.adding(by_primitive);
}
pub(crate) fn record_external_rejection(&mut self, primitive: ScenePrimitive) {
let mut counts = PrimitiveCommandCounts::default();
counts.increment(primitive);
self.record_batch_rejection(1, counts);
}
fn try_push_to_layer_inner<const FAST_APPEND: bool>(
&mut self,
layer: Layer,
command: DrawCommand,
) -> Result<(), SceneError> {
command.validate()?;
if self
.current_screen_clip
.is_some_and(|screen_clip| !screen_clip.is_valid())
{
return Err(SceneError::InvalidScreenClip);
}
let command_retained_bytes = command.retained_bytes();
let owned_payload_bytes = self
.owned_payload_bytes
.saturating_add(command.owned_allocation_bytes());
let requested = self.statistics.with_command(&command);
if let Some(budget) = self.budget {
validate_scene_budget(budget, requested)?;
}
let replacement = if self.commands.len() == self.commands.capacity() {
if let Some(budget) = self.budget {
let required_len = self.commands.len().saturating_add(1);
let capacity = budgeted_command_capacity(
budget,
self.commands.capacity(),
required_len,
owned_payload_bytes,
)?;
let mut replacement = Vec::new();
replacement.try_reserve_exact(capacity).map_err(|_| {
SceneError::AllocationFailed {
requested_bytes: scene_allocation_bytes(capacity, owned_payload_bytes),
}
})?;
validate_scene_allocation_budget(
budget,
replacement.capacity(),
owned_payload_bytes,
)?;
Some(replacement)
} else {
self.commands
.try_reserve(1)
.map_err(|_| SceneError::AllocationFailed {
requested_bytes: command_retained_bytes,
})?;
None
}
} else {
if let Some(budget) = self.budget {
validate_scene_allocation_budget(
budget,
self.commands.capacity(),
owned_payload_bytes,
)?;
}
None
};
if let Some(mut replacement) = replacement {
replacement.append(&mut self.commands);
self.commands = replacement;
}
let order = self.next_order;
let scene_command = SceneCommand {
layer,
order,
depth: self.current_depth,
screen_clip: self.current_screen_clip,
command,
};
if FAST_APPEND
&& self
.commands
.last()
.is_none_or(|existing| existing.layer <= layer)
{
self.commands.push(scene_command);
} else {
let position = self.commands.partition_point(|existing| {
existing.layer < scene_command.layer
|| (existing.layer == scene_command.layer
&& existing.order <= scene_command.order)
});
self.commands.insert(position, scene_command);
}
self.owned_payload_bytes = owned_payload_bytes;
self.next_order = self.next_order.saturating_add(1);
self.statistics = requested;
Ok(())
}
pub fn circle(&mut self, center: Vec2, radius: f32, style: ShapeStyle) -> bool {
self.try_circle(center, radius, style).is_ok()
}
pub fn try_circle(
&mut self,
center: Vec2,
radius: f32,
style: ShapeStyle,
) -> Result<(), SceneError> {
self.try_circle_on_layer(Layer::DEFAULT, center, radius, style)
}
pub fn circle_on_layer(
&mut self,
layer: Layer,
center: Vec2,
radius: f32,
style: ShapeStyle,
) -> bool {
self.try_circle_on_layer(layer, center, radius, style)
.is_ok()
}
pub fn try_circle_on_layer(
&mut self,
layer: Layer,
center: Vec2,
radius: f32,
style: ShapeStyle,
) -> Result<(), SceneError> {
self.try_push_to_layer(
layer,
DrawCommand::Circle(Circle {
center,
radius,
style,
}),
)
}
pub fn rect(&mut self, rect: Rect, corner_radius: f32, style: ShapeStyle) -> bool {
self.try_rect(rect, corner_radius, style).is_ok()
}
pub fn try_rect(
&mut self,
rect: Rect,
corner_radius: f32,
style: ShapeStyle,
) -> Result<(), SceneError> {
self.try_rect_on_layer(Layer::DEFAULT, rect, corner_radius, style)
}
pub fn rect_on_layer(
&mut self,
layer: Layer,
rect: Rect,
corner_radius: f32,
style: ShapeStyle,
) -> bool {
self.try_rect_on_layer(layer, rect, corner_radius, style)
.is_ok()
}
pub fn try_rect_on_layer(
&mut self,
layer: Layer,
rect: Rect,
corner_radius: f32,
style: ShapeStyle,
) -> Result<(), SceneError> {
self.try_push_to_layer(
layer,
DrawCommand::Rect(RectShape {
rect,
corner_radius,
style,
}),
)
}
pub fn line(&mut self, from: Vec2, to: Vec2, width: f32, color: Color) -> bool {
self.try_line(from, to, width, color).is_ok()
}
pub fn try_line(
&mut self,
from: Vec2,
to: Vec2,
width: f32,
color: Color,
) -> Result<(), SceneError> {
self.try_styled_line(from, to, StrokeStyle2d::new(width, color))
}
pub fn line_on_layer(
&mut self,
layer: Layer,
from: Vec2,
to: Vec2,
width: f32,
color: Color,
) -> bool {
self.try_line_on_layer(layer, from, to, width, color)
.is_ok()
}
pub fn try_line_on_layer(
&mut self,
layer: Layer,
from: Vec2,
to: Vec2,
width: f32,
color: Color,
) -> Result<(), SceneError> {
self.try_styled_line_on_layer(layer, from, to, StrokeStyle2d::new(width, color))
}
pub fn styled_line(&mut self, from: Vec2, to: Vec2, style: StrokeStyle2d) -> bool {
self.try_styled_line(from, to, style).is_ok()
}
pub fn try_styled_line(
&mut self,
from: Vec2,
to: Vec2,
style: StrokeStyle2d,
) -> Result<(), SceneError> {
self.try_styled_line_on_layer(Layer::DEFAULT, from, to, style)
}
pub fn styled_line_on_layer(
&mut self,
layer: Layer,
from: Vec2,
to: Vec2,
style: StrokeStyle2d,
) -> bool {
self.try_styled_line_on_layer(layer, from, to, style)
.is_ok()
}
pub fn try_styled_line_on_layer(
&mut self,
layer: Layer,
from: Vec2,
to: Vec2,
style: StrokeStyle2d,
) -> Result<(), SceneError> {
self.try_push_to_layer(layer, DrawCommand::Line(Line { from, to, style }))
}
pub fn polyline(&mut self, points: Vec<Vec2>, width: f32, color: Color) -> bool {
self.try_polyline(points, width, color).is_ok()
}
pub fn try_polyline(
&mut self,
points: Vec<Vec2>,
width: f32,
color: Color,
) -> Result<(), SceneError> {
self.try_styled_polyline(points, StrokeStyle2d::new(width, color))
}
pub fn polyline_on_layer(
&mut self,
layer: Layer,
points: Vec<Vec2>,
width: f32,
color: Color,
) -> bool {
self.try_polyline_on_layer(layer, points, width, color)
.is_ok()
}
pub fn try_polyline_on_layer(
&mut self,
layer: Layer,
points: Vec<Vec2>,
width: f32,
color: Color,
) -> Result<(), SceneError> {
self.try_styled_polyline_on_layer(layer, points, StrokeStyle2d::new(width, color))
}
pub fn styled_polyline(&mut self, points: Vec<Vec2>, style: StrokeStyle2d) -> bool {
self.try_styled_polyline(points, style).is_ok()
}
pub fn try_styled_polyline(
&mut self,
points: Vec<Vec2>,
style: StrokeStyle2d,
) -> Result<(), SceneError> {
self.try_styled_polyline_on_layer(Layer::DEFAULT, points, style)
}
pub fn styled_polyline_on_layer(
&mut self,
layer: Layer,
points: Vec<Vec2>,
style: StrokeStyle2d,
) -> bool {
self.try_styled_polyline_on_layer(layer, points, style)
.is_ok()
}
pub fn try_styled_polyline_on_layer(
&mut self,
layer: Layer,
points: Vec<Vec2>,
style: StrokeStyle2d,
) -> Result<(), SceneError> {
self.try_push_to_layer(layer, DrawCommand::Polyline(Polyline { points, style }))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Layer {
order: i32,
}
impl Layer {
pub const DEFAULT: Self = Self::new(0);
pub const BACKGROUND: Self = Self::new(-100);
pub const FOREGROUND: Self = Self::new(100);
pub const fn new(order: i32) -> Self {
Self { order }
}
pub const fn order(self) -> i32 {
self.order
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ScreenClipRect {
rect: Rect,
}
impl ScreenClipRect {
pub fn new(min: LogicalScreenPosition, max: LogicalScreenPosition) -> Result<Self, SceneError> {
Self::from_rect(Rect::new(min.to_vec2(), max.to_vec2()))
}
pub fn from_min_size(
min: LogicalScreenPosition,
size: LogicalScreenVector,
) -> Result<Self, SceneError> {
Self::from_rect(Rect::from_min_size(min.to_vec2(), size.to_vec2()))
}
fn from_rect(rect: Rect) -> Result<Self, SceneError> {
let clip = Self { rect };
clip.is_valid()
.then_some(clip)
.ok_or(SceneError::InvalidScreenClip)
}
#[cfg(feature = "wgpu")]
pub(crate) fn rect(self) -> Rect {
self.rect
}
pub fn min(self) -> LogicalScreenPosition {
LogicalScreenPosition::from_vec2(self.rect.normalized().min)
}
pub fn max(self) -> LogicalScreenPosition {
LogicalScreenPosition::from_vec2(self.rect.normalized().max)
}
pub fn intersection(self, other: Self) -> Result<Self, SceneError> {
let first = self.rect.normalized();
let second = other.rect.normalized();
let min = Vec2::new(first.min.x.max(second.min.x), first.min.y.max(second.min.y));
let max = Vec2::new(first.max.x.min(second.max.x), first.max.y.min(second.max.y));
Self::new(
LogicalScreenPosition::from_vec2(min),
LogicalScreenPosition::from_vec2(Vec2::new(max.x.max(min.x), max.y.max(min.y))),
)
}
fn is_valid(self) -> bool {
if !self.rect.min.is_finite() || !self.rect.max.is_finite() {
return false;
}
let rect = self.rect.normalized();
rect.width() > 0.0 && rect.height() > 0.0
}
}
#[derive(Debug, Clone)]
pub struct SceneCommand {
layer: Layer,
order: u64,
depth: f32,
screen_clip: Option<ScreenClipRect>,
command: DrawCommand,
}
impl SceneCommand {
pub fn layer(&self) -> Layer {
self.layer
}
pub fn order(&self) -> u64 {
self.order
}
pub fn depth(&self) -> f32 {
self.depth
}
pub fn screen_clip(&self) -> Option<ScreenClipRect> {
self.screen_clip
}
pub fn command(&self) -> &DrawCommand {
&self.command
}
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum DrawCommand {
Circle(Circle),
Rect(RectShape),
Line(Line),
Polyline(Polyline),
}
impl DrawCommand {
pub const fn primitive(&self) -> ScenePrimitive {
match self {
Self::Circle(_) => ScenePrimitive::Circle,
Self::Rect(_) => ScenePrimitive::Rect,
Self::Line(_) => ScenePrimitive::Line,
Self::Polyline(_) => ScenePrimitive::Polyline,
}
}
pub fn circle(center: Vec2, radius: f32, style: ShapeStyle) -> Result<Self, SceneError> {
let command = Self::Circle(Circle {
center,
radius,
style,
});
command.validate()?;
Ok(command)
}
pub fn rect(rect: Rect, corner_radius: f32, style: ShapeStyle) -> Result<Self, SceneError> {
let command = Self::Rect(RectShape {
rect,
corner_radius,
style,
});
command.validate()?;
Ok(command)
}
pub fn line(from: Vec2, to: Vec2, width: f32, color: Color) -> Result<Self, SceneError> {
Self::styled_line(from, to, StrokeStyle2d::new(width, color))
}
pub fn styled_line(from: Vec2, to: Vec2, style: StrokeStyle2d) -> Result<Self, SceneError> {
let command = Self::Line(Line { from, to, style });
command.validate()?;
Ok(command)
}
pub fn polyline(points: Vec<Vec2>, width: f32, color: Color) -> Result<Self, SceneError> {
Self::styled_polyline(points, StrokeStyle2d::new(width, color))
}
pub fn styled_polyline(points: Vec<Vec2>, style: StrokeStyle2d) -> Result<Self, SceneError> {
let command = Self::Polyline(Polyline { points, style });
command.validate()?;
Ok(command)
}
fn validate(&self) -> Result<(), SceneError> {
match self {
Self::Circle(circle) => {
if !circle.center.is_finite() {
return Err(SceneError::NonFiniteGeometry(ScenePrimitive::Circle));
}
if !circle.radius.is_finite() || circle.radius <= 0.0 {
return Err(SceneError::InvalidDimension(ScenePrimitive::Circle));
}
if !(circle.center + Vec2::splat(circle.radius)).is_finite()
|| !(circle.center - Vec2::splat(circle.radius)).is_finite()
{
return Err(SceneError::NonFiniteGeometry(ScenePrimitive::Circle));
}
circle.style.validate(ScenePrimitive::Circle)
}
Self::Rect(rectangle) => {
let rect = rectangle.rect.normalized();
if !rect.min.is_finite() || !rect.max.is_finite() {
return Err(SceneError::NonFiniteGeometry(ScenePrimitive::Rect));
}
let width = rect.width();
let height = rect.height();
if !width.is_finite() || !height.is_finite() {
return Err(SceneError::NonFiniteGeometry(ScenePrimitive::Rect));
}
if width <= 0.0
|| height <= 0.0
|| !rectangle.corner_radius.is_finite()
|| rectangle.corner_radius < 0.0
{
return Err(SceneError::InvalidDimension(ScenePrimitive::Rect));
}
rectangle.style.validate(ScenePrimitive::Rect)
}
Self::Line(line) => {
if !line.from.is_finite() || !line.to.is_finite() {
return Err(SceneError::NonFiniteGeometry(ScenePrimitive::Line));
}
if !(line.to - line.from).is_finite() {
return Err(SceneError::NonFiniteGeometry(ScenePrimitive::Line));
}
if !drawable_segment(line.from, line.to) {
return Err(SceneError::DegenerateGeometry(ScenePrimitive::Line));
}
if !line.style.is_valid() {
return Err(SceneError::InvalidStroke(ScenePrimitive::Line));
}
validate_stroke_path(&[line.from, line.to], line.style, ScenePrimitive::Line)?;
Ok(())
}
Self::Polyline(polyline) => {
validate_styled_polyline(polyline.points.iter().copied(), polyline.style)?;
Ok(())
}
}
}
fn retained_point_count(&self) -> usize {
match self {
Self::Polyline(polyline) => polyline.points.len(),
Self::Circle(_) | Self::Rect(_) | Self::Line(_) => 0,
}
}
fn retained_bytes(&self) -> usize {
size_of::<SceneCommand>().saturating_add(self.owned_allocation_bytes())
}
fn owned_allocation_bytes(&self) -> usize {
match self {
Self::Polyline(polyline) => {
polyline.points.capacity().saturating_mul(size_of::<Vec2>())
}
Self::Circle(_) | Self::Rect(_) | Self::Line(_) => 0,
}
}
fn estimated_tessellated_vertices(&self) -> usize {
match self {
Self::Circle(circle) => {
let fill_vertices = CIRCLE_SEGMENTS * 3;
let stroke_vertices = CIRCLE_SEGMENTS * 6;
let style = circle.style;
usize::from(style.fill.is_some()) * fill_vertices
+ usize::from(style.stroke.is_some()) * stroke_vertices
+ style.shadow.map_or(0, |shadow| {
fill_vertices + usize::from(shadow.spread > 0.0) * stroke_vertices
})
}
Self::Rect(rectangle) => {
let rect = rectangle.rect.normalized();
let radius = rectangle
.corner_radius
.max(0.0)
.min(rect.width().abs() * 0.5)
.min(rect.height().abs() * 0.5);
let boundary_segments = if radius <= 0.0 {
4
} else {
4 * (CORNER_SEGMENTS + 1)
};
let fill_vertices = boundary_segments * 3;
let stroke_vertices = boundary_segments * 6;
let style = rectangle.style;
usize::from(style.fill.is_some()) * fill_vertices
+ usize::from(style.stroke.is_some()) * stroke_vertices
+ style.shadow.map_or(0, |shadow| {
fill_vertices + usize::from(shadow.spread > 0.0) * stroke_vertices
})
}
Self::Line(line) => estimate_stroke_vertices(&[line.from, line.to], line.style),
Self::Polyline(polyline) => estimate_stroke_vertices(&polyline.points, polyline.style),
}
}
}
fn validate_stroke_path(
points: &[Vec2],
style: StrokeStyle2d,
primitive: ScenePrimitive,
) -> Result<(), SceneError> {
validate_stroke_path_iter(points.iter().copied(), style, primitive)
}
fn validate_stroke_path_iter<I>(
points: I,
style: StrokeStyle2d,
primitive: ScenePrimitive,
) -> Result<(), SceneError>
where
I: Iterator<Item = Vec2> + Clone,
{
if style.has_tip_marker() && (style.dash.is_some() || points.clone().count() != 2) {
return Err(SceneError::UnsupportedTipMarkerPath(primitive));
}
let maximum_offset = f64::from(style.stroke.width) * 0.5 * f64::from(style.miter_limit);
if !maximum_offset.is_finite() || maximum_offset > f64::from(f32::MAX) {
return Err(SceneError::InvalidStroke(primitive));
}
if style.width_mode == StrokeWidthMode2d::WorldUnits {
let extent = Vec2::splat(maximum_offset as f32);
if points
.clone()
.any(|point| !(point + extent).is_finite() || !(point - extent).is_finite())
{
return Err(SceneError::NonFiniteGeometry(primitive));
}
}
if let Some(dash) = style.dash {
let required = dash_subsegment_count_iter(points, dash, Some(dash.max_subsegments))
.ok_or(SceneError::UnrepresentableStrokePattern(primitive))?;
if required > dash.max_subsegments {
return Err(SceneError::StrokeExpansionLimitExceeded {
primitive,
limit: dash.max_subsegments,
required,
});
}
}
Ok(())
}
pub(crate) fn validate_polyline_geometry<I>(points: I) -> Result<(), SceneError>
where
I: Iterator<Item = Vec2> + Clone,
{
let primitive = ScenePrimitive::Polyline;
if !points.clone().all(|point| point.is_finite()) {
return Err(SceneError::NonFiniteGeometry(primitive));
}
let mut deltas = points.clone();
let Some(mut previous) = deltas.next() else {
return Err(SceneError::DegenerateGeometry(primitive));
};
let mut segment_count = 0usize;
for point in deltas {
let delta = point - previous;
if !delta.is_finite() {
return Err(SceneError::NonFiniteGeometry(primitive));
}
previous = point;
segment_count = segment_count.saturating_add(1);
}
if segment_count == 0 {
return Err(SceneError::DegenerateGeometry(primitive));
}
let mut segments = points.clone();
let mut previous = segments
.next()
.expect("a non-empty path was established above");
for point in segments {
if !drawable_segment(previous, point) {
return Err(SceneError::DegenerateGeometry(primitive));
}
previous = point;
}
let mut turns = points;
let mut first = turns
.next()
.expect("a drawable segment was established above");
let mut second = turns
.next()
.expect("a drawable segment was established above");
for (index, third) in turns.enumerate() {
let incoming = second - first;
let outgoing = third - second;
let cross = f64::from(incoming.x) * f64::from(outgoing.y)
- f64::from(incoming.y) * f64::from(outgoing.x);
let dot = f64::from(incoming.x) * f64::from(outgoing.x)
+ f64::from(incoming.y) * f64::from(outgoing.y);
let direction_product = f64::from(incoming.x).hypot(f64::from(incoming.y))
* f64::from(outgoing.x).hypot(f64::from(outgoing.y));
let normalized_cross = cross / direction_product;
if normalized_cross.abs() <= MIN_STROKE_TURN_SINE && (dot < 0.0 || normalized_cross != 0.0)
{
return Err(SceneError::DegenerateStrokeTurn {
primitive,
vertex_index: index + 1,
});
}
first = second;
second = third;
}
Ok(())
}
pub(crate) fn validate_styled_polyline<I>(points: I, style: StrokeStyle2d) -> Result<(), SceneError>
where
I: Iterator<Item = Vec2> + Clone,
{
validate_polyline_geometry(points.clone())?;
if !style.is_valid() {
return Err(SceneError::InvalidStroke(ScenePrimitive::Polyline));
}
validate_stroke_path_iter(points, style, ScenePrimitive::Polyline)
}
fn estimate_stroke_vertices(points: &[Vec2], style: StrokeStyle2d) -> usize {
let segment_count = points
.windows(2)
.filter(|pair| drawable_segment(pair[0], pair[1]))
.count();
if segment_count == 0 {
return 0;
}
let body_count = style.dash.map_or(segment_count, |dash| {
dash_subsegment_count(points, dash, None)
.expect("accepted dash paths have representable subsegments")
});
let join_count = segment_count.saturating_sub(1);
let cap_count = if style.dash.is_some() {
body_count.saturating_mul(2)
} else {
2
};
let cap_vertices = match style.cap {
StrokeCap2d::Round => cap_count.saturating_mul(ROUND_CAP_SEGMENTS * 3),
StrokeCap2d::Butt | StrokeCap2d::Square => 0,
};
let join_vertices = match style.join {
StrokeJoin2d::Bevel => join_count.saturating_mul(6),
StrokeJoin2d::Miter => join_count.saturating_mul(12),
StrokeJoin2d::Round if style.width_mode == StrokeWidthMode2d::LogicalPixels => {
join_count.saturating_mul(ROUND_CAP_SEGMENTS * 6)
}
StrokeJoin2d::Round => join_count.saturating_mul(ROUND_CAP_SEGMENTS * 3),
};
let marker_vertices = (usize::from(style.start_marker.is_some())
+ usize::from(style.end_marker.is_some()))
.saturating_mul(3);
body_count
.saturating_mul(6)
.saturating_add(cap_vertices)
.saturating_add(join_vertices)
.saturating_add(marker_vertices)
}
fn dash_subsegment_count(
points: &[Vec2],
dash: StrokeDashPattern2d,
stop_after: Option<usize>,
) -> Option<usize> {
dash_subsegment_count_iter(points.iter().copied(), dash, stop_after)
}
fn dash_subsegment_count_iter<I>(
points: I,
dash: StrokeDashPattern2d,
stop_after: Option<usize>,
) -> Option<usize>
where
I: Iterator<Item = Vec2>,
{
let lengths = dash.lengths();
let total: f64 = lengths.iter().map(|length| f64::from(*length)).sum();
let mut phase = f64::from(dash.phase).rem_euclid(total);
let mut pattern_index = 0usize;
while phase >= f64::from(lengths[pattern_index]) {
phase -= f64::from(lengths[pattern_index]);
pattern_index = (pattern_index + 1) % lengths.len();
}
let mut pattern_remaining = f64::from(lengths[pattern_index]) - phase;
let mut count = 0usize;
let mut points = points;
let mut previous = points.next()?;
for point in points {
let delta = point - previous;
let segment_length = f64::from(delta.x).hypot(f64::from(delta.y));
let mut segment_remaining = segment_length;
while segment_remaining > 0.0 {
let consumed = segment_remaining.min(pattern_remaining);
if pattern_index.is_multiple_of(2) && consumed > 0.0 {
count = count.saturating_add(1);
if stop_after.is_some_and(|limit| count > limit) {
return Some(count);
}
}
let next_remaining = segment_remaining - consumed;
if next_remaining >= segment_remaining {
return None;
}
let amount_start = 1.0 - segment_remaining / segment_length;
let amount_end = 1.0 - next_remaining / segment_length;
if dash_segment_point(previous, point, amount_start)
== dash_segment_point(previous, point, amount_end)
{
return None;
}
segment_remaining = next_remaining;
pattern_remaining -= consumed;
if pattern_remaining <= 0.0 {
pattern_index = (pattern_index + 1) % lengths.len();
pattern_remaining = f64::from(lengths[pattern_index]);
}
}
previous = point;
}
Some(count)
}
fn dash_segment_point(from: Vec2, to: Vec2, amount: f64) -> Vec2 {
Vec2::new(
(f64::from(from.x) * (1.0 - amount) + f64::from(to.x) * amount) as f32,
(f64::from(from.y) * (1.0 - amount) + f64::from(to.y) * amount) as f32,
)
}
fn validate_scene_budget(
budget: SceneBudget,
requested: SceneStatistics,
) -> Result<(), SceneError> {
let limits = [
(
SceneBudgetResource::Commands,
budget.max_commands,
requested.accepted_commands,
),
(
SceneBudgetResource::Points,
budget.max_points,
requested.retained_points,
),
(
SceneBudgetResource::TessellatedVertices,
budget.max_tessellated_vertices,
requested.estimated_tessellated_vertices,
),
(
SceneBudgetResource::RetainedBytes,
budget.max_retained_bytes,
requested.retained_bytes,
),
(
SceneBudgetResource::UploadBytes,
budget.max_upload_bytes,
requested.estimated_upload_bytes,
),
(
SceneBudgetResource::DrawBatches,
budget.max_draw_batches,
requested.estimated_draw_batches,
),
];
for (resource, limit, requested) in limits {
if requested > limit {
return Err(SceneError::BudgetExceeded {
resource,
limit,
requested,
});
}
}
Ok(())
}
fn scene_allocation_bytes(command_capacity: usize, owned_payload_bytes: usize) -> usize {
command_capacity
.saturating_mul(size_of::<SceneCommand>())
.saturating_add(owned_payload_bytes)
}
fn validate_scene_allocation_budget(
budget: SceneBudget,
command_capacity: usize,
owned_payload_bytes: usize,
) -> Result<(), SceneError> {
let requested = scene_allocation_bytes(command_capacity, owned_payload_bytes);
if requested > budget.max_allocation_bytes {
return Err(SceneError::BudgetExceeded {
resource: SceneBudgetResource::AllocationBytes,
limit: budget.max_allocation_bytes,
requested,
});
}
Ok(())
}
fn budgeted_command_capacity(
budget: SceneBudget,
current_capacity: usize,
required_len: usize,
owned_payload_bytes: usize,
) -> Result<usize, SceneError> {
let available = budget
.max_allocation_bytes
.saturating_sub(owned_payload_bytes);
let maximum_capacity = available / size_of::<SceneCommand>();
if required_len > maximum_capacity {
return Err(SceneError::BudgetExceeded {
resource: SceneBudgetResource::AllocationBytes,
limit: budget.max_allocation_bytes,
requested: scene_allocation_bytes(required_len, owned_payload_bytes),
});
}
Ok(current_capacity
.max(1)
.saturating_mul(2)
.max(required_len)
.min(maximum_capacity))
}
fn drawable_segment(from: Vec2, to: Vec2) -> bool {
let delta = to - from;
delta.is_finite() && (delta.x != 0.0 || delta.y != 0.0)
}
#[derive(Debug, Clone)]
pub struct Circle {
center: Vec2,
radius: f32,
style: ShapeStyle,
}
impl Circle {
pub const fn center(&self) -> Vec2 {
self.center
}
pub const fn radius(&self) -> f32 {
self.radius
}
pub const fn style(&self) -> ShapeStyle {
self.style
}
}
#[derive(Debug, Clone)]
pub struct RectShape {
rect: Rect,
corner_radius: f32,
style: ShapeStyle,
}
impl RectShape {
pub const fn rect(&self) -> Rect {
self.rect
}
pub const fn corner_radius(&self) -> f32 {
self.corner_radius
}
pub const fn style(&self) -> ShapeStyle {
self.style
}
}
#[derive(Debug, Clone)]
pub struct Line {
from: Vec2,
to: Vec2,
style: StrokeStyle2d,
}
impl Line {
pub const fn from(&self) -> Vec2 {
self.from
}
pub const fn to(&self) -> Vec2 {
self.to
}
pub const fn stroke(&self) -> Stroke {
self.style.stroke
}
pub const fn stroke_style(&self) -> StrokeStyle2d {
self.style
}
}
#[derive(Debug, Clone)]
pub struct Polyline {
points: Vec<Vec2>,
style: StrokeStyle2d,
}
impl Polyline {
pub fn points(&self) -> &[Vec2] {
&self.points
}
pub const fn stroke(&self) -> Stroke {
self.style.stroke
}
pub const fn stroke_style(&self) -> StrokeStyle2d {
self.style
}
}
#[cfg(test)]
mod tests;