use std::{error::Error, fmt};
use crate::{Color, Interpolate, LogicalPixels, LogicalScreenVector, Vec2, WorldLength};
use super::{MAX_STROKE_DASH_SUBSEGMENTS, SceneError, ScenePrimitive};
const MAX_DASH_ELEMENTS: usize = 8;
const MAX_MITER_LIMIT: f32 = 1_000.0;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StrokeWidthMode2d {
LogicalPixels,
WorldUnits,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StrokeCap2d {
Butt,
Square,
Round,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StrokeJoin2d {
Bevel,
Round,
Miter,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct StrokeDashPattern2d {
lengths: [f32; MAX_DASH_ELEMENTS],
length_count: u8,
pub(super) phase: f32,
pub(super) max_subsegments: usize,
}
impl StrokeDashPattern2d {
pub fn new(
lengths: &[f32],
phase: f32,
max_subsegments: usize,
) -> Result<Self, StrokeStyleError> {
if lengths.len() < 2
|| lengths.len() > MAX_DASH_ELEMENTS
|| !lengths.len().is_multiple_of(2)
{
return Err(StrokeStyleError::InvalidDashElementCount);
}
if lengths
.iter()
.any(|length| !length.is_finite() || *length <= 0.0)
{
return Err(StrokeStyleError::InvalidDashLength);
}
if !phase.is_finite() {
return Err(StrokeStyleError::InvalidDashPhase);
}
if max_subsegments == 0 || max_subsegments > MAX_STROKE_DASH_SUBSEGMENTS {
return Err(StrokeStyleError::InvalidDashExpansionLimit);
}
let mut stored = [0.0; MAX_DASH_ELEMENTS];
stored[..lengths.len()].copy_from_slice(lengths);
Ok(Self {
lengths: stored,
length_count: lengths.len() as u8,
phase,
max_subsegments,
})
}
pub fn lengths(&self) -> &[f32] {
&self.lengths[..usize::from(self.length_count)]
}
pub const fn phase(self) -> f32 {
self.phase
}
pub const fn max_subsegments(self) -> usize {
self.max_subsegments
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StrokeMarkerAnchor2d {
BaseAtEndpoint,
TipAtEndpoint,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct StrokeMarker2d {
length: LogicalPixels,
width: LogicalPixels,
anchor: StrokeMarkerAnchor2d,
}
impl StrokeMarker2d {
pub const fn arrow(length: LogicalPixels, width: LogicalPixels) -> Self {
Self {
length,
width,
anchor: StrokeMarkerAnchor2d::BaseAtEndpoint,
}
}
pub const fn with_anchor(mut self, anchor: StrokeMarkerAnchor2d) -> Self {
self.anchor = anchor;
self
}
pub const fn anchor(self) -> StrokeMarkerAnchor2d {
self.anchor
}
pub const fn length(self) -> LogicalPixels {
self.length
}
pub const fn width(self) -> LogicalPixels {
self.width
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct StrokeStyle2d {
pub(super) stroke: Stroke,
pub(super) width_mode: StrokeWidthMode2d,
pub(super) cap: StrokeCap2d,
pub(super) join: StrokeJoin2d,
pub(super) miter_limit: f32,
pub(super) dash: Option<StrokeDashPattern2d>,
pub(super) start_marker: Option<StrokeMarker2d>,
pub(super) end_marker: Option<StrokeMarker2d>,
}
impl StrokeStyle2d {
pub const fn new(width: f32, color: Color) -> Self {
Self {
stroke: Stroke::new(width, color),
width_mode: StrokeWidthMode2d::LogicalPixels,
cap: StrokeCap2d::Round,
join: StrokeJoin2d::Miter,
miter_limit: MAX_MITER_LIMIT,
dash: None,
start_marker: None,
end_marker: None,
}
}
pub const fn logical(width: LogicalPixels, color: Color) -> Self {
Self::new(width.get(), color)
}
pub const fn world(width: WorldLength, color: Color) -> Self {
let mut style = Self::new(width.get(), color);
style.width_mode = StrokeWidthMode2d::WorldUnits;
style
}
pub const fn with_cap(mut self, cap: StrokeCap2d) -> Self {
self.cap = cap;
self
}
pub const fn with_join(mut self, join: StrokeJoin2d) -> Self {
self.join = join;
self
}
pub fn with_miter_limit(mut self, limit: f32) -> Result<Self, StrokeStyleError> {
if !limit.is_finite() || !(1.0..=MAX_MITER_LIMIT).contains(&limit) {
return Err(StrokeStyleError::InvalidMiterLimit);
}
self.miter_limit = limit;
Ok(self)
}
pub const fn with_dash_pattern(mut self, dash: StrokeDashPattern2d) -> Self {
self.dash = Some(dash);
self
}
pub const fn with_start_marker(mut self, marker: StrokeMarker2d) -> Self {
self.start_marker = Some(marker);
self
}
pub const fn with_end_marker(mut self, marker: StrokeMarker2d) -> Self {
self.end_marker = Some(marker);
self
}
pub const fn stroke(self) -> Stroke {
self.stroke
}
pub const fn width_mode(self) -> StrokeWidthMode2d {
self.width_mode
}
pub const fn cap(self) -> StrokeCap2d {
self.cap
}
pub const fn join(self) -> StrokeJoin2d {
self.join
}
pub const fn miter_limit(self) -> f32 {
self.miter_limit
}
pub const fn dash_pattern(self) -> Option<StrokeDashPattern2d> {
self.dash
}
pub const fn start_marker(self) -> Option<StrokeMarker2d> {
self.start_marker
}
pub const fn end_marker(self) -> Option<StrokeMarker2d> {
self.end_marker
}
pub(crate) fn has_tip_marker(self) -> bool {
[self.start_marker, self.end_marker]
.into_iter()
.flatten()
.any(|marker| marker.anchor == StrokeMarkerAnchor2d::TipAtEndpoint)
}
pub(super) fn is_valid(self) -> bool {
self.stroke.is_valid()
&& self.miter_limit.is_finite()
&& (1.0..=MAX_MITER_LIMIT).contains(&self.miter_limit)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StrokeStyleError {
InvalidDashElementCount,
InvalidDashLength,
InvalidDashPhase,
InvalidDashExpansionLimit,
InvalidMiterLimit,
}
impl fmt::Display for StrokeStyleError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(formatter, "invalid bounded 2D stroke style: {self:?}")
}
}
impl Error for StrokeStyleError {}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ShapeStyle {
pub(super) fill: Option<Fill>,
pub(super) stroke: Option<Stroke>,
pub(super) shadow: Option<Shadow>,
}
impl ShapeStyle {
pub const fn new(fill: Option<Fill>, stroke: Option<Stroke>, shadow: Option<Shadow>) -> Self {
Self {
fill,
stroke,
shadow,
}
}
pub const fn fill(self) -> Option<Fill> {
self.fill
}
pub const fn stroke(self) -> Option<Stroke> {
self.stroke
}
pub const fn shadow(self) -> Option<Shadow> {
self.shadow
}
pub fn filled(color: Color) -> Self {
Self::filled_with(Fill::Solid(color))
}
pub fn filled_with(fill: Fill) -> Self {
Self {
fill: Some(fill),
stroke: None,
shadow: None,
}
}
pub fn stroked(width: f32, color: Color) -> Self {
Self {
fill: None,
stroke: Some(Stroke { width, color }),
shadow: None,
}
}
pub fn fill_stroke(fill: Color, stroke_width: f32, stroke: Color) -> Self {
Self::fill_stroke_with(Fill::Solid(fill), stroke_width, stroke)
}
pub fn fill_stroke_with(fill: Fill, stroke_width: f32, stroke: Color) -> Self {
Self {
fill: Some(fill),
stroke: Some(Stroke {
width: stroke_width,
color: stroke,
}),
shadow: None,
}
}
pub fn with_shadow(mut self, shadow: Shadow) -> Self {
self.shadow = Some(shadow);
self
}
pub(super) fn validate(self, primitive: ScenePrimitive) -> Result<(), SceneError> {
if self.fill.is_none() && self.stroke.is_none() && self.shadow.is_none() {
return Err(SceneError::MissingStyle(primitive));
}
if self.fill.is_some_and(|fill| !fill.is_valid()) {
return Err(SceneError::InvalidFill(primitive));
}
if self.stroke.is_some_and(|stroke| !stroke.is_valid()) {
return Err(SceneError::InvalidStroke(primitive));
}
if self.shadow.is_some_and(|shadow| !shadow.is_valid()) {
return Err(SceneError::InvalidShadow(primitive));
}
Ok(())
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Fill {
Solid(Color),
LinearGradient(LinearGradient),
RadialGradient(RadialGradient),
}
impl Fill {
pub fn color_at(self, world: Vec2) -> Color {
self.color_at_with_offset(world, Vec2::ZERO)
}
pub(crate) fn color_at_with_offset(self, world_base: Vec2, world_offset: Vec2) -> Color {
match self {
Self::Solid(color) => color,
Self::LinearGradient(gradient) => {
gradient.color_at_with_offset(world_base, world_offset)
}
Self::RadialGradient(gradient) => {
gradient.color_at_with_offset(world_base, world_offset)
}
}
}
fn is_valid(self) -> bool {
match self {
Self::Solid(color) => color.is_normalized(),
Self::LinearGradient(gradient) => gradient.is_valid(),
Self::RadialGradient(gradient) => gradient.is_valid(),
}
}
}
impl From<Color> for Fill {
fn from(color: Color) -> Self {
Self::Solid(color)
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct LinearGradient {
start: Vec2,
end: Vec2,
start_color: Color,
end_color: Color,
}
impl LinearGradient {
pub fn new(start: Vec2, end: Vec2, start_color: Color, end_color: Color) -> Self {
Self {
start,
end,
start_color,
end_color,
}
}
pub const fn start(self) -> Vec2 {
self.start
}
pub const fn end(self) -> Vec2 {
self.end
}
pub const fn start_color(self) -> Color {
self.start_color
}
pub const fn end_color(self) -> Color {
self.end_color
}
pub fn color_at(self, world: Vec2) -> Color {
self.color_at_with_offset(world, Vec2::ZERO)
}
fn color_at_with_offset(self, world_base: Vec2, world_offset: Vec2) -> Color {
if !self.is_valid() || !world_base.is_finite() || !world_offset.is_finite() {
return self.end_color.clamp();
}
let axis_x = f64::from(self.end.x) - f64::from(self.start.x);
let axis_y = f64::from(self.end.y) - f64::from(self.start.y);
let relative_x =
f64::from(world_base.x) - f64::from(self.start.x) + f64::from(world_offset.x);
let relative_y =
f64::from(world_base.y) - f64::from(self.start.y) + f64::from(world_offset.y);
let axis_length_squared = axis_x * axis_x + axis_y * axis_y;
let amount = ((relative_x * axis_x + relative_y * axis_y) / axis_length_squared)
.clamp(0.0, 1.0) as f32;
self.start_color.interpolate(self.end_color, amount)
}
fn is_valid(self) -> bool {
self.start.is_finite()
&& self.end.is_finite()
&& self.start_color.is_normalized()
&& self.end_color.is_normalized()
&& self.start != self.end
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct RadialGradient {
center: Vec2,
inner_radius: f32,
outer_radius: f32,
inner_color: Color,
outer_color: Color,
}
impl RadialGradient {
pub fn new(
center: Vec2,
inner_radius: f32,
outer_radius: f32,
inner_color: Color,
outer_color: Color,
) -> Self {
if inner_radius.is_finite() && outer_radius.is_finite() && inner_radius > outer_radius {
Self {
center,
inner_radius: outer_radius,
outer_radius: inner_radius,
inner_color: outer_color,
outer_color: inner_color,
}
} else {
Self {
center,
inner_radius,
outer_radius,
inner_color,
outer_color,
}
}
}
pub const fn center(self) -> Vec2 {
self.center
}
pub const fn inner_radius(self) -> f32 {
self.inner_radius
}
pub const fn outer_radius(self) -> f32 {
self.outer_radius
}
pub const fn inner_color(self) -> Color {
self.inner_color
}
pub const fn outer_color(self) -> Color {
self.outer_color
}
pub fn color_at(self, world: Vec2) -> Color {
self.color_at_with_offset(world, Vec2::ZERO)
}
fn color_at_with_offset(self, world_base: Vec2, world_offset: Vec2) -> Color {
if !self.is_valid() || !world_base.is_finite() || !world_offset.is_finite() {
return self.outer_color.clamp();
}
let radius_range = self.outer_radius - self.inner_radius;
if radius_range == 0.0 {
return self.outer_color;
}
let horizontal =
f64::from(world_base.x) - f64::from(self.center.x) + f64::from(world_offset.x);
let vertical =
f64::from(world_base.y) - f64::from(self.center.y) + f64::from(world_offset.y);
let distance = horizontal.hypot(vertical);
let amount = ((distance - f64::from(self.inner_radius)) / f64::from(radius_range))
.clamp(0.0, 1.0) as f32;
self.inner_color.interpolate(self.outer_color, amount)
}
fn is_valid(self) -> bool {
self.center.is_finite()
&& self.inner_radius.is_finite()
&& self.outer_radius.is_finite()
&& self.inner_radius >= 0.0
&& self.outer_radius >= self.inner_radius
&& self.inner_color.is_normalized()
&& self.outer_color.is_normalized()
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Stroke {
pub(super) width: f32,
color: Color,
}
impl Stroke {
pub const fn new(width: f32, color: Color) -> Self {
Self { width, color }
}
pub const fn width(self) -> f32 {
self.width
}
pub const fn color(self) -> Color {
self.color
}
fn is_valid(self) -> bool {
self.width.is_finite() && self.width > 0.0 && self.color.is_normalized()
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Shadow {
offset: LogicalScreenVector,
pub(super) spread: f32,
color: Color,
}
impl Shadow {
pub fn new(offset: LogicalScreenVector, spread: f32, color: Color) -> Self {
Self {
offset,
spread,
color,
}
}
pub const fn offset(self) -> LogicalScreenVector {
self.offset
}
pub const fn spread(self) -> f32 {
self.spread
}
pub const fn color(self) -> Color {
self.color
}
fn is_valid(self) -> bool {
self.offset.is_finite()
&& self.spread.is_finite()
&& self.spread >= 0.0
&& (self.spread * 2.0).is_finite()
&& self.color.is_normalized()
}
}