mod pipeline;
mod quad;
mod text;
use anyhow::{anyhow, Result};
pub use pipeline::{SolidPipeline, TextPipeline, Viewport};
pub use quad::{Frame, GlyphQuad, Scissor, TextVertex, Vertex};
pub use text::{AtlasSet, GlyphAtlas, TextMetrics};
use quad::intersect;
use rcus_layout::{Color, LayoutTree};
use wgpu::util::DeviceExt;
pub struct FrameBuilder {
atlases: AtlasSet,
font: Vec<u8>,
viewport: Viewport,
frame: Frame,
default_color: Color,
}
impl FrameBuilder {
pub fn new(font: Vec<u8>) -> Self {
Self {
atlases: AtlasSet::new(),
font,
viewport: Viewport {
width: 1.0,
height: 1.0,
},
frame: Frame::new(),
default_color: Color::rgba(0.85, 0.87, 0.92, 1.0),
}
}
pub fn with_default_color(mut self, color: Color) -> Self {
self.default_color = color;
self
}
pub fn layer(&mut self, font_size: f32) -> &mut GlyphAtlas {
let index = self
.atlases
.layer(font_size, true, &self.font)
.expect("embedded font must parse");
self.atlases.get_mut(index)
}
pub fn atlases(&self) -> &AtlasSet {
&self.atlases
}
pub fn take_dirty_atlas(&mut self) -> bool {
self.atlases.take_dirty()
}
pub fn build(&mut self, tree: &LayoutTree) {
self.viewport = Viewport {
width: tree.viewport.width,
height: tree.viewport.height,
};
let mut frame = quad::build_quads(tree);
self.emit_text(tree, &mut frame);
self.frame = frame;
}
fn emit_text(&mut self, tree: &LayoutTree, frame: &mut Frame) {
self.emit_text_node(&tree.root, None, frame);
}
fn emit_text_node(
&mut self,
node: &rcus_layout::LayoutNode,
inherited: Option<rcus_layout::Rect>,
frame: &mut Frame,
) {
let clip = if node.clip {
let rect = match inherited {
Some(parent) => intersect(parent, node.rect),
None => node.rect,
};
if rect.width <= 0.0 || rect.height <= 0.0 {
return;
}
Some(rect)
} else {
inherited
};
if let Some(text) = node.text.as_deref() {
self.emit_text_run(node, text, clip, frame);
}
for child in &node.children {
self.emit_text_node(child, clip, frame);
}
}
fn emit_text_run(
&mut self,
node: &rcus_layout::LayoutNode,
text: &str,
clip: Option<rcus_layout::Rect>,
frame: &mut Frame,
) {
if node.rect.width <= 0.0 || node.rect.height <= 0.0 || text.is_empty() {
return;
}
if let Some(clip) = clip {
if clip.right() <= node.rect.x || clip.bottom() <= node.rect.y {
return;
}
}
let layer = match self.atlases.layer(node.font_size, true, &self.font) {
Ok(index) => index,
Err(_) => return,
};
let color = node.color.unwrap_or(self.default_color);
let rgba = [color.r, color.g, color.b, color.a];
let width_limit = match clip {
Some(clip) => (clip.right() - node.rect.x).max(0.0),
None => node.rect.width,
};
let atlas = self.atlases.get_mut(layer);
let fitted = atlas.ellipsize(text, width_limit);
let baseline = node.rect.y + (node.rect.height - node.font_size) / 2.0 + atlas.ascent();
let scissor = clip.filter(|clip| {
!(clip.x <= node.rect.x
&& clip.y <= node.rect.y
&& clip.right() >= node.rect.right()
&& clip.bottom() >= node.rect.bottom())
});
let scissor_index = scissor.map(|clip| {
frame.scissors.push(Scissor {
x: clip.x,
y: clip.y,
width: clip.width,
height: clip.height,
});
(frame.scissors.len() - 1) as u16
});
let mut glyphs = Vec::with_capacity(fitted.chars().count() * 6);
self.atlases
.get_mut(layer)
.shape(&mut glyphs, &fitted, node.rect.x, baseline, rgba, layer);
let start = frame.glyphs.len();
frame.glyphs.extend_from_slice(&glyphs);
for _ in start..frame.glyphs.len() {
frame.glyph_scissors.push(scissor_index);
}
}
pub fn frame(&self) -> &Frame {
&self.frame
}
pub fn viewport(&self) -> Viewport {
self.viewport
}
}
pub struct Renderer {
device: wgpu::Device,
queue: wgpu::Queue,
format: wgpu::TextureFormat,
solid: SolidPipeline,
text: TextPipeline,
quad_buffer: wgpu::Buffer,
quad_capacity: usize,
glyph_buffer: wgpu::Buffer,
glyph_capacity: usize,
scale_factor: f32,
surface: Option<wgpu::Surface<'static>>,
config: Option<wgpu::SurfaceConfiguration>,
}
impl Renderer {
pub fn new(
device: wgpu::Device,
queue: wgpu::Queue,
format: wgpu::TextureFormat,
atlases: &AtlasSet,
scale_factor: f32,
) -> Result<Self> {
let solid = SolidPipeline::new(&device, format)?;
let mut text = TextPipeline::new(&device, &queue, format)?;
text.sync_atlas(&device, &queue, atlases);
let quad_buffer = empty_buffer(&device, 4096, "rcus-quad-buffer");
let glyph_buffer = empty_buffer(&device, 65536, "rcus-glyph-buffer");
Ok(Self {
device,
queue,
format,
solid,
text,
quad_buffer,
quad_capacity: 4096,
glyph_buffer,
glyph_capacity: 65536,
scale_factor: scale_factor.max(1.0),
surface: None,
config: None,
})
}
pub fn set_scale_factor(&mut self, scale_factor: f32) {
self.scale_factor = scale_factor.max(1.0);
}
pub fn attach_surface(
&mut self,
surface: wgpu::Surface<'static>,
config: wgpu::SurfaceConfiguration,
) {
surface.configure(&self.device, &config);
self.config = Some(config);
self.surface = Some(surface);
}
pub fn resize(&mut self, width: u32, height: u32) {
if let Some(config) = self.config.as_mut() {
config.width = width.max(1);
config.height = height.max(1);
}
self.reconfigure();
}
fn reconfigure(&mut self) {
let Some(config) = self.config.clone() else {
return;
};
if let Some(surface) = self.surface.as_ref() {
surface.configure(&self.device, &config);
}
}
pub fn format(&self) -> wgpu::TextureFormat {
self.format
}
pub fn upload_atlas(&mut self, atlases: &AtlasSet) {
self.text.sync_atlas(&self.device, &self.queue, atlases);
}
fn write_quads(&mut self, vertices: &[Vertex]) {
let bytes = bytemuck::cast_slice(vertices);
if bytes.len() > self.quad_capacity {
self.quad_capacity = bytes.len().next_power_of_two();
self.quad_buffer = self
.device
.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("rcus-quad-buffer"),
contents: bytes,
usage: wgpu::BufferUsages::VERTEX,
});
return;
}
self.queue.write_buffer(&self.quad_buffer, 0, bytes);
}
fn write_glyphs(&mut self, vertices: &[TextVertex]) {
let bytes = bytemuck::cast_slice(vertices);
if bytes.len() > self.glyph_capacity {
self.glyph_capacity = bytes.len().next_power_of_two();
self.glyph_buffer = self
.device
.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("rcus-glyph-buffer"),
contents: bytes,
usage: wgpu::BufferUsages::VERTEX,
});
return;
}
self.queue.write_buffer(&self.glyph_buffer, 0, bytes);
}
pub fn render(&mut self, frame: &Frame, viewport: Viewport) -> Result<()> {
let acquired = match self.surface.as_ref() {
Some(surface) => surface.get_current_texture(),
None => return Ok(()),
};
let target = match acquired {
Ok(texture) => texture,
Err(wgpu::SurfaceError::Lost | wgpu::SurfaceError::Outdated) => {
self.reconfigure();
return Ok(());
}
Err(wgpu::SurfaceError::OutOfMemory) => return Err(anyhow!("swapchain out of memory")),
Err(error) => return Err(anyhow!("swapchain error: {error:?}")),
};
let view = target
.texture
.create_view(&wgpu::TextureViewDescriptor::default());
self.draw(frame, viewport, &view)?;
target.present();
Ok(())
}
pub fn snapshot_png(
&mut self,
frame: &Frame,
viewport: Viewport,
width: u32,
height: u32,
) -> Result<Vec<u8>> {
let width = width.max(1);
let height = height.max(1);
let texture = self.device.create_texture(&wgpu::TextureDescriptor {
label: Some("rcus-snapshot"),
size: wgpu::Extent3d {
width,
height,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Rgba8Unorm,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
view_formats: &[],
});
let target = texture.create_view(&wgpu::TextureViewDescriptor::default());
self.draw(frame, viewport, &target)?;
let pixels = self.read_texture(&texture, width, height)?;
let image = image::RgbaImage::from_raw(width, height, pixels)
.ok_or_else(|| anyhow!("snapshot of {width}x{height} did not decode"))?;
let mut bytes = Vec::new();
image
.write_to(
&mut std::io::Cursor::new(&mut bytes),
image::ImageFormat::Png,
)
.map_err(|error| anyhow!("png encode: {error}"))?;
Ok(bytes)
}
fn read_texture(&self, texture: &wgpu::Texture, width: u32, height: u32) -> Result<Vec<u8>> {
const ALIGNMENT: u32 = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;
let row_bytes = width * 4;
let padded = row_bytes.div_ceil(ALIGNMENT) * ALIGNMENT;
let buffer = self.device.create_buffer(&wgpu::BufferDescriptor {
label: Some("rcus-snapshot-readback"),
size: u64::from(padded) * u64::from(height),
usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
mapped_at_creation: false,
});
let mut encoder = self
.device
.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("rcus-snapshot-copy"),
});
encoder.copy_texture_to_buffer(
texture.as_image_copy(),
wgpu::ImageCopyBuffer {
buffer: &buffer,
layout: wgpu::ImageDataLayout {
offset: 0,
bytes_per_row: Some(padded),
rows_per_image: Some(height),
},
},
wgpu::Extent3d {
width,
height,
depth_or_array_layers: 1,
},
);
self.queue.submit([encoder.finish()]);
let slice = buffer.slice(..);
let (sender, receiver) = std::sync::mpsc::channel();
slice.map_async(wgpu::MapMode::Read, move |result| {
let _ = sender.send(result);
});
self.device.poll(wgpu::Maintain::Wait);
receiver
.recv()
.map_err(|_| anyhow!("the readback channel closed"))?
.map_err(|error| anyhow!("mapping the readback: {error}"))?;
let mapped = slice.get_mapped_range();
let mut pixels = Vec::with_capacity((row_bytes * height) as usize);
for row in mapped.chunks(padded as usize) {
pixels.extend_from_slice(&row[..row_bytes as usize]);
}
drop(mapped);
buffer.unmap();
Ok(pixels)
}
fn draw(
&mut self,
frame: &Frame,
viewport: Viewport,
target: &wgpu::TextureView,
) -> Result<()> {
if frame.is_empty() {
return Ok(());
}
self.text
.set_viewport(&self.queue, viewport.width, viewport.height);
if !frame.quads.is_empty() {
self.write_quads(&frame.quads);
}
if !frame.glyphs.is_empty() {
self.write_glyphs(&frame.glyphs);
}
let scale = self.scale_factor;
let mut encoder = self
.device
.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("rcus-encoder"),
});
{
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("rcus-pass"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: target,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(wgpu::Color {
r: 0.02,
g: 0.02,
b: 0.03,
a: 1.0,
}),
store: wgpu::StoreOp::Store,
},
})],
depth_stencil_attachment: None,
timestamp_writes: None,
occlusion_query_set: None,
});
let width = viewport.width.max(1.0) as u32;
let height = viewport.height.max(1.0) as u32;
if !frame.quads.is_empty() {
pass.set_pipeline(&self.solid.pipeline);
pass.set_vertex_buffer(0, self.quad_buffer.slice(..));
draw_runs(frame.quads.len(), &frame.quad_scissors, |run, scissor| {
apply_scissor(&mut pass, frame, scissor, scale, width, height);
pass.draw(run.0 as u32..run.1 as u32, 0..1);
});
}
if !frame.glyphs.is_empty() {
pass.set_pipeline(&self.text.pipeline);
pass.set_bind_group(0, &self.text.bind_group, &[]);
pass.set_vertex_buffer(0, self.glyph_buffer.slice(..));
draw_runs(frame.glyphs.len(), &frame.glyph_scissors, |run, scissor| {
apply_scissor(&mut pass, frame, scissor, scale, width, height);
pass.draw(run.0 as u32..run.1 as u32, 0..1);
});
}
}
self.queue.submit([encoder.finish()]);
Ok(())
}
}
fn draw_runs(
vertices: usize,
scissors: &[Option<u16>],
mut draw: impl FnMut((usize, usize), Option<u16>),
) {
let mut run_start = 0usize;
let mut run_scissor = scissors.first().copied().flatten();
for index in 0..=vertices {
let scissor = scissors.get(index).copied().flatten();
if index == vertices || scissor != run_scissor {
if index > run_start {
draw((run_start, index), run_scissor);
}
run_start = index;
run_scissor = scissor;
}
}
}
fn apply_scissor(
pass: &mut wgpu::RenderPass<'_>,
frame: &Frame,
index: Option<u16>,
scale: f32,
width: u32,
height: u32,
) {
let (x, y, w, h) = match index.and_then(|index| frame.scissors.get(index as usize)) {
Some(scissor) => (
(scissor.x * scale).floor().max(0.0) as u32,
(scissor.y * scale).floor().max(0.0) as u32,
(scissor.width * scale).ceil().max(0.0) as u32,
(scissor.height * scale).ceil().max(0.0) as u32,
),
None => (0, 0, width, height),
};
pass.set_scissor_rect(
x.min(width.saturating_sub(1)),
y.min(height.saturating_sub(1)),
w.clamp(1, width),
h.clamp(1, height),
);
}
fn empty_buffer(device: &wgpu::Device, size: usize, label: &str) -> wgpu::Buffer {
device.create_buffer(&wgpu::BufferDescriptor {
label: Some(label),
size: size as u64,
usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
})
}