Draw in the host: the wasm compositor sends draw ops, the host rasterises natively
CI / test (push) Failing after 29s

The wasm software renderer cost ~10-20 ns/pixel, so any changed frame took ~100+ ms at 1080p and
the desktop swung between idle and very slow. The compositor still builds the scene (windows,
decorations, panel, wallpaper) but a new moonplasma:host/raster interface turns it into pixels
in the host:
- host-wasm/src/raster.rs: a port of compositor/renderer (same blend arithmetic: fills, strokes,
  lines, circles, text, clips, shadows, surface blits), a wallpaper+desktop-card cache, and captured
  client surfaces (copied out of the shared memory once at commit, converted to RGBA, solid ones
  blit as row copies). 9 unit tests; a full frame matches the native software renderer except for
  text antialiasing (0.3% of pixels).
- compositor/raster sends a SceneGraph as ops; compositor.compose_scene() returns it only when
  something changed. The login session shows the host framebuffer directly (display.present-frame),
  the nested window gets it as a memfd (raster.export-memfd), --gfx-out reads it (read-frame).
- Client buffers never enter wasm: snapshot_shm_buffer captures in the host and keeps an id.
- Loop pacing sleeps the rest of the frame budget instead of a fixed 16/8 ms.
Full-screen terminal flooding output at 1080p: ~2 fps / 94% CPU -> ~57 fps; idle ~9%.
The native build keeps the software renderer.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
nandiandClaude Sonnet 5.5 committed 2026-11-25 04:39:40 -08:00
1 parent 66bf293085
commit c6e31b4a8f
38 files changed
+2141 -220

No files matched your search

+72 -41
View File
@@ -16,6 +16,7 @@ use wasmtime::component::{Component, HasSelf, Linker};
use wasmtime::{Config, Engine, Result, Store};
mod plasmoid;
mod raster;
#[cfg(feature = "drm")]
mod kms;
@@ -24,14 +25,14 @@ wasmtime::component::bindgen!({
world: "compositor",
// The desktop value types are the same WIT the modules use: share the Rust types, so draw ops
// flow from a module straight to the compositor without conversion.
// Draw operations are compared to reuse the cached wallpaper.
additional_derives: [PartialEq],
with: {
"moonplasma:desktop/types@0.1.0": plasmoid::ph::moonplasma::desktop::types,
"moonplasma:desktop/theme@0.1.0": plasmoid::ph::moonplasma::desktop::theme,
},
});
use ab_glyph::{Font, FontVec, OutlineCurve};
use ab_glyph_rasterizer::{point, Rasterizer};
use moonplasma::host::font::Glyph;
use moonplasma::host::sys::{Host, Received};
@@ -41,8 +42,10 @@ struct State {
private_bus: Option<String>,
bus_tried: bool,
started: Option<std::time::Instant>,
/// TTF faces loaded by the component (`font.load`), by slot.
fonts: [Option<FontVec>; 4],
/// TTF faces loaded by the component (`font.load`), by slot, and their glyph cache.
fonts: raster::Fonts,
/// The framebuffer and client surfaces behind `moonplasma:host/raster`.
raster: raster::Raster,
/// Runs the panel modules; set once the engine exists.
pl: Option<plasmoid::Runtime>,
}
@@ -254,6 +257,10 @@ impl moonplasma::host::display::Host for State {
#[cfg(not(feature = "drm"))]
false
}
fn present_frame(&mut self) {
#[cfg(feature = "drm")]
kms::present(&self.raster.fb, self.raster.w as u32, self.raster.h as u32);
}
fn present(&mut self, pixels: Vec<u8>, width: u32, height: u32) {
#[cfg(feature = "drm")]
kms::present(&pixels, width, height);
@@ -280,50 +287,73 @@ impl moonplasma::host::display::Host for State {
impl moonplasma::host::font::Host for State {
fn load(&mut self, slot: u32, path: String) -> bool {
if slot as usize >= self.fonts.len() {
return false;
self.fonts.load(slot, &path)
}
fn rasterise(&mut self, slot: u32, codepoint: u32, size: u32) -> Glyph {
let g = self.fonts.glyph(slot, codepoint, size);
Glyph { width: g.w, height: g.h, xoff: g.xoff, yoff: g.yoff, advance: g.advance, coverage: g.coverage.clone() }
}
}
impl moonplasma::host::raster::Host for State {
fn capture(&mut self, fd: i32, offset: i32, stride: i32, width: i32, height: i32, format: i32) -> u32 {
if fd < 0 || offset < 0 || stride <= 0 || width <= 0 || height <= 0 {
return 0;
}
match std::fs::read(path).ok().and_then(|d| FontVec::try_from_vec(d).ok()) {
Some(f) => {
self.fonts[slot as usize] = Some(f);
true
let len = stride as i64 * height as i64;
let end = offset as i64 + len;
unsafe {
let mut st: libc::stat = std::mem::zeroed();
if libc::fstat(fd, &mut st) < 0 || (st.st_size as i64) < end {
return 0;
}
// Mapping a large pool only reserves address space; just the pages copied are touched.
let p = libc::mmap(std::ptr::null_mut(), end as usize, libc::PROT_READ, libc::MAP_SHARED, fd, 0);
if p == libc::MAP_FAILED {
return 0;
}
let src = std::slice::from_raw_parts((p as *const u8).add(offset as usize), len as usize);
let surface = raster::Surface::from_bgra(src, stride as usize, width, height, format == 1);
libc::munmap(p, end as usize);
match surface {
Some(s) => self.raster.add_surface(s),
None => 0,
}
None => false,
}
}
/// Same maths as stb_truetype in the native build: the size is an em size in pixels, the glyph
/// origin sits on the integer pixel grid, and the bitmap box is the outline's floor/ceil bounds.
fn rasterise(&mut self, slot: u32, codepoint: u32, size: u32) -> Glyph {
let blank = Glyph { width: 0, height: 0, xoff: 0, yoff: 0, advance: 0, coverage: Vec::new() };
let Some(Some(font)) = self.fonts.get(slot as usize) else { return blank };
let ch = char::from_u32(codepoint).unwrap_or('\u{fffd}');
let id = font.glyph_id(ch);
let s = size as f32 / font.units_per_em().unwrap_or(1000.0);
let advance = (font.h_advance_unscaled(id) * s + 0.5) as i32;
let Some(outline) = font.outline(id) else { return Glyph { advance, ..blank } };
// Font units grow upward, pixels downward; ab_glyph stores the outline's top edge as
// `min.y` and its bottom edge as `max.y`, both in font units.
let x0 = (outline.bounds.min.x * s).floor() as i32;
let x1 = (outline.bounds.max.x * s).ceil() as i32;
let y0 = (-outline.bounds.min.y * s).floor() as i32;
let y1 = (-outline.bounds.max.y * s).ceil() as i32;
let (w, h) = (x1 - x0, y1 - y0);
if w <= 0 || h <= 0 {
return Glyph { advance, ..blank };
}
let tp = |p: ab_glyph::Point| point(p.x * s - x0 as f32, -p.y * s - y0 as f32);
let mut r = Rasterizer::new(w as usize, h as usize);
for c in &outline.curves {
match c {
OutlineCurve::Line(a, b) => r.draw_line(tp(*a), tp(*b)),
OutlineCurve::Quad(a, b, c) => r.draw_quad(tp(*a), tp(*b), tp(*c)),
OutlineCurve::Cubic(a, b, c, d) => r.draw_cubic(tp(*a), tp(*b), tp(*c), tp(*d)),
fn release(&mut self, id: u32) {
self.raster.release(id);
}
fn submit(&mut self, f: moonplasma::host::raster::Frame) {
self.raster.submit(&f, &mut self.fonts);
}
fn read_frame(&mut self) -> Vec<u8> {
self.raster.fb.clone()
}
fn export_memfd(&mut self) -> i32 {
let data = self.raster.to_argb8888();
let Ok(name) = CString::new("moon-plasma-frame") else { return -1 };
unsafe {
let fd = libc::memfd_create(name.as_ptr(), libc::MFD_CLOEXEC);
if fd < 0 {
return -1;
}
let mut done = 0usize;
while done < data.len() {
let n = libc::write(fd, data[done..].as_ptr() as *const _, data.len() - done);
if n <= 0 {
libc::close(fd);
return -1;
}
done += n as usize;
}
fd
}
let mut coverage = vec![0u8; (w * h) as usize];
r.for_each_pixel(|i, a| coverage[i] = (a.clamp(0.0, 1.0) * 255.0 + 0.5) as u8);
Glyph { width: w, height: h, xoff: x0, yoff: y0, advance, coverage }
}
}
@@ -686,6 +716,7 @@ fn main() -> Result<()> {
let mut linker: Linker<State> = Linker::new(&engine);
moonplasma::host::sys::add_to_linker::<State, HasSelf<State>>(&mut linker, |s| s)?;
moonplasma::host::font::add_to_linker::<State, HasSelf<State>>(&mut linker, |s| s)?;
moonplasma::host::raster::add_to_linker::<State, HasSelf<State>>(&mut linker, |s| s)?;
moonplasma::host::display::add_to_linker::<State, HasSelf<State>>(&mut linker, |s| s)?;
moonplasma::host::plasmoids::add_to_linker::<State, HasSelf<State>>(&mut linker, |s| s)?;
let mut store = Store::new(&engine, State::default());
+1
View File
@@ -19,6 +19,7 @@ pub mod ph {
wasmtime::component::bindgen!({
path: "../wit",
world: "plasmoid-host",
additional_derives: [PartialEq],
});
}
use ph::exports::moonplasma::desktop as ex;
+778
View File
@@ -0,0 +1,778 @@
//! The host's rasteriser (`moonplasma:host/raster`).
//!
//! A direct port of compositor/renderer (the pure-MoonBit software renderer), so a frame comes out
//! pixel for pixel the same, but native: the compositor component sends draw operations and window
//! surface ids, and the pixels never cross the component boundary. Window buffers are copied out of
//! the client's shared memory once, at commit (`capture`), converted to RGBA, and kept here.
use crate::moonplasma::host::raster as wt;
use ab_glyph::{Font, FontVec, OutlineCurve};
use ab_glyph_rasterizer::{point, Rasterizer};
use std::collections::HashMap;
use std::rc::Rc;
// ---------------------------------------------------------------- fonts
/// A rasterised glyph: an 8-bit coverage bitmap whose top-left sits at (`xoff`, `yoff`) from the
/// pen on the baseline (y grows downward), and the pen advance.
pub struct Glyph {
pub w: i32,
pub h: i32,
pub xoff: i32,
pub yoff: i32,
pub advance: i32,
pub coverage: Vec<u8>,
}
/// TTF faces loaded by the component (`font.load`), by slot, and a cache of their glyphs.
#[derive(Default)]
pub struct Fonts {
faces: [Option<FontVec>; 4],
cache: HashMap<(u32, u32, u32), Rc<Glyph>>,
}
impl Fonts {
pub fn load(&mut self, slot: u32, path: &str) -> bool {
if slot as usize >= self.faces.len() {
return false;
}
match std::fs::read(path).ok().and_then(|d| FontVec::try_from_vec(d).ok()) {
Some(f) => {
self.faces[slot as usize] = Some(f);
self.cache.retain(|k, _| k.0 != slot);
true
}
None => false,
}
}
fn has(&self, slot: u32) -> bool {
self.faces.get(slot as usize).map_or(false, |f| f.is_some())
}
/// Same maths as stb_truetype in the native build: the size is an em size in pixels, the glyph
/// origin sits on the integer pixel grid, and the bitmap box is the outline's floor/ceil bounds.
pub fn glyph(&mut self, slot: u32, cp: u32, size: u32) -> Rc<Glyph> {
if let Some(g) = self.cache.get(&(slot, cp, size)) {
return g.clone();
}
let g = Rc::new(self.rasterise(slot, cp, size));
self.cache.insert((slot, cp, size), g.clone());
g
}
fn rasterise(&self, slot: u32, cp: u32, size: u32) -> Glyph {
let blank = Glyph { w: 0, h: 0, xoff: 0, yoff: 0, advance: 0, coverage: Vec::new() };
let Some(Some(font)) = self.faces.get(slot as usize) else { return blank };
let ch = char::from_u32(cp).unwrap_or('\u{fffd}');
let id = font.glyph_id(ch);
let s = size as f32 / font.units_per_em().unwrap_or(1000.0);
let advance = (font.h_advance_unscaled(id) * s + 0.5) as i32;
let Some(outline) = font.outline(id) else { return Glyph { advance, ..blank } };
// Font units grow upward, pixels downward; ab_glyph stores the outline's top edge as
// `min.y` and its bottom edge as `max.y`, both in font units.
let x0 = (outline.bounds.min.x * s).floor() as i32;
let x1 = (outline.bounds.max.x * s).ceil() as i32;
let y0 = (-outline.bounds.min.y * s).floor() as i32;
let y1 = (-outline.bounds.max.y * s).ceil() as i32;
let (w, h) = (x1 - x0, y1 - y0);
if w <= 0 || h <= 0 {
return Glyph { advance, ..blank };
}
let tp = |p: ab_glyph::Point| point(p.x * s - x0 as f32, -p.y * s - y0 as f32);
let mut r = Rasterizer::new(w as usize, h as usize);
for c in &outline.curves {
match c {
OutlineCurve::Line(a, b) => r.draw_line(tp(*a), tp(*b)),
OutlineCurve::Quad(a, b, c) => r.draw_quad(tp(*a), tp(*b), tp(*c)),
OutlineCurve::Cubic(a, b, c, d) => r.draw_cubic(tp(*a), tp(*b), tp(*c), tp(*d)),
}
}
let mut coverage = vec![0u8; (w * h) as usize];
r.for_each_pixel(|i, a| coverage[i] = (a.clamp(0.0, 1.0) * 255.0 + 0.5) as u8);
Glyph { w, h, xoff: x0, yoff: y0, advance, coverage }
}
/// The glyph for `cp` in the face the UI uses for (bold, mono), and whether it must be
/// emboldened (a face with no bold instance gets its glyphs drawn a pixel wider).
/// Slots: 0 mono, 1 mono bold, 2 sans. None when no face is loaded at all.
fn pick(&mut self, cp: u32, size: u32, bold: bool, mono: bool) -> Option<(Rc<Glyph>, bool)> {
let has_mono = self.has(0);
let has_sans = self.has(2);
if !has_mono && !has_sans {
return None;
}
let has_bold = has_mono && self.has(1);
let (slot, embolden) = if mono && has_mono {
if bold && has_bold { (1, false) } else { (0, bold) }
} else if has_sans {
(2, bold)
} else {
(0, bold)
};
Some((self.glyph(slot, cp, size), embolden))
}
}
// ---------------------------------------------------------------- canvas
/// What every drawing function paints on: an RGBA8888 buffer.
pub struct Canvas<'a> {
pub w: i32,
pub h: i32,
pub data: &'a mut [u8],
}
#[derive(Clone, Copy)]
struct R {
x: i32,
y: i32,
w: i32,
h: i32,
}
impl From<wt::Rect> for R {
fn from(r: wt::Rect) -> R {
R { x: r.x, y: r.y, w: r.w, h: r.h }
}
}
type Clip = Option<R>;
fn clamp_u8(v: i32) -> u8 {
v.clamp(0, 255) as u8
}
/// Blend one pixel; `clip` and the canvas bounds are checked.
fn blend_pixel(c: &mut Canvas, x: i32, y: i32, r: i32, g: i32, b: i32, a: i32, clip: Clip) {
if x < 0 || y < 0 || x >= c.w || y >= c.h || a <= 0 {
return;
}
if let Some(k) = clip {
if x < k.x || y < k.y || x >= k.x + k.w || y >= k.y + k.h {
return;
}
}
let off = ((y * c.w + x) * 4) as usize;
let d = &mut c.data[off..off + 4];
if a >= 255 {
d[0] = r as u8;
d[1] = g as u8;
d[2] = b as u8;
d[3] = 0xff;
return;
}
let inv = 255 - a;
d[0] = ((r * a + d[0] as i32 * inv + 127) / 255) as u8;
d[1] = ((g * a + d[1] as i32 * inv + 127) / 255) as u8;
d[2] = ((b * a + d[2] as i32 * inv + 127) / 255) as u8;
d[3] = clamp_u8(a + (d[3] as i32 * inv + 127) / 255);
}
/// Blend a colour over pixels [xa, xb) of row `y`; the span is already clipped.
fn blend_span(c: &mut Canvas, y: i32, xa: i32, xb: i32, r: i32, g: i32, b: i32, a: i32) {
if xa >= xb || a <= 0 {
return;
}
let row = &mut c.data[((y * c.w + xa) * 4) as usize..((y * c.w + xb) * 4) as usize];
if a >= 255 {
for p in row.chunks_exact_mut(4) {
p[0] = r as u8;
p[1] = g as u8;
p[2] = b as u8;
p[3] = 0xff;
}
return;
}
let inv = 255 - a;
let (ra, ga, ba) = (r * a + 127, g * a + 127, b * a + 127);
for p in row.chunks_exact_mut(4) {
p[0] = ((ra + p[0] as i32 * inv) / 255) as u8;
p[1] = ((ga + p[1] as i32 * inv) / 255) as u8;
p[2] = ((ba + p[2] as i32 * inv) / 255) as u8;
p[3] = clamp_u8(a + (p[3] as i32 * inv + 127) / 255);
}
}
/// True when (px, py) is inside the rectangle whose corners have radius `rad`.
fn in_rounded_rect(px: i32, py: i32, rx: i32, ry: i32, rw: i32, rh: i32, rad: i32) -> bool {
if px < rx || py < ry || px >= rx + rw || py >= ry + rh {
return false;
}
if rad <= 0 {
return true;
}
let max_r = rw.min(rh) / 2;
let r = rad.min(max_r);
if r <= 0 {
return true;
}
let (x_left, x_right) = (rx + r, rx + rw - r - 1);
let (y_top, y_bot) = (ry + r, ry + rh - r - 1);
let corner = |dx: i32, dy: i32| dx * dx + dy * dy <= r * r;
if px < x_left && py < y_top {
corner(x_left - px, y_top - py)
} else if px > x_right && py < y_top {
corner(px - x_right, y_top - py)
} else if px < x_left && py > y_bot {
corner(x_left - px, py - y_bot)
} else if px > x_right && py > y_bot {
corner(px - x_right, py - y_bot)
} else {
true
}
}
/// The part of `rect` that is on the canvas and inside `clip`, as (x0, y0, x1, y1).
fn visible(c: &Canvas, rect: R, clip: Clip) -> Option<(i32, i32, i32, i32)> {
let (mut x0, mut y0) = (rect.x.max(0), rect.y.max(0));
let (mut x1, mut y1) = ((rect.x + rect.w).min(c.w), (rect.y + rect.h).min(c.h));
if let Some(k) = clip {
x0 = x0.max(k.x);
y0 = y0.max(k.y);
x1 = x1.min(k.x + k.w);
y1 = y1.min(k.y + k.h);
}
if x0 >= x1 || y0 >= y1 { None } else { Some((x0, y0, x1, y1)) }
}
fn fill_rounded_rect(c: &mut Canvas, rect: R, col: wt::Color, radius: i32, clip: Clip) {
if rect.w <= 0 || rect.h <= 0 || col.a == 0 {
return;
}
let Some((x0, y0, x1, y1)) = visible(c, rect, clip) else { return };
let (cr, cg, cb, ca) = (col.r as i32, col.g as i32, col.b as i32, col.a as i32);
if radius <= 0 {
for y in y0..y1 {
blend_span(c, y, x0, x1, cr, cg, cb, ca);
}
return;
}
let r = radius.min(rect.w.min(rect.h) / 2);
let (x_left, x_right) = (rect.x + r, rect.x + rect.w - r - 1);
let (y_top, y_bot) = (rect.y + r, rect.y + rect.h - r - 1);
for y in y0..y1 {
if y >= y_top && y <= y_bot {
blend_span(c, y, x0, x1, cr, cg, cb, ca);
continue;
}
let mut x = x0;
while x < x1 && x < x_left {
if in_rounded_rect(x, y, rect.x, rect.y, rect.w, rect.h, radius) {
blend_span(c, y, x, x + 1, cr, cg, cb, ca);
}
x += 1;
}
let (mid_a, mid_b) = (x_left.max(x0), (x_right + 1).min(x1));
blend_span(c, y, mid_a, mid_b, cr, cg, cb, ca);
x = (x_right + 1).max(x0).max(mid_a);
while x < x1 {
if in_rounded_rect(x, y, rect.x, rect.y, rect.w, rect.h, radius) {
blend_span(c, y, x, x + 1, cr, cg, cb, ca);
}
x += 1;
}
}
}
fn stroke_rounded_rect(c: &mut Canvas, rect: R, col: wt::Color, width: i32, radius: i32, clip: Clip) {
if rect.w <= 0 || rect.h <= 0 || width <= 0 || col.a == 0 {
return;
}
let (x0, y0) = (rect.x.max(0), rect.y.max(0));
let (x1, y1) = ((rect.x + rect.w).min(c.w), (rect.y + rect.h).min(c.h));
let (cr, cg, cb, ca) = (col.r as i32, col.g as i32, col.b as i32, col.a as i32);
let (inner_x, inner_y) = (rect.x + width, rect.y + width);
let (inner_w, inner_h) = (rect.w - width * 2, rect.h - width * 2);
let inner_r = if radius > width { radius - width } else { 0 };
let (cx0, cx1, cy0, cy1) = match clip {
Some(k) => (k.x, k.x + k.w, k.y, k.y + k.h),
None => (0, c.w, 0, c.h),
};
// Rows where the inner rectangle is full width only have the two side strips to draw.
let (mid_a, mid_b) = (inner_y + inner_r, inner_y + inner_h - inner_r);
for y in y0..y1 {
if inner_w > 0 && inner_h > 0 && y >= mid_a && y < mid_b {
if y >= cy0 && y < cy1 {
let l0 = x0.max(cx0);
let l1 = inner_x.min(x1).min(cx1);
blend_span(c, y, l0, l1, cr, cg, cb, ca);
let r0 = (inner_x + inner_w).max(x0).max(cx0);
blend_span(c, y, r0, x1.min(cx1), cr, cg, cb, ca);
}
continue;
}
for x in x0..x1 {
let in_outer = in_rounded_rect(x, y, rect.x, rect.y, rect.w, rect.h, radius);
let in_inner = inner_w > 0
&& inner_h > 0
&& in_rounded_rect(x, y, inner_x, inner_y, inner_w, inner_h, inner_r);
if in_outer && !in_inner {
blend_pixel(c, x, y, cr, cg, cb, ca, clip);
}
}
}
}
fn draw_line(c: &mut Canvas, s: &wt::Segment, ox: i32, oy: i32, clip: Clip) {
let (cr, cg, cb, ca) = (s.color.r as i32, s.color.g as i32, s.color.b as i32, s.color.a as i32);
let half = if s.width <= 1 { 0 } else { s.width / 2 };
let (mut x0, mut y0) = (s.x0 + ox, s.y0 + oy);
let (x1, y1) = (s.x1 + ox, s.y1 + oy);
let dx = (x1 - x0).abs();
let sx = if x0 < x1 { 1 } else { -1 };
let dy = -(y1 - y0).abs();
let sy = if y0 < y1 { 1 } else { -1 };
let mut err = dx + dy;
loop {
for oy2 in -half..=half {
for ox2 in -half..=half {
blend_pixel(c, x0 + ox2, y0 + oy2, cr, cg, cb, ca, clip);
}
}
if x0 == x1 && y0 == y1 {
break;
}
let e2 = 2 * err;
if e2 >= dy {
err += dy;
x0 += sx;
}
if e2 <= dx {
err += dx;
y0 += sy;
}
}
}
fn draw_circle(c: &mut Canvas, d: &wt::Disc, ox: i32, oy: i32, clip: Clip) {
if d.radius <= 0 {
return;
}
let (cr, cg, cb, ca) = (d.color.r as i32, d.color.g as i32, d.color.b as i32, d.color.a as f64);
let rad = d.radius as f64;
let (cx, cy) = (d.cx + ox, d.cy + oy);
for dy in (-d.radius - 1)..=(d.radius + 1) {
for dx in (-d.radius - 1)..=(d.radius + 1) {
let dist = ((dx * dx + dy * dy) as f64).sqrt();
let outer = rad + 0.5 - dist;
let mut cov = if outer > 1.0 { 1.0 } else { outer };
if !d.filled {
let inner = dist - (rad - 1.0 - 0.5);
let ic = if inner > 1.0 { 1.0 } else { inner };
if ic < cov {
cov = ic;
}
}
if cov > 0.02 {
blend_pixel(c, cx + dx, cy + dy, cr, cg, cb, (ca * cov).round() as i32, clip);
}
}
}
}
fn draw_text(c: &mut Canvas, fonts: &mut Fonts, t: &wt::Label, ox: i32, oy: i32, clip: Clip) {
if t.text.is_empty() || t.color.a == 0 {
return;
}
let size = t.size.max(0) as u32;
let mut glyphs: Vec<(Rc<Glyph>, bool)> = Vec::new();
let mut total_w = 0;
for ch in t.text.chars() {
match fonts.pick(ch as u32, size, t.bold, t.mono) {
Some((g, e)) => {
total_w += g.advance + if e { 1 } else { 0 };
glyphs.push((g, e));
}
None => return, // no face loaded: nothing to draw with
}
}
let x = t.x + ox;
let start_x = match t.align {
1 => x - total_w / 2,
2 => x - total_w,
_ => x,
};
// `y` is the vertical centre of the text; centre the capital height ('H') on it.
let Some((cap, _)) = fonts.pick(72, size, false, t.mono) else { return };
let baseline = t.y + oy + (-cap.yoff) / 2;
let (cr, cg, cb, ca) = (t.color.r as i32, t.color.g as i32, t.color.b as i32, t.color.a as i32);
let mut pen = start_x;
for (g, embolden) in &glyphs {
for row in 0..g.h {
for col in 0..g.w {
let cov = g.coverage[(row * g.w + col) as usize] as i32;
if cov > 0 {
let px = pen + g.xoff + col;
let py = baseline + g.yoff + row;
blend_pixel(c, px, py, cr, cg, cb, ca * cov / 255, clip);
if *embolden {
blend_pixel(c, px + 1, py, cr, cg, cb, ca * cov / 255, clip);
}
}
}
}
pen += g.advance + if *embolden { 1 } else { 0 };
}
}
/// Draw `ops` offset by (ox, oy), with the clip stack they push and pop.
fn draw_ops(c: &mut Canvas, fonts: &mut Fonts, ops: &[wt::Op], ox: i32, oy: i32) {
let mut stack: Vec<R> = Vec::new();
for op in ops {
let clip = stack.last().copied();
match op {
wt::Op::FillRect(f) => {
let r = R { x: f.area.x + ox, y: f.area.y + oy, w: f.area.w, h: f.area.h };
fill_rounded_rect(c, r, f.color, f.radius, clip);
}
wt::Op::StrokeRect(s) => {
let r = R { x: s.area.x + ox, y: s.area.y + oy, w: s.area.w, h: s.area.h };
stroke_rounded_rect(c, r, s.color, s.width, s.radius, clip);
}
wt::Op::DrawLine(l) => draw_line(c, l, ox, oy, clip),
wt::Op::DrawCircle(d) => draw_circle(c, d, ox, oy, clip),
wt::Op::DrawText(t) => draw_text(c, fonts, t, ox, oy, clip),
wt::Op::PushClip(r) => stack.push(R { x: r.x + ox, y: r.y + oy, w: r.w, h: r.h }),
wt::Op::PopClip => {
stack.pop();
}
}
}
}
// ---------------------------------------------------------------- surfaces
/// A client window buffer, copied out of its shared memory and converted to RGBA8888.
pub struct Surface {
w: i32,
h: i32,
rgba: Vec<u8>,
/// Every pixel has alpha 255 (XRGB, or an ARGB buffer that happens to be solid): blits copy rows.
opaque: bool,
}
impl Surface {
/// Build one from `h` rows of `stride` bytes of little-endian B, G, R, A (or X) pixels.
pub fn from_bgra(src: &[u8], stride: usize, w: i32, h: i32, xrgb: bool) -> Option<Surface> {
if w <= 0 || h <= 0 || stride < w as usize * 4 || src.len() < stride * (h as usize - 1) + w as usize * 4 {
return None;
}
let mut rgba = vec![0u8; w as usize * h as usize * 4];
let mut opaque = true;
for y in 0..h as usize {
let s = &src[y * stride..y * stride + w as usize * 4];
let d = &mut rgba[y * w as usize * 4..(y + 1) * w as usize * 4];
for (sp, dp) in s.chunks_exact(4).zip(d.chunks_exact_mut(4)) {
dp[0] = sp[2];
dp[1] = sp[1];
dp[2] = sp[0];
dp[3] = if xrgb { 0xff } else { sp[3] };
opaque &= dp[3] == 0xff;
}
}
Some(Surface { w, h, rgba, opaque })
}
}
/// Draw a client surface into `dst`. While the client catches up with a resize its buffer is smaller
/// than the window: the buffer's bottom-right colour is extended over the rest.
fn blit_surface(c: &mut Canvas, s: &Surface, dst: R) {
if s.w <= 0 || s.h <= 0 || dst.w <= 0 || dst.h <= 0 {
return;
}
if s.w < dst.w || s.h < dst.h {
let o = ((s.h - 1) * s.w + (s.w - 1)) as usize * 4;
let col = wt::Color { r: s.rgba[o], g: s.rgba[o + 1], b: s.rgba[o + 2], a: s.rgba[o + 3] };
fill_rounded_rect(c, dst, col, 0, None);
}
let (copy_w, copy_h) = (s.w.min(dst.w), s.h.min(dst.h));
let c0 = (-dst.x).max(0);
let c1 = copy_w.min(c.w - dst.x);
if c0 >= c1 {
return;
}
for row in 0..copy_h {
let dy = dst.y + row;
if dy < 0 || dy >= c.h {
continue;
}
let src = &s.rgba[((row * s.w + c0) * 4) as usize..((row * s.w + c1) * 4) as usize];
let d0 = ((dy * c.w + dst.x + c0) * 4) as usize;
let dst_row = &mut c.data[d0..d0 + src.len()];
if s.opaque {
dst_row.copy_from_slice(src);
} else {
for (sp, dp) in src.chunks_exact(4).zip(dst_row.chunks_exact_mut(4)) {
let a = sp[3] as i32;
if a >= 255 {
dp.copy_from_slice(sp);
} else if a > 0 {
let inv = 255 - a;
dp[0] = ((sp[0] as i32 * a + dp[0] as i32 * inv + 127) / 255) as u8;
dp[1] = ((sp[1] as i32 * a + dp[1] as i32 * inv + 127) / 255) as u8;
dp[2] = ((sp[2] as i32 * a + dp[2] as i32 * inv + 127) / 255) as u8;
dp[3] = clamp_u8(a + (dp[3] as i32 * inv + 127) / 255);
}
}
}
}
}
// ---------------------------------------------------------------- the rasteriser
/// The framebuffer, the wallpaper cache and the captured client surfaces.
#[derive(Default)]
pub struct Raster {
pub w: i32,
pub h: i32,
/// RGBA8888, `w * h * 4` bytes.
pub fb: Vec<u8>,
wallpaper: Option<(Vec<wt::Op>, i32, i32, Vec<u8>)>,
surfaces: HashMap<u32, Surface>,
next_id: u32,
}
impl Raster {
pub fn add_surface(&mut self, s: Surface) -> u32 {
self.next_id = self.next_id.wrapping_add(1).max(1);
self.surfaces.insert(self.next_id, s);
self.next_id
}
pub fn release(&mut self, id: u32) {
self.surfaces.remove(&id);
}
pub fn surface_count(&self) -> usize {
self.surfaces.len()
}
/// Draw a frame into the framebuffer: wallpaper (cached), background, windows bottom to top,
/// panel, then client popups. The same layering as the software renderer's `render_scene`.
pub fn submit(&mut self, f: &wt::Frame, fonts: &mut Fonts) {
let (w, h) = (f.width.max(1), f.height.max(1));
if w != self.w || h != self.h || self.fb.len() != (w * h * 4) as usize {
self.w = w;
self.h = h;
self.fb = vec![0u8; (w * h * 4) as usize];
} else {
self.fb.fill(0);
}
let surfaces = &self.surfaces;
let mut c = Canvas { w, h, data: &mut self.fb };
// 1. Wallpaper: drawn once, copied back while unchanged.
match &f.wallpaper {
Some(ops) => {
let cached = matches!(&self.wallpaper, Some((o, cw, ch, _)) if *cw == w && *ch == h && o == ops);
if cached {
c.data.copy_from_slice(&self.wallpaper.as_ref().unwrap().3);
} else {
draw_ops(&mut c, fonts, ops, 0, 0);
self.wallpaper = Some((ops.clone(), w, h, c.data.to_vec()));
}
}
None => {
if let Some((_, cw, ch, px)) = &self.wallpaper {
if *cw == w && *ch == h {
c.data.copy_from_slice(px);
}
}
}
}
draw_ops(&mut c, fonts, &f.background, 0, 0);
// 2. Windows, bottom to top.
for win in &f.windows {
let g = R::from(win.geometry);
if !win.fullscreen {
let (outer_x, outer_y) = (g.x - win.inset_left, g.y - win.inset_top);
let outer_w = g.w + win.inset_left + win.inset_right;
let outer_h = g.h + win.inset_top + win.inset_bottom;
// Subtle drop shadow: only the strips that stick out from under the window (and the
// part under the translucent title bar) are blended.
let shadow = R { x: outer_x + 4, y: outer_y + 6, w: outer_w, h: outer_h };
let col = wt::Color { r: 0, g: 0, b: 0, a: 80 };
let strips = [
R { x: outer_x + outer_w, y: outer_y, w: 4, h: outer_h + 6 },
R { x: outer_x, y: outer_y + outer_h, w: outer_w + 4, h: 6 },
R { x: outer_x, y: outer_y, w: outer_w, h: win.inset_top + 2 },
];
for s in strips {
fill_rounded_rect(&mut c, shadow, col, 8, Some(s));
}
draw_ops(&mut c, fonts, &win.deco, outer_x, outer_y);
}
match surfaces.get(&win.surface) {
Some(s) => blit_surface(&mut c, s, g),
None => fill_rounded_rect(&mut c, g, wt::Color { r: 0x1e, g: 0x29, b: 0x3b, a: 0xff }, 0, None),
}
}
// 3. Panel (and its popups, menus and notices), then 4. client popups above everything.
draw_ops(&mut c, fonts, &f.panel, 0, 0);
for p in &f.popups {
if let Some(s) = surfaces.get(&p.surface) {
blit_surface(&mut c, s, R::from(p.area));
}
}
}
/// The framebuffer as little-endian ARGB8888 (B, G, R, A=255), `stride = w * 4`.
pub fn to_argb8888(&self) -> Vec<u8> {
let mut out = vec![0u8; self.fb.len()];
for (s, d) in self.fb.chunks_exact(4).zip(out.chunks_exact_mut(4)) {
d[0] = s[2];
d[1] = s[1];
d[2] = s[0];
d[3] = 0xff;
}
out
}
}
#[cfg(test)]
mod tests {
use super::*;
fn color(r: u8, g: u8, b: u8, a: u8) -> wt::Color {
wt::Color { r, g, b, a }
}
fn rect(x: i32, y: i32, w: i32, h: i32) -> wt::Rect {
wt::Rect { x, y, w, h }
}
fn fill(x: i32, y: i32, w: i32, h: i32, c: wt::Color, radius: i32) -> wt::Op {
wt::Op::FillRect(wt::Fill { area: rect(x, y, w, h), color: c, radius })
}
fn frame(w: i32, h: i32) -> wt::Frame {
wt::Frame { width: w, height: h, wallpaper: None, background: vec![], windows: vec![], panel: vec![], popups: vec![] }
}
fn px(r: &Raster, x: i32, y: i32) -> [u8; 4] {
let o = ((y * r.w + x) * 4) as usize;
[r.fb[o], r.fb[o + 1], r.fb[o + 2], r.fb[o + 3]]
}
#[test]
fn fills_blend_with_the_same_arithmetic_as_the_software_renderer() {
let mut r = Raster::default();
let mut f = frame(20, 10);
f.background = vec![fill(0, 0, 20, 10, color(10, 20, 30, 255), 0), fill(2, 2, 6, 6, color(200, 100, 0, 128), 0)];
r.submit(&f, &mut Fonts::default());
assert_eq!(px(&r, 0, 0), [10, 20, 30, 255]);
// (200*128 + 10*127 + 127) / 255 = 105, (100*128 + 20*127 + 127) / 255 = 60, (0 + 30*127 + 127) / 255 = 15
assert_eq!(px(&r, 3, 3), [105, 60, 15, 255]);
}
#[test]
fn rounded_corners_leave_the_corner_pixel_untouched() {
let mut r = Raster::default();
let mut f = frame(40, 40);
f.background = vec![fill(4, 4, 30, 30, color(255, 255, 255, 255), 10)];
r.submit(&f, &mut Fonts::default());
assert_eq!(px(&r, 4, 4), [0, 0, 0, 0]); // outside the rounded corner
assert_eq!(px(&r, 19, 19), [255, 255, 255, 255]);
assert_eq!(px(&r, 19, 4), [255, 255, 255, 255]); // straight edge
}
#[test]
fn stroke_draws_only_the_border() {
let mut r = Raster::default();
let mut f = frame(30, 30);
f.background = vec![wt::Op::StrokeRect(wt::Stroke { area: rect(2, 2, 20, 20), color: color(9, 9, 9, 255), width: 2, radius: 0 })];
r.submit(&f, &mut Fonts::default());
assert_eq!(px(&r, 2, 10), [9, 9, 9, 255]);
assert_eq!(px(&r, 3, 10), [9, 9, 9, 255]);
assert_eq!(px(&r, 4, 10), [0, 0, 0, 0]); // interior
assert_eq!(px(&r, 21, 10), [9, 9, 9, 255]);
assert_eq!(px(&r, 10, 21), [9, 9, 9, 255]);
}
#[test]
fn clip_ops_limit_drawing() {
let mut r = Raster::default();
let mut f = frame(20, 20);
f.background = vec![
wt::Op::PushClip(rect(5, 5, 5, 5)),
fill(0, 0, 20, 20, color(1, 2, 3, 255), 0),
wt::Op::PopClip,
fill(0, 0, 2, 2, color(7, 7, 7, 255), 0),
];
r.submit(&f, &mut Fonts::default());
assert_eq!(px(&r, 6, 6), [1, 2, 3, 255]);
assert_eq!(px(&r, 2, 2), [0, 0, 0, 0]);
assert_eq!(px(&r, 10, 10), [0, 0, 0, 0]);
assert_eq!(px(&r, 1, 1), [7, 7, 7, 255]);
}
#[test]
fn wallpaper_is_cached_and_reused_when_the_frame_says_unchanged() {
let mut r = Raster::default();
let mut fonts = Fonts::default();
let mut f = frame(16, 16);
f.wallpaper = Some(vec![fill(0, 0, 16, 16, color(50, 60, 70, 255), 0)]);
r.submit(&f, &mut fonts);
assert_eq!(px(&r, 8, 8), [50, 60, 70, 255]);
let mut g = frame(16, 16);
g.wallpaper = None; // unchanged: the cached pixels come back
g.background = vec![fill(0, 0, 2, 2, color(1, 1, 1, 255), 0)];
r.submit(&g, &mut fonts);
assert_eq!(px(&r, 8, 8), [50, 60, 70, 255]);
assert_eq!(px(&r, 0, 0), [1, 1, 1, 255]);
// A different wallpaper is drawn afresh.
f.wallpaper = Some(vec![fill(0, 0, 16, 16, color(9, 8, 7, 255), 0)]);
r.submit(&f, &mut fonts);
assert_eq!(px(&r, 8, 8), [9, 8, 7, 255]);
}
#[test]
fn windows_blit_their_surface_converted_from_bgra_and_shadow_only_sticks_out() {
let mut r = Raster::default();
// A 4x2 XRGB buffer, every pixel B=10 G=20 R=30.
let bgra: Vec<u8> = (0..8).flat_map(|_| [10u8, 20, 30, 0]).collect();
let id = r.add_surface(Surface::from_bgra(&bgra, 16, 4, 2, true).unwrap());
let mut f = frame(40, 30);
f.background = vec![fill(0, 0, 40, 30, color(200, 200, 200, 255), 0)];
f.windows = vec![wt::Window {
geometry: rect(10, 10, 4, 2),
inset_top: 0,
inset_right: 0,
inset_bottom: 0,
inset_left: 0,
deco: vec![],
fullscreen: false,
surface: id,
}];
r.submit(&f, &mut Fonts::default());
assert_eq!(px(&r, 10, 10), [30, 20, 10, 255]); // R, G, B order after conversion
assert_eq!(px(&r, 13, 11), [30, 20, 10, 255]);
// The shadow sits to the right of / below the window, not under it.
// The shadow rectangle is the window moved by (4, 6): (14..18, 16..18) here.
assert!(px(&r, 15, 17)[0] < 200, "shadow strip below and to the right");
assert_eq!(px(&r, 15, 12)[0], 200, "no shadow where the offset rectangle does not reach");
r.release(id);
assert_eq!(r.surface_count(), 0);
}
#[test]
fn translucent_surfaces_blend_over_what_is_behind() {
let mut r = Raster::default();
// One ARGB pixel: B=0 G=0 R=255 A=128, over a grey background.
let id = r.add_surface(Surface::from_bgra(&[0, 0, 255, 128], 4, 1, 1, false).unwrap());
let mut f = frame(8, 8);
f.background = vec![fill(0, 0, 8, 8, color(100, 100, 100, 255), 0)];
f.windows = vec![wt::Window { geometry: rect(2, 2, 1, 1), inset_top: 0, inset_right: 0, inset_bottom: 0, inset_left: 0, deco: vec![], fullscreen: true, surface: id }];
r.submit(&f, &mut Fonts::default());
// (255*128 + 100*127 + 127) / 255 = 178, (0 + 100*127 + 127) / 255 = 50
assert_eq!(px(&r, 2, 2), [178, 50, 50, 255]);
}
#[test]
fn argb_export_swaps_red_and_blue() {
let mut r = Raster::default();
let mut f = frame(2, 1);
f.background = vec![fill(0, 0, 2, 1, color(1, 2, 3, 255), 0)];
r.submit(&f, &mut Fonts::default());
assert_eq!(&r.to_argb8888()[..4], &[3, 2, 1, 255]);
}
}