rcus-render 0.2.0

wgpu renderer for rcus: solid quads, a runtime glyph atlas, and scissored text
Documentation
//! Vertex assembly for the two pipelines: solid quads and textured glyphs.
//! Everything is built per frame into one buffer each, so the renderer issues a
//! single draw per pipeline no matter how large the frame is.

use bytemuck::{Pod, Zeroable};
use rcus_layout::{LayoutNode, LayoutTree, Rect, Size};

/// One corner of a box, with everything the shader needs to draw it.
///
/// `local` is the pixel offset from the box's centre and `half` the half-extents
/// in pixels, so the fragment shader can measure distance to the rounded edge in
/// pixels rather than in normalised coordinates.
#[repr(C)]
#[derive(Clone, Copy, Debug, Pod, Zeroable)]
pub struct BoxVertex {
    pub position: [f32; 2],
    pub local: [f32; 2],
    pub half: [f32; 2],
    pub radius: f32,
    pub border_width: f32,
    pub fill: [f32; 4],
    pub border: [f32; 4],
    pub shadow_offset: [f32; 2],
    pub shadow_blur: f32,
    pub shadow_spread: f32,
    pub shadow_color: [f32; 4],
}

#[repr(C)]
#[derive(Clone, Copy, Debug, Pod, Zeroable)]
pub struct TextVertex {
    /// Device-space position in pixels, y down from the top of the viewport.
    pub position: [f32; 2],
    /// Atlas coordinates normalized to atlas size.
    pub uv: [f32; 2],
    pub color: [f32; 4],
    /// Atlas array layer holding this glyph's coverage.
    pub layer: f32,
}

/// A run of geometry that must be clipped, in device pixels.
#[derive(Clone, Copy, Debug)]
pub struct Scissor {
    pub x: f32,
    pub y: f32,
    pub width: f32,
    pub height: f32,
}

/// One assembled frame: solid quads, glyph quads, and their clip rectangles.
pub struct Frame {
    /// Boxes, parents before children so children paint on top.
    pub boxes: Vec<BoxVertex>,
    /// Glyph quads with their atlas coordinates.
    pub glyphs: Vec<TextVertex>,
    /// Clip rectangles referenced by the per-node scissor indices.
    pub scissors: Vec<Scissor>,
    /// Scissor index per glyph, or `None` when the glyph is unclipped.
    pub glyph_scissors: Vec<Option<u16>>,
    /// Scissor index per box vertex, or `None` when unclipped.
    pub box_scissors: Vec<Option<u16>>,
}

impl Frame {
    pub fn new() -> Self {
        Self {
            boxes: Vec::with_capacity(256),
            glyphs: Vec::with_capacity(4096),
            scissors: Vec::new(),
            glyph_scissors: Vec::new(),
            box_scissors: Vec::new(),
        }
    }

    pub fn is_empty(&self) -> bool {
        self.boxes.is_empty() && self.glyphs.is_empty()
    }
}

impl Default for Frame {
    fn default() -> Self {
        Self::new()
    }
}

/// The shape of one box, in the units the shader expects.
#[derive(Clone, Copy, Debug, Default)]
pub struct BoxStyle {
    pub radius: f32,
    pub border_width: f32,
    pub fill: [f32; 4],
    pub border: [f32; 4],
    pub shadow_offset: [f32; 2],
    pub shadow_blur: f32,
    pub shadow_spread: f32,
    pub shadow_color: [f32; 4],
}

impl BoxStyle {
    /// A plain filled rectangle, which is what every view that never mentions a
    /// radius or a border draws.
    pub fn fill(color: [f32; 4]) -> Self {
        Self {
            fill: color,
            ..Self::default()
        }
    }

    /// How far this box's shadow reaches past its edges.
    fn reach(&self) -> f32 {
        if self.shadow_color[3] <= 0.0 {
            return 0.0;
        }
        self.shadow_blur.abs()
            + self.shadow_spread.abs()
            + self.shadow_offset[0].abs().max(self.shadow_offset[1].abs())
    }
}

/// Appends a box, expanded to contain its shadow.
///
/// A shadow is drawn outside the box, so the quad has to be larger than the box
/// or the shadow would be clipped at the framebuffer edge. A box with no shadow
/// is exactly its own rect, which is what keeps a flat rectangle pixel-identical
/// to the plain fill it replaced.
pub fn push_box(out: &mut Vec<BoxVertex>, viewport: Size, rect: Rect, style: BoxStyle) {
    if rect.width <= 0.0 || rect.height <= 0.0 || viewport.width <= 0.0 || viewport.height <= 0.0 {
        return;
    }
    if style.fill[3] <= 0.0 && style.border[3] <= 0.0 && style.reach() <= 0.0 {
        return;
    }
    let reach = style.reach();
    let left = rect.x - reach;
    let top = rect.y - reach;
    let right = rect.right() + reach;
    let bottom = rect.bottom() + reach;
    let centre_x = rect.x + rect.width / 2.0;
    let centre_y = rect.y + rect.height / 2.0;
    let half = [rect.width / 2.0, rect.height / 2.0];
    let radius = style.radius.max(0.0).min(half[0].min(half[1]));
    let border_width =
        style
            .border_width
            .max(0.0)
            .min(half[0].min(half[1]))
            .min(if style.border[3] > 0.0 {
                half[0].min(half[1])
            } else {
                0.0
            });

    let x0 = left / viewport.width * 2.0 - 1.0;
    let x1 = right / viewport.width * 2.0 - 1.0;
    let y0 = 1.0 - top / viewport.height * 2.0;
    let y1 = 1.0 - bottom / viewport.height * 2.0;
    for (px, py) in [
        (left, top),
        (right, top),
        (right, bottom),
        (left, top),
        (right, bottom),
        (left, bottom),
    ] {
        out.push(BoxVertex {
            position: [
                px / viewport.width * 2.0 - 1.0,
                1.0 - py / viewport.height * 2.0,
            ],
            local: [px - centre_x, py - centre_y],
            half,
            radius,
            border_width,
            fill: style.fill,
            border: style.border,
            shadow_offset: style.shadow_offset,
            shadow_blur: style.shadow_blur,
            shadow_spread: style.shadow_spread,
            shadow_color: style.shadow_color,
        });
    }
    // The two triangles above share corners; keep the unused pair explicit so a
    // reader can see the winding is two triangles and not a strip.
    let _ = (x0, x1, y0, y1);
}

/// One glyph quad in device pixels, ready to be expanded into triangles.
#[derive(Clone, Copy, Debug)]
pub struct GlyphQuad {
    pub left: f32,
    pub top: f32,
    pub width: f32,
    pub height: f32,
    /// Atlas rectangle: u, v, width, height normalized to atlas size.
    pub uv: [f32; 4],
    pub color: [f32; 4],
    pub layer: f32,
}

/// Appends one glyph as two triangles, positions in device pixels.
pub fn push_glyph(out: &mut Vec<TextVertex>, quad: GlyphQuad) {
    let GlyphQuad {
        left,
        top,
        width,
        height,
        uv,
        color,
        layer,
    } = quad;
    let (u0, v0) = (uv[0], uv[1]);
    let (u1, v1) = (uv[0] + uv[2], uv[1] + uv[3]);
    for (x, y, u, v) in [
        (left, top, u0, v0),
        (left + width, top, u1, v0),
        (left + width, top + height, u1, v1),
        (left, top, u0, v0),
        (left + width, top + height, u1, v1),
        (left, top + height, u0, v1),
    ] {
        out.push(TextVertex {
            position: [x, y],
            uv: [u, v],
            color,
            layer,
        });
    }
}

/// Builds solid quads for a laid-out tree, honoring nested clip rectangles.
pub fn build_quads(tree: &LayoutTree) -> Frame {
    let mut frame = Frame::new();
    let viewport = tree.viewport;
    push_box(
        &mut frame.boxes,
        viewport,
        Rect::new(0.0, 0.0, viewport.width, viewport.height),
        BoxStyle::fill([0.02, 0.02, 0.03, 1.0]),
    );
    // One scissor index per vertex, so a run can be sliced at any box.
    frame.box_scissors.extend(std::iter::repeat_n(None, 6));
    collect_quads(&tree.root, viewport, None, &mut frame);
    frame
}

fn collect_quads(node: &LayoutNode, viewport: Size, inherited: Option<Rect>, frame: &mut Frame) {
    let mut clip = inherited;
    if node.clip {
        let rect = match clip {
            Some(parent) => intersect(parent, node.rect),
            None => node.rect,
        };
        if rect.width <= 0.0 || rect.height <= 0.0 {
            return;
        }
        clip = Some(rect);
    }
    let scissor = clip.filter(|rect| {
        !(rect.x <= node.rect.x
            && rect.y <= node.rect.y
            && rect.right() >= node.rect.right()
            && rect.bottom() >= node.rect.bottom())
    });
    let scissor_index = scissor.map(|rect| {
        frame.scissors.push(Scissor {
            x: rect.x,
            y: rect.y,
            width: rect.width,
            height: rect.height,
        });
        (frame.scissors.len() - 1) as u16
    });
    let fill = node.background;
    if fill.is_some() || node.border_color.is_some() || node.shadow.is_some() {
        let mut style = BoxStyle {
            fill: fill.map_or([0.0, 0.0, 0.0, 0.0], |color| {
                [color.r, color.g, color.b, color.a]
            }),
            ..BoxStyle::default()
        };
        style.radius = node.corner_radius();
        if let Some(border) = node.border_color {
            if node.border_width > 0.0 && border.a > 0.0 {
                style.border_width = node.border_width;
                style.border = [border.r, border.g, border.b, border.a];
            }
        }
        if let Some(shadow) = node.shadow {
            if !shadow.is_empty() {
                style.shadow_offset = [shadow.offset_x, shadow.offset_y];
                style.shadow_blur = shadow.blur;
                style.shadow_spread = shadow.spread;
                style.shadow_color = [
                    shadow.color.r,
                    shadow.color.g,
                    shadow.color.b,
                    shadow.color.a,
                ];
            }
        }
        push_box(&mut frame.boxes, viewport, node.rect, style);
        frame
            .box_scissors
            .extend(std::iter::repeat_n(scissor_index, 6));
    }
    for child in &node.children {
        collect_quads(child, viewport, clip, frame);
    }
}

pub fn intersect(a: Rect, b: Rect) -> Rect {
    let x = a.x.max(b.x);
    let y = a.y.max(b.y);
    let right = a.right().min(b.right());
    let bottom = a.bottom().min(b.bottom());
    Rect::new(x, y, (right - x).max(0.0), (bottom - y).max(0.0))
}