Skip to main content

pax_std/drawing/
line.rs

1use kurbo::{Affine, BezPath, Shape};
2use pax_engine::api::Size;
3use pax_engine::*;
4use pax_runtime::api::drawing::stroke_utils::{stroke_width_pixels, stroked_outline_path};
5use pax_runtime::api::{use_RefCell, Layer, Material, RenderContext, Stroke};
6use pax_runtime::BaseInstance;
7use pax_runtime::{ExpandedNode, InstanceFlags, InstanceNode, InstantiationArgs, RuntimeContext};
8
9use crate::common::{begin_bounded_canvas_node, to_kurbo_point};
10
11use_RefCell!();
12use std::rc::Rc;
13
14/// A 2D vector line segment.
15///
16/// `x1`/`y1` and `x2`/`y2` describe the segment endpoints in the primitive's
17/// local coordinate space. The segment is rendered with `stroke`, whose cap
18/// style controls how the two exposed endpoints terminate.
19#[pax]
20#[engine_import_path("pax_engine")]
21#[primitive("pax_std::drawing::line::LineInstance")]
22pub struct Line {
23    /// The x-coordinate of the start point.
24    pub x1: Property<Size>,
25    /// The y-coordinate of the start point.
26    pub y1: Property<Size>,
27    /// The x-coordinate of the end point.
28    pub x2: Property<Size>,
29    /// The y-coordinate of the end point.
30    pub y2: Property<Size>,
31    /// The stroke used to render the segment.
32    pub stroke: Property<Stroke>,
33    /// Light-reactive surface response.
34    pub material: Property<Material>,
35}
36
37// Runtime instance backing `<Line>`.
38pub struct LineInstance {
39    base: BaseInstance,
40}
41
42impl InstanceNode for LineInstance {
43    fn instantiate(args: InstantiationArgs) -> Rc<Self>
44    where
45        Self: Sized,
46    {
47        Rc::new(Self {
48            base: BaseInstance::new(
49                args,
50                InstanceFlags {
51                    invisible_to_slot: false,
52                    invisible_to_raycasting: false,
53                    layer: Layer::Canvas,
54                    is_component: false,
55                    is_slot: false,
56                },
57            ),
58        })
59    }
60
61    fn handle_mount(
62        self: Rc<Self>,
63        expanded_node: &Rc<ExpandedNode>,
64        context: &Rc<RuntimeContext>,
65    ) {
66        let tab = expanded_node.transform_and_bounds.clone();
67        let (x1, y1, x2, y2, stroke, material) =
68            expanded_node.with_properties_unwrapped(|properties: &mut Line| {
69                (
70                    properties.x1.clone(),
71                    properties.y1.clone(),
72                    properties.x2.clone(),
73                    properties.y2.clone(),
74                    properties.stroke.clone(),
75                    properties.material.clone(),
76                )
77            });
78
79        let deps = &[
80            tab.untyped(),
81            x1.untyped(),
82            y1.untyped(),
83            x2.untyped(),
84            y2.untyped(),
85            stroke.untyped(),
86            material.untyped(),
87            expanded_node.computed_opacity.untyped(),
88        ];
89        let cloned_expanded_node = expanded_node.clone();
90        let cloned_context = context.clone();
91
92        expanded_node
93            .changed_listener
94            .replace_with(Property::computed(
95                move || {
96                    cloned_context.mark_canvas_node_dirty(cloned_expanded_node.id);
97                    cloned_context
98                        .set_canvas_dirty(cloned_expanded_node.occlusion.get().render_layer_id)
99                },
100                deps,
101            ));
102    }
103
104    fn ray_cast_test(
105        &self,
106        expanded_node: &ExpandedNode,
107        ray: pax_runtime::api::math::Point2<pax_runtime::api::Window>,
108    ) -> bool {
109        self.resolve_coverage_path(expanded_node)
110            .is_some_and(|path| {
111                path_contains_with_tolerance(&path, kurbo::Point::new(ray.x, ray.y))
112            })
113    }
114
115    fn resolve_coverage_path(&self, expanded_node: &ExpandedNode) -> Option<BezPath> {
116        expanded_node.with_properties_unwrapped(|properties: &mut Line| {
117            let tab = expanded_node.transform_and_bounds.get();
118            let (start, end) = resolve_points(properties, tab.bounds);
119            let stroke = properties.stroke.get();
120            line_coverage_path(start, end, &stroke).map(|path| Affine::from(tab.transform) * path)
121        })
122    }
123
124    fn resolve_coverage_opacity(&self, expanded_node: &ExpandedNode) -> f64 {
125        expanded_node.with_properties_unwrapped(|properties: &mut Line| {
126            let stroke = properties.stroke.get();
127            (stroke.color.get().alpha_0_1() * expanded_node.computed_opacity.get()).clamp(0.0, 1.0)
128        })
129    }
130
131    fn render(
132        &self,
133        expanded_node: &ExpandedNode,
134        rtc: &Rc<RuntimeContext>,
135        rc: &mut dyn RenderContext,
136    ) {
137        if !rtc.is_canvas_node_dirty(&expanded_node.id) {
138            return;
139        }
140
141        let Some(scope) = begin_bounded_canvas_node(rc, expanded_node, rtc) else {
142            return;
143        };
144
145        expanded_node.with_properties_unwrapped(|properties: &mut Line| {
146            let (start, end) = resolve_points(properties, scope.bounds);
147            let stroke = properties.stroke.get();
148            let material = properties.material.get();
149            let stroke_width = stroke_width_pixels(&stroke);
150            if stroke_width > f64::EPSILON {
151                let bez_path = centerline_path(start, end);
152                rc.save(scope.layer_id);
153                rc.transform(scope.layer_id, scope.surface_transform);
154                rc.stroke_with_material_and_opacity(
155                    scope.layer_id,
156                    bez_path,
157                    &stroke,
158                    &material,
159                    expanded_node.computed_opacity.get(),
160                );
161                rc.restore(scope.layer_id);
162            }
163        });
164
165        if rc.end_node(scope.layer_id, scope.node_id) {
166            rtc.clear_canvas_node_dirty(&expanded_node.id);
167        }
168    }
169
170    fn resolve_debug(
171        &self,
172        f: &mut std::fmt::Formatter,
173        expanded_node: Option<&ExpandedNode>,
174    ) -> std::fmt::Result {
175        match expanded_node {
176            Some(expanded_node) => expanded_node.with_properties_unwrapped(|line: &mut Line| {
177                f.debug_struct("Line")
178                    .field("x1", &line.x1.get())
179                    .field("y1", &line.y1.get())
180                    .field("x2", &line.x2.get())
181                    .field("y2", &line.y2.get())
182                    .finish()
183            }),
184            None => f.debug_struct("Line").finish_non_exhaustive(),
185        }
186    }
187
188    fn base(&self) -> &BaseInstance {
189        &self.base
190    }
191}
192
193fn resolve_points(line: &Line, bounds: (f64, f64)) -> (kurbo::Point, kurbo::Point) {
194    (
195        to_kurbo_point(line.x1.get(), line.y1.get(), bounds),
196        to_kurbo_point(line.x2.get(), line.y2.get(), bounds),
197    )
198}
199
200fn centerline_path(start: kurbo::Point, end: kurbo::Point) -> BezPath {
201    let mut path = BezPath::new();
202    path.move_to(start);
203    path.line_to(end);
204    path
205}
206
207fn line_coverage_path(start: kurbo::Point, end: kurbo::Point, stroke: &Stroke) -> Option<BezPath> {
208    stroked_outline_path(&centerline_path(start, end), stroke)
209}
210
211fn path_contains_with_tolerance(path: &BezPath, point: kurbo::Point) -> bool {
212    if path.contains(point) {
213        return true;
214    }
215
216    const HIT_TEST_EPSILON: f64 = 1e-3;
217    [
218        (HIT_TEST_EPSILON, 0.0),
219        (-HIT_TEST_EPSILON, 0.0),
220        (0.0, HIT_TEST_EPSILON),
221        (0.0, -HIT_TEST_EPSILON),
222    ]
223    .into_iter()
224    .any(|(dx, dy)| path.contains(kurbo::Point::new(point.x + dx, point.y + dy)))
225}
226
227#[cfg(test)]
228mod tests {
229    use super::{line_coverage_path, path_contains_with_tolerance};
230    use kurbo::{Point, Shape};
231    use pax_runtime::api::{Property, Size, Stroke, StrokeCap, StrokeJoin};
232
233    fn test_stroke(width: f64, cap: StrokeCap) -> Stroke {
234        Stroke {
235            color: Property::new(pax_runtime::api::Color::BLACK),
236            width: Property::new(Size::Pixels(width.into())),
237            cap: Property::new(cap),
238            join: Property::new(StrokeJoin::default()),
239        }
240    }
241
242    #[test]
243    fn horizontal_line_coverage_has_area() {
244        let path = line_coverage_path(
245            Point::new(0.0, 0.0),
246            Point::new(10.0, 0.0),
247            &test_stroke(2.0, StrokeCap::Butt),
248        )
249        .unwrap();
250        assert!(!path.bounding_box().is_zero_area());
251    }
252
253    #[test]
254    fn zero_length_line_coverage_has_area() {
255        let path = line_coverage_path(
256            Point::new(4.0, 8.0),
257            Point::new(4.0, 8.0),
258            &test_stroke(6.0, StrokeCap::Round),
259        )
260        .unwrap();
261        assert!(!path.bounding_box().is_zero_area());
262    }
263
264    #[test]
265    fn line_coverage_contains_points_inside_stroke() {
266        let path = line_coverage_path(
267            Point::new(0.0, 0.0),
268            Point::new(20.0, 0.0),
269            &test_stroke(6.0, StrokeCap::Butt),
270        )
271        .unwrap();
272        assert!(path.contains(Point::new(10.0, 1.0)));
273        assert!(!path.contains(Point::new(10.0, 4.0)));
274    }
275
276    #[test]
277    fn round_caps_extend_beyond_segment_endpoints() {
278        let path = line_coverage_path(
279            Point::new(0.0, 0.0),
280            Point::new(20.0, 0.0),
281            &test_stroke(6.0, StrokeCap::Round),
282        )
283        .unwrap();
284        assert!(path_contains_with_tolerance(&path, Point::new(-2.0, 0.0)));
285        assert!(path_contains_with_tolerance(&path, Point::new(22.0, 0.0)));
286    }
287}