rcus-render 0.1.4

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};

#[repr(C)]
#[derive(Clone, Copy, Debug, Pod, Zeroable)]
pub struct Vertex {
    pub position: [f32; 2],
    pub 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 {
    /// Solid quads, parents before children so children paint on top.
    pub quads: Vec<Vertex>,
    /// 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 quad vertex, or `None` when unclipped.
    pub quad_scissors: Vec<Option<u16>>,
}

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

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

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

/// Appends a solid rectangle in normalized device coordinates.
pub fn push_rect(out: &mut Vec<Vertex>, viewport: Size, rect: Rect, color: [f32; 4]) {
    if rect.width <= 0.0 || rect.height <= 0.0 || viewport.width <= 0.0 || viewport.height <= 0.0 {
        return;
    }
    let x0 = rect.x / viewport.width * 2.0 - 1.0;
    let x1 = rect.right() / viewport.width * 2.0 - 1.0;
    let y0 = 1.0 - rect.y / viewport.height * 2.0;
    let y1 = 1.0 - rect.bottom() / viewport.height * 2.0;
    for (x, y) in [(x0, y0), (x1, y0), (x1, y1), (x0, y0), (x1, y1), (x0, y1)] {
        out.push(Vertex {
            position: [x, y],
            color,
        });
    }
}

/// 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_rect(
        &mut frame.quads,
        viewport,
        Rect::new(0.0, 0.0, viewport.width, viewport.height),
        [0.02, 0.02, 0.03, 1.0],
    );
    // One scissor index per vertex, so a run can be sliced at any quad.
    frame.quad_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
    });
    if let Some(color) = node.background {
        push_rect(
            &mut frame.quads,
            viewport,
            node.rect,
            [color.r, color.g, color.b, color.a],
        );
        frame
            .quad_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))
}