Skip to main content

pax_std/drawing/
ellipse.rs

1use kurbo::{Affine, Rect, Shape};
2use pax_engine::api::LocalProperty;
3use pax_engine::*;
4use pax_runtime::api as pax_runtime_api;
5use pax_runtime::api::{use_RefCell, Stroke};
6use pax_runtime::api::{Layer, RenderContext};
7use pax_runtime::BaseInstance;
8use pax_runtime::{ExpandedNode, InstanceFlags, InstanceNode, InstantiationArgs, RuntimeContext};
9
10use_RefCell!();
11use std::rc::Rc;
12
13const ELLIPSE_PATH_ACCURACY: f64 = 0.01;
14
15/// A 2D vector ellipse, which inscribes its bounding box with the specified fill and stroke.
16#[pax]
17#[custom(Default)]
18#[engine_import_path("pax_engine")]
19#[primitive("pax_std::drawing::ellipse::EllipseInstance")]
20pub struct Ellipse {
21    /// Ordered outline layers above the fills, index zero topmost. Empty by default.
22    pub stroke: Property<Vec<Stroke>>,
23    /// Paint painted inside the ellipse.
24    pub fill: Property<Vec<pax_runtime_api::Fill>>,
25}
26
27impl Default for Ellipse {
28    fn default() -> Self {
29        Self {
30            fill: Property::new(vec![pax_runtime_api::Fill::default()]),
31            stroke: Default::default(),
32        }
33    }
34}
35
36// Runtime instance backing `<Ellipse>`.
37pub struct EllipseInstance {
38    base: BaseInstance,
39}
40
41impl InstanceNode for EllipseInstance {
42    fn supports_alpha_source_render(&self) -> bool {
43        true
44    }
45
46    fn instantiate(args: InstantiationArgs) -> Rc<Self>
47    where
48        Self: Sized,
49    {
50        Rc::new(EllipseInstance {
51            base: BaseInstance::new(
52                args,
53                InstanceFlags {
54                    invisible_to_slot: false,
55                    invisible_to_raycasting: false,
56                    layer: Layer::Canvas,
57                    is_component: false,
58                    is_slot: false,
59                },
60            ),
61        })
62    }
63
64    fn handle_mount(
65        self: Rc<Self>,
66        expanded_node: &Rc<ExpandedNode>,
67        context: &Rc<RuntimeContext>,
68    ) {
69        let tab = expanded_node.transform_and_bounds.clone();
70        let (stroke, fill) = expanded_node.with_properties_unwrapped(|properties: &mut Ellipse| {
71            (properties.stroke.local(), properties.fill.local())
72        });
73
74        let appearance =
75            crate::common::watch_appearance(expanded_node, context, fill.clone(), stroke.clone());
76        let deps = &[
77            appearance.untyped(),
78            tab.untyped(),
79            stroke.untyped(),
80            fill.untyped(),
81            expanded_node.computed_opacity.untyped(),
82            expanded_node.computed_opacity_scopes.untyped(),
83        ];
84        let cloned_expanded_node = expanded_node.clone();
85        let cloned_context = context.clone();
86
87        expanded_node
88            .changed_listener
89            .replace_with(LocalProperty::computed(
90                move || {
91                    appearance.get();
92                    cloned_context.mark_canvas_node_dirty(cloned_expanded_node.id);
93                    cloned_context
94                        .set_canvas_dirty(cloned_expanded_node.occlusion.get().render_layer_id)
95                },
96                deps,
97            ));
98    }
99
100    fn resolve_coverage_path(&self, expanded_node: &ExpandedNode) -> Option<kurbo::BezPath> {
101        expanded_node.with_properties_unwrapped(|p: &mut Ellipse| {
102            let tab = expanded_node.transform_and_bounds.get();
103            let rect = Rect::new(0.0, 0.0, tab.bounds.0, tab.bounds.1);
104            Some(
105                Affine::from(tab.transform)
106                    * crate::common::appearance_coverage_path(
107                        &kurbo::Ellipse::from_rect(rect).to_path(ELLIPSE_PATH_ACCURACY),
108                        &p.fill.local().get(),
109                        &p.stroke.local().get(),
110                    ),
111            )
112        })
113    }
114
115    fn resolve_alpha_mask_paints(
116        &self,
117        node: &ExpandedNode,
118    ) -> Vec<pax_runtime_api::AlphaMaskPaint> {
119        node.with_properties_unwrapped(|p: &mut Ellipse| {
120            let (w, h) = node.transform_and_bounds.get().bounds;
121            crate::common::alpha_mask_paints(
122                node,
123                kurbo::Ellipse::from_rect(Rect::new(0.0, 0.0, w, h)).to_path(ELLIPSE_PATH_ACCURACY),
124                p.fill.local().get(),
125                p.stroke.local().get(),
126            )
127        })
128    }
129
130    fn resolve_coverage_opacity(&self, expanded_node: &ExpandedNode) -> f64 {
131        expanded_node.with_properties_unwrapped(|properties: &mut Ellipse| {
132            (crate::common::appearance_coverage_alpha(
133                &properties.fill.local().get(),
134                &properties.stroke.local().get(),
135            ) * expanded_node.computed_opacity.get())
136            .clamp(0.0, 1.0)
137        })
138    }
139
140    fn prepare_canvas_geometry(
141        &self,
142        node: &ExpandedNode,
143    ) -> pax_runtime::scene_geometry::CanvasGeometry {
144        let bounds = node.transform_and_bounds.get().bounds;
145        let local_bounds = node.with_properties_unwrapped(|p: &mut Ellipse| {
146            crate::common::stroke_coverage_bounds(
147                kurbo::Rect::new(0.0, 0.0, bounds.0, bounds.1),
148                &p.stroke.local().get(),
149            )
150        });
151        pax_runtime::scene_geometry::CanvasGeometry {
152            local_bounds: Some(local_bounds),
153            path: None,
154        }
155    }
156
157    fn render(
158        &self,
159        expanded_node: &ExpandedNode,
160        rtc: &Rc<RuntimeContext>,
161        rc: &mut dyn RenderContext,
162    ) {
163        if rc.alpha_source_layer().is_none() && !rtc.is_canvas_node_dirty(&expanded_node.id) {
164            return;
165        }
166
167        let Some(scope) = crate::common::begin_bounded_canvas_node(rc, expanded_node, rtc) else {
168            return;
169        };
170
171        let (width, height) = scope.bounds;
172        expanded_node.with_properties_unwrapped(|properties: &mut Ellipse| {
173            let rect = Rect::from_points((0.0, 0.0), (width, height));
174            let ellipse = kurbo::Ellipse::from_rect(rect);
175            let bez_path = ellipse.to_path(ELLIPSE_PATH_ACCURACY);
176            rc.save(scope.layer_id);
177            rc.transform(scope.layer_id, scope.surface_transform);
178            crate::common::draw_appearance(
179                rc,
180                scope.layer_id,
181                bez_path,
182                &properties.fill.local().get(),
183                &properties.stroke.local().get(),
184                scope.paint_opacity,
185                pax_runtime_api::PathSmoothing::None,
186                0.0,
187                1.0,
188            );
189            rc.restore(scope.layer_id);
190        });
191        if rc.end_node(scope.layer_id, scope.node_id) {
192            rtc.clear_canvas_node_dirty(&expanded_node.id);
193        }
194    }
195
196    fn resolve_debug(
197        &self,
198        f: &mut std::fmt::Formatter,
199        expanded_node: Option<&ExpandedNode>,
200    ) -> std::fmt::Result {
201        match expanded_node {
202            Some(expanded_node) => expanded_node
203                .with_properties_unwrapped(|_e: &mut Ellipse| f.debug_struct("Ellipse").finish()),
204            None => f.debug_struct("Ellipse").finish_non_exhaustive(),
205        }
206    }
207
208    fn base(&self) -> &BaseInstance {
209        &self.base
210    }
211}