1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
use std::{rc::Rc, sync::Arc};
use cranpose_ui_graphics::{
BlendMode, Color, ColorFilter, CompositingStrategy, Density, Dp, GradientBlurDirection,
GradientCutMaskSpec, GradientFadeMaskSpec, LayerShape, Px, RenderEffect, RoundedCornerShape,
RuntimeShader, TransformOrigin, gradient_blur_effect, gradient_cut_mask_effect,
gradient_fade_dst_out_effect, rounded_alpha_mask_effect,
space::{LayerSpace, Mat4, MeshSurface, Scene3d},
};
use super::{GraphicsLayer, Modifier, inspector_metadata};
use crate::modifier_nodes::{GraphicsLayerElement, LazyGraphicsLayerElement};
fn backdrop_blur_layer(radius: Dp, shape: LayerShape) -> GraphicsLayer {
let density = Density::from_scale(crate::render_state::current_density());
let radius_px = radius.to_px(density).max(Px::ZERO);
GraphicsLayer {
backdrop_effect: (radius_px.0 > 0.0).then(|| RenderEffect::blur(radius_px.0)),
shape,
clip: true,
..Default::default()
}
}
fn backdrop_gradient_blur_layer(
start_radius: Dp,
end_radius: Dp,
direction: GradientBlurDirection,
) -> GraphicsLayer {
let density = Density::from_scale(crate::render_state::current_density());
let start_px = start_radius.to_px(density).max(Px::ZERO);
let end_px = end_radius.to_px(density).max(Px::ZERO);
GraphicsLayer {
backdrop_effect: (start_px.0 > 0.0 || end_px.0 > 0.0)
.then(|| gradient_blur_effect(start_px.0, end_px.0, direction)),
shape: LayerShape::Rectangle,
clip: true,
..Default::default()
}
}
impl Modifier {
/// Apply a lazily evaluated graphics layer.
///
/// The closure is evaluated during scene building, not composition, which lets
/// layer properties update without forcing recomposition.
///
/// Example:
/// `Modifier::empty().graphics_layer(|| GraphicsLayer { alpha: 0.5, ..Default::default() })`
///
/// # A drag that drives the translation must not be read inside it
///
/// [`PointerEvent::position`](crate::modifier::PointerEvent::position) is
/// in the receiving node's own space, so a node this layer translates
/// reports a finger that has moved only as far as it OUTRAN the
/// translation. Feed that position back into `translation_x` and the
/// gesture measures itself:
///
/// ```text
/// reported = finger - offset offset = reported - start
/// => offset = (finger - start) / 2
/// ```
///
/// The offset converges on half the finger's travel and can never exceed
/// it, so a swipe-to-dismiss whose threshold is half the width never
/// crosses it however far the finger goes -- silently, with the content
/// sliding convincingly the whole time.
///
/// Two ways out, and [`SwipeToDismiss`](crate::widgets::SwipeToDismiss)
/// uses both:
///
/// - put `pointer_input` on a node OUTSIDE the translated one, which is
/// also how Compose's own `SwipeToDismissBox` is built -- the drag is
/// detected on the box, the content carries the layer;
/// - or read
/// [`PointerEvent::global_position`](crate::modifier::PointerEvent::global_position),
/// which no layer transform touches.
pub fn graphics_layer(self, layer: impl Fn() -> GraphicsLayer + 'static) -> Self {
let modifier = Self::with_element(LazyGraphicsLayerElement::new(Rc::new(layer)))
.with_inspector_metadata(inspector_metadata("graphicsLayer", |info| {
info.add_property("lazy", "true");
}));
self.then(modifier)
}
/// Shows a 3D scene in this node's bounds.
///
/// Every node inside the scene takes a 3D frame from its parent's: its
/// place in its parent's layout, on the parent's plane, with x right, y
/// down and z away from the side the content shows to, a unit to a
/// logical pixel. The scene's own frame is its space, which the camera
/// looks into through the middle of the node's bounds; a camera one
/// focal length in front of the plane z = 0 shows the scene's children
/// at their own size, where layout put them. A child with a
/// [`mesh_surface`](Self::mesh_surface) draws its content on its mesh in
/// its frame, and nearer surfaces hide farther ones; a
/// [`transform3d`](Self::transform3d) moves the frames beneath it. The
/// scene is cut to the node's bounds, and the node's own draws and its
/// children's flat draws stay flat: those that come before the first
/// child in 3D are drawn under the scene, the rest over it.
///
/// A `scene3d` inside the scene is a doorway: its node's rect, in its
/// frame, opens onto a space of its own, which lies behind it, placed so
/// the inner scene's camera stands in the doorway's middle (see
/// [`Camera::doorway`](cranpose_ui_graphics::space::Camera::doorway)).
/// The window's eye sees through each doorway that shows on screen, as
/// deep as they show, and walks through them (see [`Eye`](crate::Eye)).
///
/// The closure runs when the scene is drawn, as a lazy
/// [`graphics_layer`](Self::graphics_layer)'s does, so a camera that
/// follows a state read in it moves without recomposition.
///
/// ```
/// use std::sync::Arc;
///
/// use cranpose_ui::Modifier;
/// use cranpose_ui_graphics::space::{Camera, Mat4, Material, Mesh, MeshSurface, Scene3d, Vec3};
///
/// let camera = Camera::look_at(
/// Vec3::new(0.0, 0.0, -800.0),
/// Vec3::ZERO,
/// Vec3::new(0.0, 1.0, 0.0),
/// 700.0,
/// );
/// let scene = Modifier::empty().scene3d(move || Scene3d {
/// camera,
/// light: None,
/// eye: None,
/// });
/// let sphere = Arc::new(Mesh::sphere(48, 24));
/// let globe = Modifier::empty().mesh_surface(move || MeshSurface {
/// mesh: Arc::clone(&sphere),
/// transform: Mat4::scaling(Vec3::new(200.0, 200.0, 200.0)),
/// material: Material::Lit,
/// casts_shadow: true,
/// solid: true,
/// });
/// # let _ = (scene, globe);
/// ```
pub fn scene3d(self, scene: impl Fn() -> Scene3d + 'static) -> Self {
self.graphics_layer(move || GraphicsLayer {
space: Some(Arc::new(LayerSpace::Scene(scene()))),
clip: true,
..GraphicsLayer::DEFAULT
})
}
/// Draws this node's content on a mesh in its scene, placed in the
/// node's 3D frame (see [`scene3d`](Self::scene3d)).
///
/// The node's size is the size of the content laid on the mesh: content
/// point `(x, y)` shows where the mesh's texture coordinate is
/// `(x / width, y / height)`. The surface's transform places the mesh in
/// the node's frame, which starts where layout placed the node. The
/// content stays live and takes pointer input where it shows on the
/// mesh. The frames of the node's children lie in its content: x and y
/// in its content's pixels, z into it (see
/// [`MeshSurface::content_to_scene`](cranpose_ui_graphics::space::MeshSurface::content_to_scene)),
/// so a control can stand out of the wall it sits on, where layout put
/// it on the wall. A node outside every scene draws its content flat.
///
/// The closure runs when the scene is drawn, as a lazy
/// [`graphics_layer`](Self::graphics_layer)'s does.
pub fn mesh_surface(self, surface: impl Fn() -> MeshSurface + 'static) -> Self {
self.graphics_layer(move || GraphicsLayer {
space: Some(Arc::new(LayerSpace::Surface(surface()))),
clip: true,
..GraphicsLayer::DEFAULT
})
}
/// Moves the 3D frames beneath this node by `transform`, in the node's
/// own frame, as a group of 3D objects moves together: the mesh surfaces
/// and doorways under it follow. The node's own draws and the flat draws
/// beneath it stay where they would be without it, and outside a scene
/// it changes nothing.
///
/// The closure runs when the scene is drawn, as a lazy
/// [`graphics_layer`](Self::graphics_layer)'s does, so a group that
/// follows a state read in it moves without recomposition.
pub fn transform3d(self, transform: impl Fn() -> Mat4 + 'static) -> Self {
self.graphics_layer(move || GraphicsLayer {
space: Some(Arc::new(LayerSpace::Transform(transform()))),
..GraphicsLayer::DEFAULT
})
}
/// Apply a concrete graphics layer snapshot.
///
/// This is useful for parameter-style wrappers that already build a fixed
/// [`GraphicsLayer`] value.
pub fn graphics_layer_value(self, layer: GraphicsLayer) -> Self {
let inspector_values = layer.clone();
let modifier = Self::with_element(GraphicsLayerElement::new(layer))
.with_inspector_metadata(inspector_metadata("graphicsLayer", move |info| {
info.add_property("alpha", inspector_values.alpha.to_string());
info.add_property("scale", inspector_values.scale.to_string());
info.add_property("scaleX", inspector_values.scale_x.to_string());
info.add_property("scaleY", inspector_values.scale_y.to_string());
info.add_property("rotationX", inspector_values.rotation_x.to_string());
info.add_property("rotationY", inspector_values.rotation_y.to_string());
info.add_property("rotationZ", inspector_values.rotation_z.to_string());
info.add_property(
"cameraDistance",
inspector_values.camera_distance.to_string(),
);
info.add_property(
"transformOrigin",
format!(
"{},{}",
inspector_values.transform_origin.pivot_fraction_x,
inspector_values.transform_origin.pivot_fraction_y
),
);
info.add_property("translationX", inspector_values.translation_x.to_string());
info.add_property("translationY", inspector_values.translation_y.to_string());
if let Some(space) = &inspector_values.space {
info.add_property("space", format!("{space:?}"));
}
info.add_property(
"shadowElevation",
inspector_values.shadow_elevation.to_string(),
);
info.add_property("shape", format!("{:?}", inspector_values.shape));
info.add_property("clip", inspector_values.clip.to_string());
info.add_property(
"ambientShadowColor",
format!("{:?}", inspector_values.ambient_shadow_color),
);
info.add_property(
"spotShadowColor",
format!("{:?}", inspector_values.spot_shadow_color),
);
info.add_property(
"compositingStrategy",
format!("{:?}", inspector_values.compositing_strategy),
);
info.add_property("blendMode", format!("{:?}", inspector_values.blend_mode));
if let Some(filter) = inspector_values.color_filter {
info.add_property("colorFilter", format!("{filter:?}"));
}
}));
self.then(modifier)
}
/// Compose-compatible parameter-style graphics layer entry point.
///
/// This mirrors `Modifier.graphicsLayer(...)` style APIs and maps directly to
/// [`GraphicsLayer`] fields currently implemented by the renderer stack.
#[expect(clippy::too_many_arguments)]
pub fn graphics_layer_params(
self,
scale_x: f32,
scale_y: f32,
alpha: f32,
translation_x: f32,
translation_y: f32,
shadow_elevation: f32,
rotation_x: f32,
rotation_y: f32,
rotation_z: f32,
camera_distance: f32,
transform_origin: TransformOrigin,
shape: LayerShape,
clip: bool,
render_effect: Option<RenderEffect>,
ambient_shadow_color: Color,
spot_shadow_color: Color,
compositing_strategy: CompositingStrategy,
blend_mode: BlendMode,
color_filter: Option<ColorFilter>,
) -> Self {
self.graphics_layer_value(GraphicsLayer {
alpha,
scale: 1.0,
scale_x,
scale_y,
rotation_x,
rotation_y,
rotation_z,
camera_distance,
transform_origin,
translation_x,
translation_y,
space: None,
shadow_elevation,
ambient_shadow_color,
spot_shadow_color,
shape,
clip,
compositing_strategy,
blend_mode,
color_filter,
render_effect,
backdrop_effect: None,
})
}
/// Compose-compatible block-style graphics layer entry point.
///
/// Example:
/// `Modifier::empty().graphics_layer_block(|layer| { layer.alpha = 0.5; layer.scale_x = 1.2; })`
pub fn graphics_layer_block(self, configure: impl Fn(&mut GraphicsLayer) + 'static) -> Self {
self.graphics_layer(move || {
let mut layer = GraphicsLayer::default();
configure(&mut layer);
layer
})
}
/// Compose-style rotation convenience.
///
/// Matches Kotlin: `Modifier.rotate(degrees: Float)`, which maps to
/// `graphicsLayer(rotationZ = degrees)`. Rotation is clockwise for
/// positive `degrees` and pivots around the layer's center, matching
/// `graphics_layer_value`'s default (centered) `transform_origin`.
pub fn rotate(self, degrees: f32) -> Self {
self.graphics_layer_value(GraphicsLayer {
rotation_z: degrees,
..Default::default()
})
}
/// Compose-style uniform scale convenience.
///
/// Matches Kotlin: `Modifier.scale(scale: Float)`, which maps to
/// `graphicsLayer(scaleX = scale, scaleY = scale)`.
pub fn scale(self, scale: f32) -> Self {
self.scale_xy(scale, scale)
}
/// Compose-style non-uniform scale convenience.
///
/// Matches Kotlin: `Modifier.scale(scaleX: Float, scaleY: Float)`.
pub fn scale_xy(self, scale_x: f32, scale_y: f32) -> Self {
self.graphics_layer_value(GraphicsLayer {
scale_x,
scale_y,
..Default::default()
})
}
/// Compose-style elevation shadow convenience.
///
/// This mirrors `Modifier.shadow(elevation)` defaults:
/// rectangle shape, black ambient/spot colors, and clipping enabled when
/// elevation is positive.
pub fn shadow(self, elevation: f32) -> Self {
self.shadow_with(
elevation,
LayerShape::Rectangle,
elevation > 0.0,
Color::BLACK,
Color::BLACK,
)
}
/// Compose-style shadow API with explicit shape/clip/colors.
pub fn shadow_with(
self,
elevation: f32,
shape: LayerShape,
clip: bool,
ambient_color: Color,
spot_color: Color,
) -> Self {
let clamped_elevation = elevation.max(0.0);
if clamped_elevation == 0.0 && !clip {
return self;
}
self.graphics_layer_value(GraphicsLayer {
shadow_elevation: clamped_elevation,
ambient_shadow_color: ambient_color,
spot_shadow_color: spot_color,
shape,
clip,
..Default::default()
})
}
/// Apply a backdrop effect to content behind this composable's bounds.
pub fn backdrop_effect(self, effect: RenderEffect) -> Self {
let layer = GraphicsLayer {
backdrop_effect: Some(effect),
..Default::default()
};
let modifier = Self::with_element(GraphicsLayerElement::new(layer))
.with_inspector_metadata(inspector_metadata("backdropEffect", |info| {
info.add_property("enabled", "true");
}));
self.then(modifier)
}
/// Blur content behind this composable, clipped to the composable bounds.
///
/// `radius` is expressed in Dp and converted to px using the current render
/// density when modifier slices are evaluated.
pub fn backdrop_blur(self, radius: Dp) -> Self {
if radius.0 <= 0.0 {
return self.clip_to_bounds();
}
let modifier = Self::with_element(LazyGraphicsLayerElement::new(Rc::new(move || {
backdrop_blur_layer(radius, LayerShape::Rectangle)
})))
.with_inspector_metadata(inspector_metadata("backdropBlur", move |info| {
info.add_property("radius", radius.0.to_string());
}));
self.then(modifier)
}
/// Blur content behind this composable with a radius that changes across
/// its bounds. This is a true spatial blur gradient: the sampling kernel
/// interpolates from `start_radius` to `end_radius`; it is not an opacity
/// gradient over a uniformly blurred layer.
pub fn backdrop_gradient_blur(
self,
start_radius: Dp,
end_radius: Dp,
direction: GradientBlurDirection,
) -> Self {
if start_radius.0 <= 0.0 && end_radius.0 <= 0.0 {
return self.clip_to_bounds();
}
let modifier = Self::with_element(LazyGraphicsLayerElement::new(Rc::new(move || {
backdrop_gradient_blur_layer(start_radius, end_radius, direction)
})))
.with_inspector_metadata(inspector_metadata(
"backdropGradientBlur",
move |info| {
info.add_property("startRadius", start_radius.0.to_string());
info.add_property("endRadius", end_radius.0.to_string());
info.add_property("direction", format!("{direction:?}"));
},
));
self.then(modifier)
}
/// Apply a frosted glass material: backdrop blur, clipped shape, and tint.
pub fn glass_material(self, material: GlassMaterial) -> Self {
let blur_radius = material.blur_radius;
let shape = material.shape;
let modifier = Self::with_element(LazyGraphicsLayerElement::new(Rc::new(move || {
backdrop_blur_layer(blur_radius, LayerShape::Rounded(shape))
})))
.with_inspector_metadata(inspector_metadata("glassMaterial", move |info| {
info.add_property("blurRadius", blur_radius.0.to_string());
info.add_property("shape", format!("{shape:?}"));
}));
self.then(modifier)
.rounded_corner_shape(material.shape)
.background(material.tint)
}
/// Convenience alias for applying a backdrop shader effect.
pub fn shader_background(self, shader: RuntimeShader) -> Self {
self.backdrop_effect(RenderEffect::runtime_shader(shader))
}
/// Apply a color filter to this composable's graphics layer output.
///
/// This mirrors Compose's `graphicsLayer(colorFilter = ...)` capability.
pub fn color_filter(self, filter: ColorFilter) -> Self {
let layer = GraphicsLayer {
color_filter: Some(filter),
..Default::default()
};
let modifier = Self::with_element(GraphicsLayerElement::new(layer))
.with_inspector_metadata(inspector_metadata("colorFilter", |info| {
info.add_property("enabled", "true");
}));
self.then(modifier)
}
/// Convenience color filter that tints layer output.
pub fn tint(self, tint: Color) -> Self {
self.color_filter(ColorFilter::tint(tint))
}
/// Configures how the layer is composited into its parent.
pub fn compositing_strategy(self, strategy: CompositingStrategy) -> Self {
self.graphics_layer_value(GraphicsLayer {
compositing_strategy: strategy,
..Default::default()
})
}
/// Configures blend mode for this layer output.
///
/// Runtime support is backend-dependent. Current renderers fully support
/// `SrcOver` and `DstOut`; unsupported modes fall back to `SrcOver`.
pub fn layer_blend_mode(self, blend_mode: BlendMode) -> Self {
self.graphics_layer_value(GraphicsLayer {
blend_mode,
..Default::default()
})
}
/// Apply a directional gradient cut mask to this composable output.
///
/// This masks the rendered layer with rounded corners and a feathered edge.
pub fn gradient_cut_mask(
self,
area_width: f32,
area_height: f32,
spec: GradientCutMaskSpec,
) -> Self {
let layer = GraphicsLayer {
render_effect: Some(gradient_cut_mask_effect(&spec, area_width, area_height)),
..Default::default()
};
self.graphics_layer_value(layer)
}
/// Apply a rounded alpha mask to this composable output.
///
/// Useful to constrain a preceding render effect (for example blur) to a
/// rounded shape while preserving a soft edge transition.
pub fn rounded_alpha_mask(
self,
area_width: f32,
area_height: f32,
corner_radius: f32,
edge_feather: f32,
) -> Self {
let has_radius = corner_radius.is_finite() && corner_radius > 0.0;
let has_feather = edge_feather.is_finite() && edge_feather > 0.0;
if !has_radius && !has_feather {
return self;
}
let layer = GraphicsLayer {
render_effect: Some(rounded_alpha_mask_effect(
area_width,
area_height,
corner_radius,
edge_feather,
)),
..Default::default()
};
self.graphics_layer_value(layer)
}
/// Apply a directional gradient fade mask with destination-out semantics.
///
/// This mirrors Compose's `drawWithContent + drawRect(..., BlendMode.DstOut)`
/// pattern for fading content to transparent along one axis.
pub fn gradient_fade_dst_out(
self,
area_width: f32,
area_height: f32,
spec: GradientFadeMaskSpec,
) -> Self {
let layer = GraphicsLayer {
render_effect: Some(gradient_fade_dst_out_effect(&spec, area_width, area_height)),
..Default::default()
};
self.graphics_layer_value(layer)
}
}
/// Visual parameters for [`Modifier::glass_material`].
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct GlassMaterial {
/// Radius of the blur applied to what is behind the node.
pub blur_radius: Dp,
/// Color drawn over the blurred backdrop as the node's background.
pub tint: Color,
/// Rounded corners that clip the blur and the tint.
pub shape: RoundedCornerShape,
}
impl GlassMaterial {
/// Creates a material from its blur radius, tint and shape.
pub fn new(blur_radius: Dp, tint: Color, shape: RoundedCornerShape) -> Self {
Self {
blur_radius,
tint,
shape,
}
}
}