Skip to main content

pax_std/drawing/
lighting.rs

1use kurbo::Point;
2use pax_engine::api::LocalProperty;
3use pax_engine::*;
4use pax_runtime::api::{
5    Color, Depth, Layer, LightShape, Numeric, SceneAmbientLight, SceneLight, SceneLighting, Size,
6    Vector3,
7};
8use pax_runtime::{
9    BaseInstance, ExpandedNode, InstanceFlags, InstanceNode, InstantiationArgs, RuntimeContext,
10};
11use std::rc::Rc;
12
13use crate::common::canvas_surface_transform;
14
15/// A non-rendering container that keeps descendant lights from escaping its subtree.
16///
17/// Lights outside the frame may still illuminate its descendants. Each expanded
18/// frame instance has its own lexical lighting identity.
19#[pax]
20#[engine_import_path("pax_engine")]
21#[primitive("pax_std::drawing::lighting::LightFrameInstance")]
22pub struct LightFrame {}
23
24pub struct LightFrameInstance {
25    base: BaseInstance,
26}
27
28impl InstanceNode for LightFrameInstance {
29    fn instantiate(args: InstantiationArgs) -> Rc<Self>
30    where
31        Self: Sized,
32    {
33        Rc::new(Self {
34            base: BaseInstance::new(
35                args,
36                InstanceFlags {
37                    invisible_to_slot: false,
38                    invisible_to_raycasting: true,
39                    layer: Layer::DontCare,
40                    is_component: false,
41                    is_slot: false,
42                },
43            ),
44        })
45    }
46
47    fn establishes_light_frame(&self) -> bool {
48        true
49    }
50
51    fn resolve_debug(
52        &self,
53        f: &mut std::fmt::Formatter,
54        _expanded_node: Option<&ExpandedNode>,
55    ) -> std::fmt::Result {
56        f.debug_struct("LightFrame").finish()
57    }
58
59    fn base(&self) -> &BaseInstance {
60        &self.base
61    }
62}
63
64/// A non-rendering light resource that affects light-reactive vector materials in its scene.
65#[pax]
66#[engine_import_path("pax_engine")]
67#[custom(Default)]
68#[primitive("pax_std::drawing::lighting::LightSourceInstance")]
69pub struct LightSource {
70    /// Light color.
71    pub color: Property<Color>,
72    /// Light intensity multiplier.
73    pub intensity: Property<f64>,
74    /// Radius for point-light attenuation.
75    pub radius: Property<Size>,
76    /// Logical scene depth in pixels.
77    pub z: Property<Depth>,
78    /// Positional or directional light shape.
79    pub shape: Property<LightShape>,
80    /// Direction for directional lights.
81    pub direction: Property<Vector3>,
82    /// Whether this light contributes to the scene.
83    pub enabled: Property<bool>,
84}
85
86impl Default for LightSource {
87    fn default() -> Self {
88        Self {
89            color: Property::new(Color::WHITE),
90            intensity: Property::new(1.0),
91            radius: Property::new(Size::Pixels(Numeric::F64(240.0))),
92            z: Property::new(Depth(Numeric::F64(200.0))),
93            shape: Property::new(LightShape::Point),
94            direction: Property::new(Vector3::new(0.0, 0.0, -1.0)),
95            enabled: Property::new(true),
96        }
97    }
98}
99
100pub struct LightSourceInstance {
101    base: BaseInstance,
102}
103
104impl InstanceNode for LightSourceInstance {
105    fn has_scene_lighting(&self) -> bool {
106        true
107    }
108
109    fn instantiate(args: InstantiationArgs) -> Rc<Self>
110    where
111        Self: Sized,
112    {
113        Rc::new(Self {
114            base: BaseInstance::new(
115                args,
116                InstanceFlags {
117                    invisible_to_slot: false,
118                    invisible_to_raycasting: true,
119                    layer: Layer::Canvas,
120                    is_component: false,
121                    is_slot: false,
122                },
123            ),
124        })
125    }
126
127    fn handle_mount(
128        self: Rc<Self>,
129        expanded_node: &Rc<ExpandedNode>,
130        context: &Rc<RuntimeContext>,
131    ) {
132        let tab = expanded_node.transform_and_bounds.clone();
133        let (color, intensity, radius, z, shape, direction, enabled) = expanded_node
134            .with_properties_unwrapped(|properties: &mut LightSource| {
135                (
136                    properties.color.clone(),
137                    properties.intensity.clone(),
138                    properties.radius.clone(),
139                    properties.z.clone(),
140                    properties.shape.clone(),
141                    properties.direction.clone(),
142                    properties.enabled.clone(),
143                )
144            });
145
146        let deps = &[
147            tab.untyped(),
148            color.untyped(),
149            intensity.untyped(),
150            radius.untyped(),
151            z.untyped(),
152            shape.untyped(),
153            direction.untyped(),
154            enabled.untyped(),
155        ];
156        let cloned_context = context.clone();
157
158        expanded_node
159            .changed_listener
160            .replace_with(LocalProperty::computed(
161                move || {
162                    cloned_context.mark_scene_lighting_dirty();
163                },
164                deps,
165            ));
166    }
167
168    fn resolve_scene_light(
169        &self,
170        expanded_node: &ExpandedNode,
171        context: &RuntimeContext,
172    ) -> Option<SceneLight> {
173        expanded_node.with_properties_unwrapped(|properties: &mut LightSource| {
174            if !properties.enabled.local().get() {
175                return None;
176            }
177
178            let tab = expanded_node.transform_and_bounds.get();
179            let center = Point::new(tab.bounds.0 * 0.5, tab.bounds.1 * 0.5);
180            let point = canvas_surface_transform(expanded_node, context) * center;
181            Some(SceneLight {
182                shape: properties.shape.local().get(),
183                position: Vector3::new(point.x, point.y, properties.z.local().get().to_float()),
184                direction: properties.direction.local().get(),
185                color: properties.color.local().get(),
186                intensity: properties.intensity.local().get().max(0.0),
187                radius: properties
188                    .radius
189                    .local()
190                    .get()
191                    .expect_pixels()
192                    .to_float()
193                    .max(0.0),
194                enabled: true,
195            })
196        })
197    }
198
199    fn resolve_debug(
200        &self,
201        f: &mut std::fmt::Formatter,
202        _expanded_node: Option<&ExpandedNode>,
203    ) -> std::fmt::Result {
204        f.debug_struct("LightSource").finish()
205    }
206
207    fn base(&self) -> &BaseInstance {
208        &self.base
209    }
210}
211
212/// A non-rendering singleton ambient-light override for its scene.
213#[pax]
214#[engine_import_path("pax_engine")]
215#[custom(Default)]
216#[primitive("pax_std::drawing::lighting::AmbientLightInstance")]
217pub struct AmbientLight {
218    /// Ambient color.
219    pub color: Property<Color>,
220    /// Ambient intensity multiplier.
221    pub intensity: Property<f64>,
222    /// Whether this ambient override participates in topmost-wins selection.
223    pub enabled: Property<bool>,
224}
225
226impl Default for AmbientLight {
227    fn default() -> Self {
228        Self {
229            color: Property::new(Color::WHITE),
230            intensity: Property::new(SceneLighting::DEFAULT_AMBIENT_INTENSITY),
231            enabled: Property::new(true),
232        }
233    }
234}
235
236pub struct AmbientLightInstance {
237    base: BaseInstance,
238}
239
240impl InstanceNode for AmbientLightInstance {
241    fn has_scene_lighting(&self) -> bool {
242        true
243    }
244
245    fn instantiate(args: InstantiationArgs) -> Rc<Self>
246    where
247        Self: Sized,
248    {
249        Rc::new(Self {
250            base: BaseInstance::new(
251                args,
252                InstanceFlags {
253                    invisible_to_slot: false,
254                    invisible_to_raycasting: true,
255                    layer: Layer::Canvas,
256                    is_component: false,
257                    is_slot: false,
258                },
259            ),
260        })
261    }
262
263    fn handle_mount(
264        self: Rc<Self>,
265        expanded_node: &Rc<ExpandedNode>,
266        context: &Rc<RuntimeContext>,
267    ) {
268        let (color, intensity, enabled) =
269            expanded_node.with_properties_unwrapped(|properties: &mut AmbientLight| {
270                (
271                    properties.color.clone(),
272                    properties.intensity.clone(),
273                    properties.enabled.clone(),
274                )
275            });
276
277        let deps = &[color.untyped(), intensity.untyped(), enabled.untyped()];
278        let cloned_context = context.clone();
279
280        expanded_node
281            .changed_listener
282            .replace_with(LocalProperty::computed(
283                move || {
284                    cloned_context.mark_scene_lighting_dirty();
285                },
286                deps,
287            ));
288    }
289
290    fn resolve_scene_ambient_light(
291        &self,
292        expanded_node: &ExpandedNode,
293        _context: &RuntimeContext,
294    ) -> Option<SceneAmbientLight> {
295        expanded_node.with_properties_unwrapped(|properties: &mut AmbientLight| {
296            properties.enabled.local().get().then(|| SceneAmbientLight {
297                color: properties.color.local().get(),
298                intensity: properties.intensity.local().get().max(0.0),
299            })
300        })
301    }
302
303    fn resolve_debug(
304        &self,
305        f: &mut std::fmt::Formatter,
306        _expanded_node: Option<&ExpandedNode>,
307    ) -> std::fmt::Result {
308        f.debug_struct("AmbientLight").finish()
309    }
310
311    fn base(&self) -> &BaseInstance {
312        &self.base
313    }
314}