Add design persistence, world rendering, metrics overlay and logs
Some checks failed
ci / check (macos-latest) (push) Has been cancelled
ci / check (ubuntu-latest) (push) Has been cancelled
ci / check (windows-latest) (push) Has been cancelled

M3: STL/OBJ import with mesh validation, mass/COM/inertia, material database, RON scene with content-addressed blobs and v0->v1 migration. M4: deterministic heightmap terrain, trimesh colliders, wgpu renderer with instancing and depth, winit app with 1 kHz physics, fly camera, on-screen metrics overlay and per-frame CSV/dev logs. Docs: UI, logging, network and headless CLI plans.
This commit is contained in:
Loki 2026-11-16 23:34:05 +01:00
parent 79928b645b
commit 93075ab1fd
Signed by: boba
GPG key ID: 6CDE87BC9A778D97
107 changed files with 14785 additions and 46 deletions

View file

@ -0,0 +1,193 @@
//! CPU-side glyph packing for the overlay text atlas.
//!
//! The atlas is a single `R8` image: one byte of coverage per texel. Glyphs are
//! packed shelf by shelf and cached by `(char, pixel size)`, so a glyph is
//! rasterized and uploaded once per size.
/// Edge length of the square atlas texture, texels.
pub(super) const SIZE: u32 = 1024;
/// Empty texels kept between glyphs so linear filtering cannot bleed.
const PADDING: u32 = 1;
/// UV of a texel that is always opaque white, shared by solid rectangles and
/// lines so they can use the text pipeline.
pub(super) const WHITE_UV: [f32; 2] = [1.0 / 1024.0, 1.0 / 1024.0];
/// A rectangle of the atlas that has to be uploaded.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) struct Region {
pub(super) x: u32,
pub(super) y: u32,
pub(super) w: u32,
pub(super) h: u32,
}
/// A rasterized glyph placed in the atlas.
#[derive(Debug, Clone, Copy, PartialEq)]
pub(super) struct Glyph {
pub(super) uv: [f32; 2],
pub(super) uv_size: [f32; 2],
pub(super) xmin: i32,
pub(super) ymin: i32,
pub(super) width: u32,
pub(super) height: u32,
pub(super) advance: f32,
}
/// One rasterized bitmap handed to the atlas.
pub(super) struct Raster<'a> {
pub(super) bitmap: &'a [u8],
pub(super) width: u32,
pub(super) height: u32,
pub(super) xmin: i32,
pub(super) ymin: i32,
pub(super) advance: f32,
}
struct Entry {
ch: char,
size_bits: u32,
glyph: Glyph,
}
/// Packed glyph coverage plus the cache that maps characters onto it.
pub(super) struct GlyphAtlas {
pixels: Vec<u8>,
entries: Vec<Entry>,
cursor_x: u32,
cursor_y: u32,
shelf: u32,
dirty: Vec<Region>,
}
impl GlyphAtlas {
/// An empty atlas with a small white block at the origin.
pub(super) fn new() -> Self {
let mut pixels = vec![0; (SIZE * SIZE) as usize];
// A two by two white block at the origin; sampling its centre stays white
// even when filtering drifts by half a texel.
pixels[0..2].fill(255);
let second_row = SIZE as usize;
pixels[second_row..second_row + 2].fill(255);
Self {
pixels,
entries: Vec::new(),
cursor_x: 2 + PADDING,
cursor_y: 0,
shelf: 2,
dirty: vec![Region {
x: 0,
y: 0,
w: 2,
h: 2,
}],
}
}
/// The raw coverage buffer, `SIZE * SIZE` bytes.
pub(super) fn pixels(&self) -> &[u8] {
&self.pixels
}
/// The number of cached glyphs.
#[allow(dead_code, reason = "read by the overlay atlas test")]
pub(super) fn len(&self) -> usize {
self.entries.len()
}
/// A region that still has to be uploaded to the GPU.
pub(super) fn take_dirty(&mut self) -> Vec<Region> {
std::mem::take(&mut self.dirty)
}
/// The cached glyph for `ch` at a pixel size, if any.
pub(super) fn get(&self, ch: char, size_bits: u32) -> Option<&Glyph> {
self.entries
.iter()
.find(|entry| entry.ch == ch && entry.size_bits == size_bits)
.map(|entry| &entry.glyph)
}
/// Packs a rasterized glyph and returns its placement.
///
/// Returns `None` when the glyph is already cached or the atlas has no room
/// left for it.
pub(super) fn insert(
&mut self,
ch: char,
size_bits: u32,
raster: &Raster<'_>,
) -> Option<Glyph> {
if self.get(ch, size_bits).is_some() {
return None;
}
let (x, y) = self.reserve(raster.width, raster.height)?;
let glyph = Glyph {
uv: [x as f32 / SIZE as f32, y as f32 / SIZE as f32],
uv_size: [
raster.width as f32 / SIZE as f32,
raster.height as f32 / SIZE as f32,
],
xmin: raster.xmin,
ymin: raster.ymin,
width: raster.width,
height: raster.height,
advance: raster.advance,
};
self.write(x, y, raster);
self.entries.push(Entry {
ch,
size_bits,
glyph,
});
Some(glyph)
}
/// Finds a free shelf slot for a `width` by `height` bitmap.
fn reserve(&mut self, width: u32, height: u32) -> Option<(u32, u32)> {
if width == 0 || height == 0 {
// Invisible glyphs (spaces) still need a cache entry, not texels.
return Some((0, 0));
}
if width + 2 * PADDING > SIZE || height + PADDING > SIZE {
return None;
}
if self.cursor_x + width + PADDING > SIZE {
self.cursor_y += self.shelf + PADDING;
self.cursor_x = 0;
self.shelf = 0;
}
if self.cursor_y + height + PADDING > SIZE {
return None;
}
let spot = (self.cursor_x, self.cursor_y);
self.cursor_x += width + PADDING;
self.shelf = self.shelf.max(height);
Some(spot)
}
/// Copies a bitmap into the coverage buffer and marks the region dirty.
fn write(&mut self, x: u32, y: u32, raster: &Raster<'_>) {
if raster.width == 0 || raster.height == 0 {
return;
}
for row in 0..raster.height {
let source = (row * raster.width) as usize;
let target = ((y + row) * SIZE + x) as usize;
let length = raster.width as usize;
if let (Some(from), Some(to)) = (
raster.bitmap.get(source..source + length),
self.pixels.get_mut(target..target + length),
) {
to.copy_from_slice(from);
}
}
self.dirty.push(Region {
x,
y,
w: raster.width,
h: raster.height,
});
}
}

View file

@ -0,0 +1,123 @@
//! Screen-space 2D overlay drawn after the 3D scene.
//!
//! The overlay is a list of rectangles, lines and text in target pixels with the
//! origin at the top-left. One triangle batch draws all of it with depth testing
//! disabled and alpha blending: solid shapes sample a white texel of the glyph
//! atlas, text samples glyph coverage.
mod atlas;
mod pass;
mod text;
#[cfg(test)]
mod tests;
pub(crate) use pass::{OverlayRenderer, Target};
/// A filled rectangle in target pixels.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct OverlayRect {
pub x: f32,
pub y: f32,
pub w: f32,
pub h: f32,
pub color: [f32; 4],
}
impl OverlayRect {
/// A rectangle at `(x, y)` with a size and a linear RGBA colour.
#[must_use]
pub fn new(x: f32, y: f32, w: f32, h: f32, color: [f32; 4]) -> Self {
Self { x, y, w, h, color }
}
}
/// A straight line of a given width in target pixels.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct OverlayLine {
pub from: [f32; 2],
pub to: [f32; 2],
pub width: f32,
pub color: [f32; 4],
}
impl OverlayLine {
/// A line from `from` to `to` with a width and a linear RGBA colour.
#[must_use]
pub fn new(from: [f32; 2], to: [f32; 2], width: f32, color: [f32; 4]) -> Self {
Self {
from,
to,
width,
color,
}
}
}
/// One line of ASCII text, anchored at its top-left corner.
#[derive(Debug, Clone, PartialEq)]
pub struct OverlayText {
pub x: f32,
pub y: f32,
pub size: f32,
pub color: [f32; 4],
pub text: String,
}
impl OverlayText {
/// Text at `(x, y)` in pixels with a font size and a linear RGBA colour.
#[must_use]
pub fn new(x: f32, y: f32, size: f32, color: [f32; 4], text: impl Into<String>) -> Self {
Self {
x,
y,
size,
color,
text: text.into(),
}
}
}
/// Everything the overlay pass draws in one frame.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Overlay {
pub rects: Vec<OverlayRect>,
pub lines: Vec<OverlayLine>,
pub texts: Vec<OverlayText>,
}
impl Overlay {
/// An empty overlay.
#[must_use]
pub fn new() -> Self {
Self::default()
}
/// Drops all shapes but keeps the allocated buffers.
pub fn clear(&mut self) {
self.rects.clear();
self.lines.clear();
self.texts.clear();
}
/// Whether the overlay would draw nothing.
#[must_use]
pub fn is_empty(&self) -> bool {
self.rects.is_empty() && self.lines.is_empty() && self.texts.is_empty()
}
/// Queues a filled rectangle.
pub fn push_rect(&mut self, rect: OverlayRect) {
self.rects.push(rect);
}
/// Queues a line.
pub fn push_line(&mut self, line: OverlayLine) {
self.lines.push(line);
}
/// Queues a text line.
pub fn push_text(&mut self, text: OverlayText) {
self.texts.push(text);
}
}

View file

@ -0,0 +1,106 @@
//! Vertex layout and quad assembly for the overlay batch.
use bytemuck::{Pod, Zeroable};
use super::super::OverlayLine;
use super::super::atlas::WHITE_UV;
/// A single overlay vertex: clip-space position, atlas UV and colour.
#[repr(C)]
#[derive(Debug, Clone, Copy, Pod, Zeroable)]
pub(super) struct Vertex {
pub(super) position: [f32; 2],
pub(super) uv: [f32; 2],
pub(super) color: [f32; 4],
}
pub(super) const ATTRIBUTES: [wgpu::VertexAttribute; 3] = [
wgpu::VertexAttribute {
format: wgpu::VertexFormat::Float32x2,
offset: 0,
shader_location: 0,
},
wgpu::VertexAttribute {
format: wgpu::VertexFormat::Float32x2,
offset: 8,
shader_location: 1,
},
wgpu::VertexAttribute {
format: wgpu::VertexFormat::Float32x4,
offset: 16,
shader_location: 2,
},
];
/// UV rectangle of the always-white atlas texel.
pub(super) fn solid_uv() -> [f32; 4] {
[WHITE_UV[0], WHITE_UV[1], WHITE_UV[0], WHITE_UV[1]]
}
/// Pixels to normalized device coordinates; the overlay's y axis points down.
fn ndc(x: f32, y: f32, size: (u32, u32)) -> [f32; 2] {
let width = size.0.max(1) as f32;
let height = size.1.max(1) as f32;
[x / width * 2.0 - 1.0, 1.0 - y / height * 2.0]
}
/// Appends an axis-aligned quad as two triangles.
pub(super) fn push_quad(
vertices: &mut Vec<Vertex>,
size: (u32, u32),
rect: [f32; 4],
uv: [f32; 4],
color: [f32; 4],
) {
let [x, y, w, h] = rect;
if w <= 0.0 || h <= 0.0 {
return;
}
let top_left = ndc(x, y, size);
let bottom_right = ndc(x + w, y + h, size);
let corners = [
([top_left[0], top_left[1]], [uv[0], uv[1]]),
([bottom_right[0], top_left[1]], [uv[2], uv[1]]),
([bottom_right[0], bottom_right[1]], [uv[2], uv[3]]),
([top_left[0], bottom_right[1]], [uv[0], uv[3]]),
];
push_corners(vertices, corners, color);
}
/// Appends a line as a quad expanded along its normal.
pub(super) fn push_segment(vertices: &mut Vec<Vertex>, size: (u32, u32), line: &OverlayLine) {
let [x0, y0] = line.from;
let [x1, y1] = line.to;
let dx = x1 - x0;
let dy = y1 - y0;
let length = (dx * dx + dy * dy).sqrt();
if length <= f32::EPSILON || line.width <= 0.0 {
return;
}
let half = line.width * 0.5;
let nx = -dy / length * half;
let ny = dx / length * half;
let uv = WHITE_UV;
let corners = [
(ndc(x0 + nx, y0 + ny, size), uv),
(ndc(x1 + nx, y1 + ny, size), uv),
(ndc(x1 - nx, y1 - ny, size), uv),
(ndc(x0 - nx, y0 - ny, size), uv),
];
push_corners(vertices, corners, line.color);
}
/// Appends two triangles for four pixel-space corners.
fn push_corners(vertices: &mut Vec<Vertex>, corners: [([f32; 2], [f32; 2]); 4], color: [f32; 4]) {
const INDICES: [usize; 6] = [0, 1, 2, 0, 2, 3];
for index in INDICES {
let Some((position, uv)) = corners.get(index) else {
continue;
};
vertices.push(Vertex {
position: *position,
uv: *uv,
color,
});
}
}

View file

@ -0,0 +1,327 @@
//! The overlay render pass: one triangle batch with alpha blending, no depth.
mod geometry;
use std::sync::Mutex;
use wgpu::util::DeviceExt;
use self::geometry::{ATTRIBUTES, Vertex, push_quad, push_segment, solid_uv};
use super::Overlay;
use super::atlas::{GlyphAtlas, Region, SIZE};
use super::text::TextRasterizer;
/// GPU state of the overlay pass.
///
/// The glyph atlas grows while drawing, so it sits behind a mutex: that keeps
/// [`crate::Renderer::draw_overlay`] callable through a shared reference.
pub(crate) struct OverlayRenderer {
state: Mutex<State>,
}
struct State {
pipeline: wgpu::RenderPipeline,
bind_group: wgpu::BindGroup,
texture: wgpu::Texture,
rasterizer: TextRasterizer,
}
/// The colour view and pixel size the overlay draws into.
#[derive(Clone, Copy)]
pub(crate) struct Target<'a> {
pub(crate) view: &'a wgpu::TextureView,
pub(crate) size: (u32, u32),
}
/// A recorded vertex batch: pipeline, atlas binding and geometry.
struct Batch<'a> {
pipeline: &'a wgpu::RenderPipeline,
bind_group: &'a wgpu::BindGroup,
vertices: &'a [Vertex],
}
impl OverlayRenderer {
/// Creates the atlas texture, sampler, bind group and pipeline.
pub(crate) fn new(
device: &wgpu::Device,
queue: &wgpu::Queue,
format: wgpu::TextureFormat,
) -> Self {
let texture = create_atlas_texture(device);
let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
label: Some("fabrilis atlas sampler"),
address_mode_u: wgpu::AddressMode::ClampToEdge,
address_mode_v: wgpu::AddressMode::ClampToEdge,
address_mode_w: wgpu::AddressMode::ClampToEdge,
mag_filter: wgpu::FilterMode::Linear,
min_filter: wgpu::FilterMode::Linear,
..Default::default()
});
let layout = create_layout(device);
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("fabrilis atlas"),
layout: &layout,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: wgpu::BindingResource::TextureView(&view),
},
wgpu::BindGroupEntry {
binding: 1,
resource: wgpu::BindingResource::Sampler(&sampler),
},
],
});
let pipeline = create_pipeline(device, format, &layout);
let mut rasterizer = TextRasterizer::new();
upload_atlas(queue, &texture, &mut rasterizer);
Self {
state: Mutex::new(State {
pipeline,
bind_group,
texture,
rasterizer,
}),
}
}
/// Draws the overlay over whatever is already in the target.
pub(crate) fn draw(
&self,
device: &wgpu::Device,
queue: &wgpu::Queue,
target: Target<'_>,
overlay: &Overlay,
) {
if target.size.0 == 0 || target.size.1 == 0 || overlay.is_empty() {
return;
}
let Ok(mut guard) = self.state.lock() else {
return;
};
let State {
pipeline,
bind_group,
texture,
rasterizer,
} = &mut *guard;
let mut vertices = Vec::with_capacity(
overlay.rects.len() * 6 + overlay.lines.len() * 6 + overlay.texts.len() * 24,
);
for rect in &overlay.rects {
push_quad(
&mut vertices,
target.size,
[rect.x, rect.y, rect.w, rect.h],
solid_uv(),
rect.color,
);
}
for line in &overlay.lines {
push_segment(&mut vertices, target.size, line);
}
for item in &overlay.texts {
for quad in rasterizer.layout(item) {
push_quad(&mut vertices, target.size, quad.rect, quad.uv, item.color);
}
}
// Layout may have rasterized new glyphs, so upload after it.
upload_atlas(queue, texture, rasterizer);
submit(
device,
queue,
target,
Batch {
pipeline,
bind_group,
vertices: &vertices,
},
);
}
}
/// Uploads the vertex batch and records the overlay pass.
fn submit(device: &wgpu::Device, queue: &wgpu::Queue, target: Target<'_>, batch: Batch<'_>) {
let vertices = batch.vertices;
if vertices.is_empty() {
return;
}
let buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("fabrilis overlay vertices"),
contents: bytemuck::cast_slice(vertices),
usage: wgpu::BufferUsages::VERTEX,
});
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("fabrilis overlay frame"),
});
{
let attachments = [Some(wgpu::RenderPassColorAttachment {
view: target.view,
depth_slice: None,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Load,
store: wgpu::StoreOp::Store,
},
})];
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("fabrilis overlay pass"),
color_attachments: &attachments,
depth_stencil_attachment: None,
timestamp_writes: None,
occlusion_query_set: None,
multiview_mask: None,
});
pass.set_pipeline(batch.pipeline);
pass.set_bind_group(0, batch.bind_group, &[]);
pass.set_vertex_buffer(0, buffer.slice(..));
pass.draw(0..vertices.len() as u32, 0..1);
}
queue.submit([encoder.finish()]);
}
fn create_atlas_texture(device: &wgpu::Device) -> wgpu::Texture {
device.create_texture(&wgpu::TextureDescriptor {
label: Some("fabrilis glyph atlas"),
size: wgpu::Extent3d {
width: SIZE,
height: SIZE,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::R8Unorm,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
view_formats: &[],
})
}
fn create_layout(device: &wgpu::Device) -> wgpu::BindGroupLayout {
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("fabrilis overlay layout"),
entries: &[
wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Float { filterable: true },
view_dimension: wgpu::TextureViewDimension::D2,
multisampled: false,
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 1,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
count: None,
},
],
})
}
fn create_pipeline(
device: &wgpu::Device,
format: wgpu::TextureFormat,
layout: &wgpu::BindGroupLayout,
) -> wgpu::RenderPipeline {
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("fabrilis overlay shader"),
source: wgpu::ShaderSource::Wgsl(std::borrow::Cow::Borrowed(include_str!("overlay.wgsl"))),
});
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("fabrilis overlay pipeline layout"),
bind_group_layouts: &[Some(layout)],
immediate_size: 0,
});
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("fabrilis overlay pipeline"),
layout: Some(&pipeline_layout),
vertex: wgpu::VertexState {
module: &shader,
entry_point: Some("vs_main"),
compilation_options: wgpu::PipelineCompilationOptions::default(),
buffers: &[Some(wgpu::VertexBufferLayout {
array_stride: 32,
step_mode: wgpu::VertexStepMode::Vertex,
attributes: &ATTRIBUTES,
})],
},
primitive: wgpu::PrimitiveState {
topology: wgpu::PrimitiveTopology::TriangleList,
cull_mode: None,
..Default::default()
},
depth_stencil: None,
multisample: wgpu::MultisampleState::default(),
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: Some("fs_main"),
compilation_options: wgpu::PipelineCompilationOptions::default(),
targets: &[Some(wgpu::ColorTargetState {
format,
blend: Some(wgpu::BlendState::ALPHA_BLENDING),
write_mask: wgpu::ColorWrites::ALL,
})],
}),
multiview_mask: None,
cache: None,
})
}
/// Uploads every atlas region written since the previous frame.
fn upload_atlas(queue: &wgpu::Queue, texture: &wgpu::Texture, rasterizer: &mut TextRasterizer) {
let regions = rasterizer.take_dirty();
if regions.is_empty() {
return;
}
let atlas = rasterizer.atlas();
for region in regions {
let (data, row) = padded_region(atlas, region);
queue.write_texture(
wgpu::TexelCopyTextureInfo {
texture,
mip_level: 0,
origin: wgpu::Origin3d {
x: region.x,
y: region.y,
z: 0,
},
aspect: wgpu::TextureAspect::All,
},
&data,
wgpu::TexelCopyBufferLayout {
offset: 0,
bytes_per_row: Some(row),
rows_per_image: Some(region.h),
},
wgpu::Extent3d {
width: region.w,
height: region.h,
depth_or_array_layers: 1,
},
);
}
}
/// Copies one atlas region into a row-padded staging buffer.
fn padded_region(atlas: &GlyphAtlas, region: Region) -> (Vec<u8>, u32) {
let row =
region.w.div_ceil(wgpu::COPY_BYTES_PER_ROW_ALIGNMENT) * wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;
let mut data = vec![0; (row * region.h) as usize];
let pixels = atlas.pixels();
let length = region.w as usize;
for line in 0..region.h {
let source = ((region.y + line) * SIZE + region.x) as usize;
let target = (line * row) as usize;
if let (Some(from), Some(to)) = (
pixels.get(source..source + length),
data.get_mut(target..target + length),
) {
to.copy_from_slice(from);
}
}
(data, row)
}

View file

@ -0,0 +1,29 @@
struct VertexInput {
@location(0) position: vec2<f32>,
@location(1) uv: vec2<f32>,
@location(2) color: vec4<f32>,
};
struct VertexOutput {
@builtin(position) clip_position: vec4<f32>,
@location(0) uv: vec2<f32>,
@location(1) color: vec4<f32>,
};
@vertex
fn vs_main(input: VertexInput) -> VertexOutput {
var output: VertexOutput;
output.clip_position = vec4<f32>(input.position, 0.0, 1.0);
output.uv = input.uv;
output.color = input.color;
return output;
}
@group(0) @binding(0) var atlas: texture_2d<f32>;
@group(0) @binding(1) var atlas_sampler: sampler;
@fragment
fn fs_main(input: VertexOutput) -> @location(0) vec4<f32> {
let coverage = textureSample(atlas, atlas_sampler, input.uv).r;
return vec4<f32>(input.color.rgb, input.color.a * coverage);
}

View file

@ -0,0 +1,156 @@
//! Headless tests for the screen-space overlay.
use super::atlas::{GlyphAtlas, Raster};
use super::text::font_path;
use super::{Overlay, OverlayLine, OverlayRect, OverlayText};
use crate::{Camera, Gpu, MeshData, Renderer, Scene};
use wgpu::TextureFormat;
const SIZE: u32 = 64;
const FORMAT: TextureFormat = TextureFormat::Rgba8UnormSrgb;
fn setup() -> (Gpu, Renderer) {
let gpu = Gpu::headless().expect("headless adapter");
let renderer =
Renderer::new(gpu.device(), gpu.queue(), FORMAT, (SIZE, SIZE)).expect("renderer");
(gpu, renderer)
}
fn empty_scene() -> Scene {
Scene::new(MeshData::default())
}
fn camera() -> Camera {
Camera::look_at([0.0, 0.0, 5.0], [0.0, 0.0, 0.0], [0.0, 0.0, 1.0])
}
fn pixel_at(pixels: &[u8], x: u32, y: u32) -> [u8; 4] {
let index = ((y * SIZE + x) * 4) as usize;
[
pixels[index],
pixels[index + 1],
pixels[index + 2],
pixels[index + 3],
]
}
#[test]
fn red_rect_changes_pixels() {
let (_gpu, mut renderer) = setup();
let mut overlay = Overlay::new();
overlay.push_rect(OverlayRect::new(
16.0,
16.0,
32.0,
32.0,
[1.0, 0.0, 0.0, 1.0],
));
renderer
.draw_with_overlay(&empty_scene(), &camera(), &overlay)
.expect("draw");
let pixels = renderer.pixels().expect("pixels");
assert_eq!(pixels.len(), (SIZE * SIZE * 4) as usize);
let inside = pixel_at(&pixels, 32, 32);
assert!(
inside[0] > 200 && inside[1] < 40 && inside[2] < 40,
"the rect must be red: {inside:?}"
);
let outside = pixel_at(&pixels, 2, 2);
assert!(
outside[0] < 120,
"the corner must keep the clear colour: {outside:?}"
);
}
#[test]
fn white_line_changes_pixels() {
let (_gpu, mut renderer) = setup();
let mut overlay = Overlay::new();
overlay.push_line(OverlayLine::new(
[4.0, 32.0],
[60.0, 32.0],
3.0,
[1.0, 1.0, 1.0, 1.0],
));
renderer
.draw_with_overlay(&empty_scene(), &camera(), &overlay)
.expect("draw");
let pixels = renderer.pixels().expect("pixels");
let on_line = pixel_at(&pixels, 32, 32);
assert!(
on_line.iter().take(3).all(|channel| *channel > 200),
"the line must be white: {on_line:?}"
);
let off_line = pixel_at(&pixels, 32, 4);
assert!(
off_line[0] < 120,
"away from the line the background stays: {off_line:?}"
);
}
#[test]
fn text_draws_pixels_when_a_font_exists() {
if font_path().is_none() {
return;
}
let (_gpu, mut renderer) = setup();
let mut overlay = Overlay::new();
overlay.push_text(OverlayText::new(
4.0,
4.0,
20.0,
[1.0, 1.0, 1.0, 1.0],
"FPS 60",
));
renderer
.draw_with_overlay(&empty_scene(), &camera(), &overlay)
.expect("draw");
let pixels = renderer.pixels().expect("pixels");
let covered = (4..60)
.flat_map(|x| (4..28).map(move |y| (x, y)))
.filter(|(x, y)| pixel_at(&pixels, *x, *y)[0] > 150)
.count();
assert!(covered > 0, "the text must cover at least one pixel");
}
#[test]
fn atlas_does_not_duplicate_glyphs() {
let mut atlas = GlyphAtlas::new();
let _ = atlas.take_dirty();
let bitmap = [255u8; 16];
let raster = Raster {
bitmap: &bitmap,
width: 4,
height: 4,
xmin: 0,
ymin: 0,
advance: 5.0,
};
let size = 14.0f32.to_bits();
let first = atlas.insert('A', size, &raster).expect("first insert");
assert_eq!(atlas.take_dirty().len(), 1, "one upload per new glyph");
assert!(
atlas.insert('A', size, &raster).is_none(),
"the same glyph is not packed twice"
);
assert!(
atlas.take_dirty().is_empty(),
"no upload for a cached glyph"
);
assert_eq!(atlas.len(), 1);
let cached = atlas.get('A', size).expect("cached glyph");
assert_eq!(cached.uv, first.uv);
}
#[test]
fn zero_size_target_is_skipped() {
let (_gpu, mut renderer) = setup();
renderer.resize((0, 0)).expect("resize to zero");
let mut overlay = Overlay::new();
overlay.push_rect(OverlayRect::new(0.0, 0.0, 8.0, 8.0, [1.0; 4]));
renderer
.draw_with_overlay(&empty_scene(), &camera(), &overlay)
.expect("skipped draw");
assert!(renderer.pixels().expect("pixels").is_empty());
}

View file

@ -0,0 +1,136 @@
//! Font loading and glyph layout for the overlay text.
use std::path::Path;
use fontdue::{Font, FontSettings};
use super::OverlayText;
use super::atlas::{Glyph, GlyphAtlas, Raster, Region};
/// Font files tried in order; the first one that exists is loaded.
const FONT_PATHS: [&str; 5] = [
"/usr/share/fonts/noto/NotoSans-Regular.ttf",
"/usr/share/fonts/TTF/DejaVuSans.ttf",
"/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
"/System/Library/Fonts/Helvetica.ttc",
"C:\\Windows\\Fonts\\segoeui.ttf",
];
/// One textured glyph quad in overlay pixels, origin top-left.
#[derive(Debug, Clone, Copy, PartialEq)]
pub(super) struct GlyphQuad {
pub(super) rect: [f32; 4],
pub(super) uv: [f32; 4],
}
/// The first font file that exists on this machine, if any.
pub(super) fn font_path() -> Option<&'static str> {
FONT_PATHS
.iter()
.copied()
.find(|path| Path::new(path).is_file())
}
/// Rasterizes text and caches glyph coverage in the atlas.
pub(super) struct TextRasterizer {
font: Option<Font>,
atlas: GlyphAtlas,
}
impl TextRasterizer {
/// Loads the first available font; without one, text is skipped.
pub(super) fn new() -> Self {
Self {
font: load_font(),
atlas: GlyphAtlas::new(),
}
}
/// Regions of the atlas that were written since the last call.
pub(super) fn take_dirty(&mut self) -> Vec<Region> {
self.atlas.take_dirty()
}
/// The packed coverage that backs the glyph quads.
pub(super) fn atlas(&self) -> &GlyphAtlas {
&self.atlas
}
/// Lays one line of ASCII text out into covered quads.
pub(super) fn layout(&mut self, text: &OverlayText) -> Vec<GlyphQuad> {
let mut quads = Vec::new();
if self.font.is_none() {
return quads;
}
let size = text.size.max(1.0);
let bits = size.to_bits();
let baseline = text.y + self.ascent(size);
let mut pen = text.x;
for ch in text.text.chars() {
if !ch.is_ascii() {
continue;
}
let Some(glyph) = self.glyph(ch, size, bits) else {
continue;
};
if glyph.width > 0 && glyph.height > 0 {
let x = pen + glyph.xmin as f32;
let y = baseline - glyph.ymin as f32 - glyph.height as f32;
quads.push(GlyphQuad {
rect: [x, y, glyph.width as f32, glyph.height as f32],
uv: [
glyph.uv[0],
glyph.uv[1],
glyph.uv[0] + glyph.uv_size[0],
glyph.uv[1] + glyph.uv_size[1],
],
});
}
pen += glyph.advance;
}
quads
}
/// Distance from the top of the text box down to the baseline.
fn ascent(&self, size: f32) -> f32 {
self.font
.as_ref()
.and_then(|font| font.horizontal_line_metrics(size))
.map_or(size * 0.8, |line| line.ascent)
}
/// The cached glyph for `ch`, rasterizing and packing it on first use.
fn glyph(&mut self, ch: char, size: f32, bits: u32) -> Option<Glyph> {
if let Some(cached) = self.atlas.get(ch, bits) {
return Some(*cached);
}
let font = self.font.as_ref()?;
let (metrics, bitmap) = font.rasterize(ch, size);
let raster = Raster {
bitmap: &bitmap,
width: metrics.width as u32,
height: metrics.height as u32,
xmin: metrics.xmin,
ymin: metrics.ymin,
advance: metrics.advance_width,
};
if let Some(packed) = self.atlas.insert(ch, bits, &raster) {
return Some(packed);
}
// The atlas is full: keep the pen moving but draw nothing.
Some(Glyph {
uv: [0.0, 0.0],
uv_size: [0.0, 0.0],
xmin: 0,
ymin: 0,
width: 0,
height: 0,
advance: metrics.advance_width,
})
}
}
fn load_font() -> Option<Font> {
let data = std::fs::read(font_path()?).ok()?;
Font::from_bytes(data, FontSettings::default()).ok()
}