cranpose-render-wgpu 0.22.4

GPU renderer for Cranpose scenes through wgpu
Documentation
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
use cranpose_render_common::{
    graph::{DrawRunNode, InlineNode, LayerNode, PrimitiveNode, RenderNode},
    primitive_emit::resolve_clip,
};
use cranpose_ui_graphics::{
    DrawPrimitive, LayerShape, Point, RecordLane, Rect, RenderEffect, ShadowPrimitive, expand_rect,
    primitive_coverage_rect,
};

use super::{AFFINE_TOLERANCE, RasterScale, child_needs_surface, direct_translation};
use crate::scene::LayerRoundedClip;

pub(super) fn rounded_clip_for_layer(layer: &LayerNode) -> Option<LayerRoundedClip> {
    if !layer.graphics_layer.clip {
        return None;
    }
    let LayerShape::Rounded(shape) = layer.graphics_layer.shape else {
        return None;
    };
    let radii = shape.resolve(layer.local_bounds.width, layer.local_bounds.height);
    let radii = [
        radii.top_left,
        radii.top_right,
        radii.bottom_left,
        radii.bottom_right,
    ];
    if radii.iter().all(|radius| *radius <= f32::EPSILON) {
        return None;
    }
    Some(LayerRoundedClip {
        rect: layer.local_bounds,
        radii,
    })
}

/// The four corner squares of a rounded rect are the only places a rounded
/// clip differs from its rect clip. Content whose coverage stays inside the
/// corner circles there is clipped identically by both.
pub(super) struct RoundedClipCorners {
    rect: Rect,
    radii: [f32; 4],
    raster_scale: RasterScale,
    aa_margin: f32,
}

impl RoundedClipCorners {
    pub(super) fn of(clip: LayerRoundedClip, raster_scale: RasterScale) -> Self {
        Self {
            rect: clip.rect,
            radii: clip.radii,
            raster_scale,
            aa_margin: raster_scale.aa_margin(),
        }
    }

    /// Whether `region` lies inside the rounded rect: for every corner square
    /// it enters, its point farthest from that corner's circle centre is still
    /// within the circle.
    pub(super) fn admits(&self, region: Rect) -> bool {
        if ![region.x, region.y, region.width, region.height]
            .into_iter()
            .all(f32::is_finite)
        {
            return false;
        }
        let Rect {
            x,
            y,
            width,
            height,
        } = self.rect;
        let right = x + width;
        let bottom = y + height;
        let corners = [
            (self.radii[0], x, y, 1.0, 1.0),
            (self.radii[1], right, y, -1.0, 1.0),
            (self.radii[2], x, bottom, 1.0, -1.0),
            (self.radii[3], right, bottom, -1.0, -1.0),
        ];
        let region_right = region.x + region.width;
        let region_bottom = region.y + region.height;
        for (radius, corner_x, corner_y, sign_x, sign_y) in corners {
            if radius <= 0.0 {
                continue;
            }
            let square_left = corner_x.min(corner_x + sign_x * radius);
            let square_right = corner_x.max(corner_x + sign_x * radius);
            let square_top = corner_y.min(corner_y + sign_y * radius);
            let square_bottom = corner_y.max(corner_y + sign_y * radius);
            let overlap_left = region.x.max(square_left);
            let overlap_right = region_right.min(square_right);
            let overlap_top = region.y.max(square_top);
            let overlap_bottom = region_bottom.min(square_bottom);
            if overlap_left >= overlap_right || overlap_top >= overlap_bottom {
                continue;
            }
            let centre_x = corner_x + sign_x * radius;
            let centre_y = corner_y + sign_y * radius;
            let farthest_x = if sign_x > 0.0 {
                overlap_left
            } else {
                overlap_right
            };
            let farthest_y = if sign_y > 0.0 {
                overlap_top
            } else {
                overlap_bottom
            };
            let dx = farthest_x - centre_x;
            let dy = farthest_y - centre_y;
            if dx * dx + dy * dy > radius * radius {
                return false;
            }
        }
        true
    }
}

pub(super) fn content_admits_rounded_clip(
    layer: &LayerNode,
    clip: LayerRoundedClip,
    raster_scale: RasterScale,
) -> bool {
    let corners = RoundedClipCorners::of(clip, raster_scale);
    layer_admits_corners(layer, Point::default(), None, &corners)
}

fn layer_admits_corners(
    layer: &LayerNode,
    offset: Point,
    clip: Option<Rect>,
    corners: &RoundedClipCorners,
) -> bool {
    let inherited_clip = resolve_clip(
        clip,
        layer
            .visual_clip_rect()
            .map(|rect| rect.translate(offset.x, offset.y)),
    );
    nodes_admit_corners(&layer.children, offset, inherited_clip, corners)
}

fn nodes_admit_corners(
    nodes: &[RenderNode],
    offset: Point,
    inherited_clip: Option<Rect>,
    corners: &RoundedClipCorners,
) -> bool {
    let check = |rect: Rect, primitive_clip: Option<Rect>| -> bool {
        let rect = rect.translate(offset.x, offset.y);
        let clip = resolve_clip(
            inherited_clip,
            primitive_clip.map(|clip| clip.translate(offset.x, offset.y)),
        );
        let visible = match clip {
            Some(clip) => rect.intersect(clip),
            None => Some(rect),
        };
        visible.is_none_or(|visible| corners.admits(expand_rect(visible, corners.aa_margin)))
    };
    nodes
        .iter()
        .all(|child| node_admits_corners(child, offset, inherited_clip, corners, &check))
}

fn node_admits_corners(
    node: &RenderNode,
    offset: Point,
    inherited_clip: Option<Rect>,
    corners: &RoundedClipCorners,
    check: &impl Fn(Rect, Option<Rect>) -> bool,
) -> bool {
    match node {
        RenderNode::Primitive(entry) => match &entry.node {
            PrimitiveNode::Draw(draw) => {
                primitive_stays_clear(&draw.primitive, corners.raster_scale, |rect| {
                    check(rect, draw.clip)
                })
            }
            PrimitiveNode::Text(text) => text.draw_bounds().is_some_and(|rect| check(rect, None)),
        },
        RenderNode::DrawRun(run) => {
            run.coverage_rects().all(|rect| check(rect, None))
                && (!run.summary.has_shadow
                    || run_others_stay_clear(run, corners.raster_scale, |rect| check(rect, None)))
        }
        RenderNode::Layer(child) => {
            if child.graphics_layer.shadow_elevation > 0.0 {
                return false;
            }
            let Some(translation) = direct_translation(child.transform_to_parent) else {
                return child_stays_clear(child, offset, corners);
            };
            // A child whose bounds stay clear holds content that stays clear.
            let clear = child_stays_clear(child, offset, corners);
            if clear || child_needs_surface(child) {
                return clear;
            }
            let child_offset = Point::new(offset.x + translation.x, offset.y + translation.y);
            layer_admits_corners(child, child_offset, inherited_clip, corners)
        }
        RenderNode::Inline(inline) => {
            inline_stays_clear(inline, offset, corners)
                || nodes_admit_corners(
                    &inline.content,
                    Point::new(offset.x + inline.origin.x, offset.y + inline.origin.y),
                    inherited_clip,
                    corners,
                )
        }
    }
}

/// The radius a layer whose rounded clip cuts into its content draws in
/// place with, its records taking the clip's coverage as its surface's
/// composite would: a uniform one, with nothing in the corners but shapes
/// and images drawn straight under that clip. Text, shadows, layers that
/// composite and anything under a clip of its own stay out of the corners,
/// which the rect clip alone then leaves whole.
pub(super) fn content_takes_rounded_clip(
    layer: &LayerNode,
    clip: LayerRoundedClip,
    raster_scale: RasterScale,
) -> Option<f32> {
    let radius = clip.radii[0];
    let uniform = clip
        .radii
        .iter()
        .all(|corner| (corner - radius).abs() <= AFFINE_TOLERANCE);
    (uniform
        && layer.visual_clip_rect() == Some(clip.rect)
        && nodes_take_corners(
            &layer.children,
            Point::default(),
            &RoundedClipCorners::of(clip, raster_scale),
        ))
    .then_some(radius)
}

fn nodes_take_corners(nodes: &[RenderNode], offset: Point, corners: &RoundedClipCorners) -> bool {
    nodes.iter().all(|node| match node {
        RenderNode::Primitive(entry) => match &entry.node {
            PrimitiveNode::Draw(draw)
                if draw.clip.is_none() && takes_rounded_clip(&draw.primitive) =>
            {
                true
            }
            PrimitiveNode::Draw(draw) => {
                primitive_stays_clear(&draw.primitive, corners.raster_scale, |rect| {
                    stays_clear(rect, offset, corners)
                })
            }
            PrimitiveNode::Text(text) => text
                .draw_bounds()
                .is_some_and(|rect| stays_clear(rect, offset, corners)),
        },
        RenderNode::DrawRun(run) => run_takes_corners(run, offset, corners),
        RenderNode::Layer(child) => child_takes_corners(child, offset, corners),
        RenderNode::Inline(inline) => {
            inline_stays_clear(inline, offset, corners)
                || nodes_take_corners(
                    &inline.content,
                    Point::new(offset.x + inline.origin.x, offset.y + inline.origin.y),
                    corners,
                )
        }
    })
}

fn child_takes_corners(child: &LayerNode, offset: Point, corners: &RoundedClipCorners) -> bool {
    // A child whose bounds stay clear holds content that stays clear.
    if child_stays_clear(child, offset, corners) {
        return true;
    }
    let plain = child.visual_clip_rect().is_none()
        && rounded_clip_for_layer(child).is_none()
        && child.graphics_layer.shadow_elevation <= 0.0
        && !child_needs_surface(child);
    match direct_translation(child.transform_to_parent) {
        Some(translation) if plain => nodes_take_corners(
            &child.children,
            Point::new(offset.x + translation.x, offset.y + translation.y),
            corners,
        ),
        _ => false,
    }
}

// Whether everything `inline`, a node drawn in the layer at `offset`, puts
// down stays clear of the corners: it draws within its rect, and that rect
// does.
fn inline_stays_clear(inline: &InlineNode, offset: Point, corners: &RoundedClipCorners) -> bool {
    inline.draws_within_bounds()
        && stays_clear(
            expand_rect(
                inline.node_rect(),
                cranpose_render_common::graph::CONTAINED_DRAW_SLACK,
            )
            .translate(inline.origin.x, inline.origin.y),
            offset,
            corners,
        )
}

fn child_stays_clear(child: &LayerNode, offset: Point, corners: &RoundedClipCorners) -> bool {
    if !child.draws_within_bounds() || child.graphics_layer.shadow_elevation > 0.0 {
        return false;
    }
    let padding = cranpose_render_common::graph::CONTAINED_DRAW_SLACK
        + child.effect().map_or(0.0, RenderEffect::output_padding);
    stays_clear(
        child
            .transform_to_parent
            .bounds_for_rect(expand_rect(child.local_bounds, padding)),
        offset,
        corners,
    )
}

/// Whether a run's shapes and images may take the corners: the rest of its
/// other lane (text, shadows) stays out of them.
fn run_takes_corners(run: &DrawRunNode, offset: Point, corners: &RoundedClipCorners) -> bool {
    run_others_all(run, |primitive| {
        takes_rounded_clip(primitive)
            || primitive_stays_clear(primitive, corners.raster_scale, |rect| {
                stays_clear(rect, offset, corners)
            })
    })
}

fn run_others_stay_clear(
    run: &DrawRunNode,
    raster_scale: RasterScale,
    clear: impl Fn(Rect) -> bool,
) -> bool {
    run_others_all(run, |primitive| {
        primitive_stays_clear(primitive, raster_scale, &clear)
    })
}

/// Whether every primitive of the run's other lane is one `keeps`.
fn run_others_all(run: &DrawRunNode, keeps: impl Fn(&DrawPrimitive) -> bool) -> bool {
    let recording = &*run.recording;
    recording
        .segments_in(&run.segments)
        .all(|segment| match segment.lane {
            RecordLane::Shapes
            | RecordLane::Content
            | RecordLane::GroupStart
            | RecordLane::GroupEnd => true,
            RecordLane::Others => recording.others()[segment.range()].iter().all(&keeps),
        })
}

fn primitive_stays_clear(
    primitive: &DrawPrimitive,
    raster_scale: RasterScale,
    clear: impl Fn(Rect) -> bool,
) -> bool {
    let mut primitive = primitive;
    while let DrawPrimitive::Blend {
        primitive: inner, ..
    } = primitive
    {
        primitive = inner;
    }
    let bounds = match primitive {
        DrawPrimitive::Shadow(ShadowPrimitive::Drop {
            shape, blur_radius, ..
        }) => {
            let reach = raster_scale.shadow_reach(*blur_radius);
            primitive_coverage_rect(shape).map(|rect| expand_rect(rect, reach))
        }
        DrawPrimitive::Shadow(ShadowPrimitive::Inner { clip_rect, .. }) => Some(*clip_rect),
        DrawPrimitive::Content => return true,
        _ => primitive_coverage_rect(primitive),
    };
    match bounds {
        Some(rect) => {
            [rect.x, rect.y, rect.width, rect.height]
                .into_iter()
                .all(f32::is_finite)
                && clear(rect)
        }
        None => false,
    }
}

fn stays_clear(rect: Rect, offset: Point, corners: &RoundedClipCorners) -> bool {
    corners.admits(expand_rect(
        rect.translate(offset.x, offset.y),
        corners.aa_margin,
    ))
}

/// Whether a primitive takes a rounded clip's coverage in its own shader: a
/// shape record in the shape shader, or an image in the image shader.
fn takes_rounded_clip(primitive: &DrawPrimitive) -> bool {
    matches!(
        primitive,
        DrawPrimitive::Rect { .. }
            | DrawPrimitive::RoundRect { .. }
            | DrawPrimitive::Arc { .. }
            | DrawPrimitive::Line { .. }
            | DrawPrimitive::Trapezoid { .. }
            | DrawPrimitive::Image { .. }
    )
}