use crate::geometry::{Color, Point, Rect, Transform, Vec2};
use crate::render::Renderer;
use crate::text::{RichSpan, TextLayout};
use kurbo::BezPath;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ObjectFit {
#[default]
Contain,
Cover,
Fill,
None,
}
#[derive(Debug, Clone)]
pub struct SceneImage {
pub pixmap: crate::Pixmap,
pub object_fit: ObjectFit,
}
impl SceneImage {
#[must_use]
pub fn from_pixmap(pixmap: crate::Pixmap) -> Self {
Self {
pixmap,
object_fit: ObjectFit::Contain,
}
}
#[must_use]
pub fn from_rgba8(
width: u32,
height: u32,
pixels: impl Into<std::sync::Arc<[u8]>>,
) -> Option<Self> {
crate::Pixmap::from_rgba8(width, height, pixels).map(Self::from_pixmap)
}
#[must_use]
pub fn from_png(bytes: &[u8]) -> Option<Self> {
crate::Pixmap::decode_png(bytes).map(Self::from_pixmap)
}
#[cfg(feature = "extra-image-codecs")]
#[must_use]
pub fn from_encoded(bytes: &[u8]) -> Option<Self> {
let dyn_img = image::load_from_memory(bytes).ok()?;
let rgba = dyn_img.to_rgba8();
let (w, h) = rgba.dimensions();
Self::from_rgba8(w, h, rgba.into_raw())
}
#[must_use]
pub fn width(&self) -> u32 {
self.pixmap.width()
}
#[must_use]
pub fn height(&self) -> u32 {
self.pixmap.height()
}
#[must_use]
pub fn with_object_fit(mut self, fit: ObjectFit) -> Self {
self.object_fit = fit;
self
}
#[must_use]
pub fn preserve_aspect_ratio(&self) -> &'static str {
match self.object_fit {
ObjectFit::Contain => "xMidYMid meet",
ObjectFit::Cover => "xMidYMid slice",
ObjectFit::Fill => "none",
ObjectFit::None => "none",
}
}
}
#[derive(Debug, Clone)]
pub struct Scene {
pub width: f64,
pub height: f64,
pub background: Color,
pub nodes: Vec<SceneNode>,
pub layers: Vec<Layer>,
pub title: Option<String>,
pub description: Option<String>,
pub scale: f64,
}
impl Default for Scene {
fn default() -> Self {
Self {
width: 0.0,
height: 0.0,
background: Color::WHITE,
nodes: Vec::new(),
layers: Vec::new(),
title: None,
description: None,
scale: 1.0,
}
}
}
impl Scene {
pub fn new(width: f64, height: f64) -> Self {
Self {
width,
height,
background: Color::WHITE,
nodes: Vec::new(),
layers: Vec::new(),
title: None,
description: None,
scale: 1.0,
}
}
#[must_use]
pub fn with_background(mut self, bg: Color) -> Self {
self.background = bg;
self
}
#[must_use]
pub fn with_title(mut self, title: impl Into<String>) -> Self {
self.title = Some(title.into());
self
}
#[must_use]
pub fn with_description(mut self, description: impl Into<String>) -> Self {
self.description = Some(description.into());
self
}
#[must_use]
pub fn with_scale(mut self, scale: f64) -> Self {
self.scale = scale;
self
}
pub fn push(&mut self, node: impl Into<SceneNode>) {
self.nodes.push(node.into());
}
pub fn push_node(&mut self, node: SceneNode) {
self.nodes.push(node);
}
pub fn push_group(&mut self, children: Vec<SceneNode>) {
self.nodes.push(SceneNode::group(children));
}
pub fn push_layer(&mut self, layer: Layer) {
self.layers.push(layer);
}
pub fn layers(&self) -> &[Layer] {
&self.layers
}
pub fn layer(&self, name: &str) -> Option<&Layer> {
self.layers.iter().find(|l| l.name == name)
}
pub fn layer_mut(&mut self, name: &str) -> Option<&mut Layer> {
self.layers.iter_mut().find(|l| l.name == name)
}
pub fn render(&self, renderer: &mut dyn Renderer) {
renderer.render_scene(self);
}
pub fn iter_ordered(&self) -> impl Iterator<Item = &SceneNode> {
SceneNode::ordered(&self.nodes)
}
}
#[derive(Debug, Clone)]
pub struct Layer {
pub name: String,
pub visible: bool,
pub opacity: f64,
pub transform: Option<Transform>,
pub nodes: Vec<SceneNode>,
}
impl Layer {
pub fn new(name: impl Into<String>) -> Self {
Self {
name: name.into(),
visible: true,
opacity: 1.0,
transform: None,
nodes: Vec::new(),
}
}
pub fn with_nodes(mut self, nodes: Vec<SceneNode>) -> Self {
self.nodes = nodes;
self
}
pub fn push(&mut self, node: impl Into<SceneNode>) {
self.nodes.push(node.into());
}
pub fn push_node(&mut self, node: SceneNode) {
self.nodes.push(node);
}
pub fn push_group(&mut self, children: Vec<SceneNode>) {
self.nodes.push(SceneNode::group(children));
}
pub fn iter_ordered(&self) -> impl Iterator<Item = &SceneNode> {
SceneNode::ordered(&self.nodes)
}
#[must_use]
pub fn with_name(mut self, name: impl Into<String>) -> Self {
self.name = name.into();
self
}
#[must_use]
pub fn with_visible(mut self, visible: bool) -> Self {
self.visible = visible;
self
}
#[must_use]
pub fn with_opacity(mut self, opacity: f64) -> Self {
self.opacity = opacity.clamp(0.0, 1.0);
self
}
#[must_use]
pub fn with_transform(mut self, t: Transform) -> Self {
self.transform = Some(t);
self
}
}
#[derive(Debug, Clone)]
pub struct SceneNode {
pub element: Element,
pub z_index: i32,
pub transform: Option<Transform>,
pub opacity: f64,
pub name: Option<String>,
pub visible: bool,
pub clip: Option<Clip>,
}
impl SceneNode {
pub fn new(element: Element) -> Self {
Self {
element,
z_index: 0,
transform: None,
opacity: 1.0,
name: None,
visible: true,
clip: None,
}
}
pub fn group(children: Vec<SceneNode>) -> Self {
Self {
element: Element::Group { children },
z_index: 0,
transform: None,
opacity: 1.0,
name: None,
visible: true,
clip: None,
}
}
pub fn ordered(nodes: &[SceneNode]) -> impl Iterator<Item = &SceneNode> {
let mut order: Vec<usize> = (0..nodes.len()).collect();
order.sort_by_key(|&i| nodes[i].z_index);
order.into_iter().map(move |i| &nodes[i])
}
#[must_use]
pub fn with_z(mut self, z: i32) -> Self {
self.z_index = z;
self
}
#[must_use]
pub fn with_transform(mut self, t: Transform) -> Self {
self.transform = Some(t);
self
}
#[must_use]
pub fn with_opacity(mut self, opacity: f64) -> Self {
self.opacity = opacity.clamp(0.0, 1.0);
self
}
#[must_use]
pub fn with_name(mut self, name: impl Into<String>) -> Self {
self.name = Some(name.into());
self
}
#[must_use]
pub fn with_visible(mut self, visible: bool) -> Self {
self.visible = visible;
self
}
#[must_use]
pub fn with_clip(mut self, clip: Clip) -> Self {
self.clip = Some(clip);
self
}
}
impl From<Element> for SceneNode {
fn from(element: Element) -> Self {
SceneNode::new(element)
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum Clip {
Rect(Rect),
RoundedRect { rect: Rect, radius: f64 },
Circle { center: Point, radius: f64 },
Ellipse {
center: Point,
radii: Vec2,
rotation: f64,
},
Path(BezPath),
}
impl Clip {
#[must_use]
pub fn rect(rect: Rect) -> Self {
Self::Rect(rect)
}
#[must_use]
pub fn rounded_rect(rect: Rect, radius: f64) -> Self {
Self::RoundedRect { rect, radius }
}
#[must_use]
pub fn circle(center: Point, radius: f64) -> Self {
Self::Circle { center, radius }
}
#[must_use]
pub fn ellipse(center: Point, radii: Vec2, rotation: f64) -> Self {
Self::Ellipse {
center,
radii,
rotation,
}
}
#[must_use]
pub fn path(path: BezPath) -> Self {
Self::Path(path)
}
#[must_use]
pub fn to_bezpath(&self) -> BezPath {
use kurbo::Shape;
match self {
Clip::Rect(rect) => {
let mut p = BezPath::new();
p.move_to((rect.min_x(), rect.min_y()));
p.line_to((rect.max_x(), rect.min_y()));
p.line_to((rect.max_x(), rect.max_y()));
p.line_to((rect.min_x(), rect.max_y()));
p.close_path();
p
}
Clip::RoundedRect { rect, radius } => kurbo::RoundedRect::new(
rect.min_x(),
rect.min_y(),
rect.max_x(),
rect.max_y(),
*radius,
)
.to_path(0.1),
Clip::Circle { center, radius } => {
kurbo::Circle::new((center.x, center.y), *radius).to_path(0.1)
}
Clip::Ellipse {
center,
radii,
rotation,
} => kurbo::Ellipse::new((center.x, center.y), (radii.x, radii.y), *rotation)
.to_path(0.1),
Clip::Path(path) => path.clone(),
}
}
}
#[derive(Debug, Clone, PartialEq, Default)]
pub struct FillStrokeStyle {
pub fill: Option<Fill>,
pub stroke: Option<Stroke>,
}
impl FillStrokeStyle {
#[must_use]
pub fn fill(color: Color) -> Self {
Self {
fill: Some(Fill::Solid(color)),
stroke: None,
}
}
#[must_use]
pub fn fill_gradient(gradient: impl Into<Fill>) -> Self {
Self {
fill: Some(gradient.into()),
stroke: None,
}
}
#[must_use]
pub fn stroke(color: Color, width: f64) -> Self {
Self {
fill: None,
stroke: Some(Stroke {
color,
width,
..Default::default()
}),
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum Fill {
Solid(Color),
LinearGradient(LinearGradient),
RadialGradient(RadialGradient),
}
impl From<Color> for Fill {
fn from(c: Color) -> Self {
Self::Solid(c)
}
}
impl From<LinearGradient> for Fill {
fn from(g: LinearGradient) -> Self {
Self::LinearGradient(g)
}
}
impl From<RadialGradient> for Fill {
fn from(g: RadialGradient) -> Self {
Self::RadialGradient(g)
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct LinearGradient {
pub start: Point,
pub end: Point,
pub stops: Vec<GradientStop>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct RadialGradient {
pub center: Point,
pub radius: f64,
pub stops: Vec<GradientStop>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct GradientStop {
pub offset: f64,
pub color: Color,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Stroke {
pub color: Color,
pub width: f64,
pub line_cap: LineCap,
pub line_join: LineJoin,
pub dash_array: Vec<f64>,
pub dash_offset: f64,
pub miter_limit: f64,
}
impl Default for Stroke {
fn default() -> Self {
Self {
color: Color::default(),
width: 0.0,
line_cap: LineCap::default(),
line_join: LineJoin::default(),
dash_array: Vec::new(),
dash_offset: 0.0,
miter_limit: 10.0,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum LineCap {
#[default]
Butt,
Round,
Square,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum LineJoin {
#[default]
Miter,
Round,
Bevel,
}
impl Stroke {
#[must_use]
pub fn new(color: Color, width: f64) -> Self {
Self {
color,
width,
..Default::default()
}
}
#[must_use]
pub fn dashed(color: Color, width: f64, dash_array: Vec<f64>) -> Self {
Self {
color,
width,
dash_array,
..Default::default()
}
}
}
#[derive(Debug, Clone)]
pub enum Element {
Rect {
rect: Rect,
style: FillStrokeStyle,
},
Circle {
center: Point,
radius: f64,
style: FillStrokeStyle,
},
Ellipse {
center: Point,
radii: Vec2,
rotation: f64,
style: FillStrokeStyle,
},
RoundedRect {
rect: Rect,
radius: f64,
style: FillStrokeStyle,
},
Line {
start: Point,
end: Point,
style: Stroke,
},
Polyline {
points: Vec<Point>,
style: Stroke,
},
Polygon {
points: Vec<Point>,
style: FillStrokeStyle,
},
Arc {
center: Point,
radii: Vec2,
start_angle: f64,
sweep_angle: f64,
style: Stroke,
},
Pie {
center: Point,
radius: f64,
start_angle: f64,
sweep_angle: f64,
style: FillStrokeStyle,
},
Path {
path: BezPath,
style: FillStrokeStyle,
closed: bool,
},
Image {
image: SceneImage,
frame: Rect,
opacity: f64,
},
GradientPath {
path: BezPath,
gradient: LinearGradient,
stroke: Option<Stroke>,
},
Text {
spans: Vec<RichSpan>,
position: Point,
style: crate::text::TextStyle,
layout: Option<std::sync::Arc<TextLayout>>,
},
Group {
children: Vec<SceneNode>,
},
}
impl Element {
#[must_use]
pub fn rect(rect: Rect, style: FillStrokeStyle) -> Self {
Self::Rect { rect, style }
}
#[must_use]
pub fn circle(center: Point, radius: f64, style: FillStrokeStyle) -> Self {
Self::Circle {
center,
radius,
style,
}
}
#[must_use]
pub fn ellipse(center: Point, radii: Vec2, rotation: f64, style: FillStrokeStyle) -> Self {
Self::Ellipse {
center,
radii,
rotation,
style,
}
}
#[must_use]
pub fn rounded_rect(rect: Rect, radius: f64, style: FillStrokeStyle) -> Self {
Self::RoundedRect {
rect,
radius,
style,
}
}
#[must_use]
pub fn line(start: Point, end: Point, style: Stroke) -> Self {
Self::Line { start, end, style }
}
#[must_use]
pub fn poly(points: Vec<Point>, style: Stroke) -> Self {
Self::Polyline {
points,
style,
}
}
#[must_use]
pub fn polygon(points: Vec<Point>, style: FillStrokeStyle) -> Self {
Self::Polygon { points, style }
}
#[must_use]
pub fn arc(
center: Point,
radii: Vec2,
start_angle: f64,
sweep_angle: f64,
style: Stroke,
) -> Self {
Self::Arc {
center,
radii,
start_angle,
sweep_angle,
style,
}
}
#[must_use]
pub fn pie(
center: Point,
radius: f64,
start_angle: f64,
sweep_angle: f64,
style: FillStrokeStyle,
) -> Self {
Self::Pie {
center,
radius,
start_angle,
sweep_angle,
style,
}
}
#[must_use]
pub fn text(
content: impl Into<String>,
position: Point,
style: crate::text::TextStyle,
) -> Self {
Self::Text {
spans: vec![RichSpan::new(content, style.clone())],
position,
style,
layout: None,
}
}
#[must_use]
pub fn rich_text(spans: Vec<RichSpan>, position: Point, style: crate::text::TextStyle) -> Self {
Self::Text {
spans,
position,
style,
layout: None,
}
}
#[must_use]
pub fn image(image: SceneImage, frame: Rect) -> Self {
Self::Image {
image,
frame,
opacity: 1.0,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn rect_node(x: f64, z: i32) -> SceneNode {
SceneNode::new(Element::rect(
Rect::new(x, 0.0, x + 1.0, 1.0),
FillStrokeStyle::fill(Color::BLACK),
))
.with_z(z)
}
fn rect_x(node: &SceneNode) -> f64 {
match &node.element {
Element::Rect { rect, .. } => rect.min_x(),
_ => panic!("expected rect"),
}
}
mod element {
use super::*;
#[test]
fn push_accepts_element_and_scene_node() {
let mut scene = Scene::new(100.0, 100.0);
scene.push(Element::rect(
Rect::new(0.0, 0.0, 1.0, 1.0),
FillStrokeStyle::fill(Color::BLACK),
));
scene.push(SceneNode::new(Element::rect(
Rect::new(0.0, 0.0, 1.0, 1.0),
FillStrokeStyle::fill(Color::BLACK),
)));
assert_eq!(scene.nodes.len(), 2);
}
#[test]
fn builder_chaining() {
let node = SceneNode::new(Element::circle(
Point::new(1.0, 2.0),
3.0,
FillStrokeStyle::stroke(Color::BLACK, 1.0),
))
.with_z(7)
.with_transform(Transform::translate(1.0, 2.0))
.with_opacity(0.5)
.with_name("node-a")
.with_visible(false);
assert_eq!(node.z_index, 7);
assert_eq!(node.transform, Some(Transform::translate(1.0, 2.0)));
assert_eq!(node.opacity, 0.5);
assert_eq!(node.name.as_deref(), Some("node-a"));
assert!(!node.visible);
}
#[test]
fn node_defaults() {
let node = SceneNode::new(Element::rect(
Rect::new(0.0, 0.0, 1.0, 1.0),
FillStrokeStyle::fill(Color::BLACK),
));
assert_eq!(node.opacity, 1.0);
assert!(node.name.is_none());
assert!(node.visible);
}
#[test]
fn from_element_conversion() {
let node: SceneNode = Element::line(
Point::new(0.0, 0.0),
Point::new(1.0, 1.0),
Stroke::new(Color::BLACK, 1.0),
)
.into();
assert_eq!(node.z_index, 0);
assert!(node.transform.is_none());
}
#[test]
fn element_constructors() {
let r = Element::rect(
Rect::new(0.0, 0.0, 10.0, 10.0),
FillStrokeStyle::fill(Color::BLACK),
);
assert!(matches!(r, Element::Rect { .. }));
let c = Element::circle(
Point::new(1.0, 2.0),
3.0,
FillStrokeStyle::fill(Color::BLACK),
);
assert!(matches!(c, Element::Circle { .. }));
let e = Element::ellipse(
Point::new(1.0, 2.0),
Vec2::new(4.0, 2.0),
0.1,
FillStrokeStyle::fill(Color::BLACK),
);
assert!(matches!(e, Element::Ellipse { .. }));
let rr = Element::rounded_rect(
Rect::new(0.0, 0.0, 10.0, 10.0),
3.0,
FillStrokeStyle::fill(Color::BLACK),
);
assert!(matches!(rr, Element::RoundedRect { .. }));
let l = Element::line(
Point::new(0.0, 0.0),
Point::new(1.0, 1.0),
Stroke::new(Color::BLACK, 1.0),
);
assert!(matches!(l, Element::Line { .. }));
let p = Element::poly(
vec![Point::new(0.0, 0.0), Point::new(1.0, 1.0)],
Stroke::new(Color::BLACK, 1.0),
);
assert!(matches!(p, Element::Polyline { .. }));
let pg = Element::polygon(
vec![
Point::new(0.0, 0.0),
Point::new(1.0, 1.0),
Point::new(0.0, 1.0),
],
FillStrokeStyle::fill(Color::BLACK),
);
assert!(matches!(pg, Element::Polygon { .. }));
let a = Element::arc(
Point::new(0.0, 0.0),
Vec2::new(5.0, 5.0),
0.0,
std::f64::consts::FRAC_PI_2,
Stroke::new(Color::BLACK, 1.0),
);
assert!(matches!(a, Element::Arc { .. }));
let pie = Element::pie(
Point::new(0.0, 0.0),
5.0,
0.0,
std::f64::consts::FRAC_PI_2,
FillStrokeStyle::fill(Color::BLACK),
);
assert!(matches!(pie, Element::Pie { .. }));
let t = Element::text(
"hi",
Point::new(0.0, 0.0),
crate::text::TextStyle::new(Color::BLACK, 12.0, "sans-serif"),
);
match t {
Element::Text {
spans,
position,
style,
layout,
} => {
assert_eq!(spans.len(), 1);
assert_eq!(spans[0].text, "hi");
assert_eq!(position, Point::new(0.0, 0.0));
assert_eq!(style.font_size, 12.0);
assert!(layout.is_none());
}
_ => panic!("expected text"),
}
}
#[test]
fn stroke_dash_and_miter_defaults() {
let s = Stroke::new(Color::BLACK, 2.0);
assert!(s.dash_array.is_empty());
assert_eq!(s.dash_offset, 0.0);
assert_eq!(s.miter_limit, 10.0);
let d = Stroke::dashed(Color::BLACK, 2.0, vec![4.0, 2.0]);
assert_eq!(d.dash_array, vec![4.0, 2.0]);
}
#[test]
fn radial_gradient_into_fill() {
let g = RadialGradient {
center: Point::new(0.0, 0.0),
radius: 10.0,
stops: vec![
GradientStop {
offset: 0.0,
color: Color::BLACK,
},
GradientStop {
offset: 1.0,
color: Color::WHITE,
},
],
};
let style = FillStrokeStyle::fill_gradient(g);
assert!(matches!(style.fill, Some(Fill::RadialGradient(_))));
}
#[test]
fn rect_center_helper() {
assert_eq!(
Rect::new(2.0, 4.0, 12.0, 10.0).center(),
Point::new(7.0, 7.0)
);
}
#[test]
fn clip_constructors_and_bezpath() {
let c = Clip::circle(Point::new(1.0, 2.0), 5.0);
assert!(matches!(c, Clip::Circle { radius: 5.0, .. }));
let p = c.to_bezpath();
assert!(!p.is_empty());
let r = Clip::rect(Rect::new(0.0, 0.0, 10.0, 20.0));
assert!(matches!(r, Clip::Rect(_)));
assert!(!r.to_bezpath().is_empty());
let rr = Clip::rounded_rect(Rect::new(0.0, 0.0, 10.0, 10.0), 2.0);
assert!(matches!(rr, Clip::RoundedRect { .. }));
let e = Clip::ellipse(Point::new(0.0, 0.0), Vec2::new(3.0, 4.0), 0.0);
assert!(matches!(e, Clip::Ellipse { .. }));
let mut bp = BezPath::new();
bp.move_to((0.0, 0.0));
bp.line_to((1.0, 0.0));
let p2 = Clip::path(bp);
assert!(matches!(p2, Clip::Path(_)));
assert!(!p2.to_bezpath().is_empty());
}
#[test]
fn scene_node_clip_builder() {
let node = SceneNode::new(Element::rect(
Rect::new(0.0, 0.0, 10.0, 10.0),
FillStrokeStyle::fill(Color::BLACK),
))
.with_clip(Clip::circle(Point::new(5.0, 5.0), 3.0));
assert!(node.clip.is_some());
let n = SceneNode::new(Element::rect(
Rect::new(0.0, 0.0, 1.0, 1.0),
FillStrokeStyle::fill(Color::BLACK),
));
assert!(n.clip.is_none());
}
}
mod ordering {
use super::*;
#[test]
fn iter_ordered_sorts_z_ascending() {
let mut scene = Scene::new(100.0, 100.0);
scene.push_node(rect_node(0.0, 5));
scene.push_node(rect_node(0.0, -3));
scene.push_node(rect_node(0.0, 1));
let zs: Vec<i32> = scene.iter_ordered().map(|n| n.z_index).collect();
assert_eq!(zs, vec![-3, 1, 5]);
}
#[test]
fn ordered_is_stable_within_same_z() {
let nodes = vec![rect_node(10.0, 0), rect_node(20.0, 0), rect_node(30.0, 0)];
let xs: Vec<f64> = SceneNode::ordered(&nodes).map(rect_x).collect();
assert_eq!(xs, vec![10.0, 20.0, 30.0]);
}
#[test]
fn layer_iter_ordered_sorts_within_layer() {
let layer = Layer::new("l").with_nodes(vec![
rect_node(0.0, 5),
rect_node(0.0, -2),
rect_node(0.0, 1),
]);
let zs: Vec<i32> = layer.iter_ordered().map(|n| n.z_index).collect();
assert_eq!(zs, vec![-2, 1, 5]);
}
}
mod scene {
use super::*;
#[test]
fn scene_metadata_defaults_and_builders() {
let scene = Scene::new(10.0, 20.0)
.with_title("图表")
.with_description("示例")
.with_scale(2.0);
assert_eq!(scene.title.as_deref(), Some("图表"));
assert_eq!(scene.description.as_deref(), Some("示例"));
assert_eq!(scene.scale, 2.0);
let d = Scene::default();
assert_eq!(d.scale, 1.0);
}
#[test]
fn scene_node_group_and_push_group() {
let group = SceneNode::group(vec![rect_node(0.0, 0), rect_node(0.0, 1)]);
match &group.element {
Element::Group { children } => assert_eq!(children.len(), 2),
_ => panic!("expected group"),
}
let mut scene = Scene::new(10.0, 10.0);
scene.push_group(vec![rect_node(0.0, 0)]);
assert!(matches!(&scene.nodes[0].element, Element::Group { .. }));
}
#[test]
fn scene_push_layer_and_lookup() {
let mut scene = Scene::new(100.0, 100.0);
scene.push_layer(Layer::new("grid"));
scene.push_layer(Layer::new("data").with_nodes(vec![rect_node(0.0, 0)]));
assert_eq!(scene.layers().len(), 2);
assert!(scene.layer("data").is_some());
assert!(scene.layer("missing").is_none());
scene.layer_mut("grid").unwrap().visible = false;
assert!(!scene.layers[0].visible);
}
#[test]
fn scene_default_has_empty_layers() {
let scene = Scene::new(10.0, 10.0);
assert!(scene.layers.is_empty());
}
}
mod layer {
use super::*;
#[test]
fn layer_defaults_and_builders() {
let layer = Layer::new("data").with_nodes(vec![rect_node(0.0, 1)]);
assert_eq!(layer.name, "data");
assert!(layer.visible);
assert_eq!(layer.opacity, 1.0);
assert!(layer.transform.is_none());
assert_eq!(layer.nodes.len(), 1);
let l2 = Layer::new("x")
.with_visible(false)
.with_opacity(0.5)
.with_transform(Transform::translate(1.0, 2.0));
assert!(!l2.visible);
assert_eq!(l2.opacity, 0.5);
assert_eq!(l2.transform, Some(Transform::translate(1.0, 2.0)));
}
}
mod image {
use super::*;
fn img(w: u32, h: u32) -> SceneImage {
let px = vec![0u8; (w * h * 4) as usize];
SceneImage::from_rgba8(w, h, px).unwrap()
}
#[test]
fn preserve_aspect_ratio_mapping() {
let base = img(10, 10);
assert_eq!(base.preserve_aspect_ratio(), "xMidYMid meet");
assert_eq!(
base.clone()
.with_object_fit(ObjectFit::Cover)
.preserve_aspect_ratio(),
"xMidYMid slice"
);
assert_eq!(
base.clone()
.with_object_fit(ObjectFit::Fill)
.preserve_aspect_ratio(),
"none"
);
assert_eq!(
base.clone()
.with_object_fit(ObjectFit::None)
.preserve_aspect_ratio(),
"none"
);
}
#[test]
fn default_object_fit_is_contain() {
assert_eq!(img(1, 1).object_fit, ObjectFit::Contain);
}
#[test]
fn from_rgba8_validates_dimensions() {
assert!(SceneImage::from_rgba8(4, 4, vec![0u8; 64]).is_some());
assert!(SceneImage::from_rgba8(4, 4, vec![0u8; 63]).is_none());
}
#[test]
fn from_png_roundtrips() {
let pm = crate::Pixmap::from_rgba8(2, 2, vec![255u8; 16]).unwrap();
let png = pm.to_png();
let img = SceneImage::from_png(&png).expect("有效 PNG 应可解码");
assert_eq!(img.width(), 2);
assert_eq!(img.height(), 2);
assert_eq!(img.pixmap.pixels(), pm.pixels());
}
#[test]
fn image_element_constructs() {
let img = img(4, 4);
let el = Element::image(img, Rect::new(0.0, 0.0, 10.0, 10.0));
match &el {
Element::Image {
image,
frame,
opacity,
} => {
assert_eq!(image.width(), 4);
assert_eq!(image.height(), 4);
assert_eq!(frame.width(), 10.0);
assert_eq!(*opacity, 1.0);
}
_ => panic!("expected image"),
}
}
}
}