Skip to main content

rcus_render/
lib.rs

1mod pipeline;
2mod quad;
3mod text;
4
5use anyhow::{anyhow, Result};
6
7pub use pipeline::{SolidPipeline, TextPipeline, Viewport};
8pub use quad::{Frame, GlyphQuad, Scissor, TextVertex, Vertex};
9pub use text::{AtlasSet, GlyphAtlas, TextMetrics};
10
11use quad::intersect;
12use rcus_layout::{Color, LayoutTree};
13use wgpu::util::DeviceExt;
14
15/// Turns a layout tree into the two vertex batches the GPU consumes. The
16/// builder owns the glyph atlases so a host never touches glyph internals.
17pub struct FrameBuilder {
18    atlases: AtlasSet,
19    font: Vec<u8>,
20    viewport: Viewport,
21    frame: Frame,
22    default_color: Color,
23}
24
25impl FrameBuilder {
26    pub fn new(font: Vec<u8>) -> Self {
27        Self {
28            atlases: AtlasSet::new(),
29            font,
30            viewport: Viewport {
31                width: 1.0,
32                height: 1.0,
33            },
34            frame: Frame::new(),
35            default_color: Color::rgba(0.85, 0.87, 0.92, 1.0),
36        }
37    }
38
39    pub fn with_default_color(mut self, color: Color) -> Self {
40        self.default_color = color;
41        self
42    }
43
44    /// Resolves the atlas layer for a pixel size, creating it on first use.
45    pub fn layer(&mut self, font_size: f32) -> &mut GlyphAtlas {
46        let index = self
47            .atlases
48            .layer(font_size, true, &self.font)
49            .expect("embedded font must parse");
50        self.atlases.get_mut(index)
51    }
52
53    /// Glyph atlases, so a renderer can upload them after shaping.
54    pub fn atlases(&self) -> &AtlasSet {
55        &self.atlases
56    }
57
58    /// True when new glyphs or layers were rasterized since the last frame.
59    pub fn take_dirty_atlas(&mut self) -> bool {
60        self.atlases.take_dirty()
61    }
62
63    pub fn build(&mut self, tree: &LayoutTree) {
64        self.viewport = Viewport {
65            width: tree.viewport.width,
66            height: tree.viewport.height,
67        };
68        let mut frame = quad::build_quads(tree);
69        self.emit_text(tree, &mut frame);
70        self.frame = frame;
71    }
72
73    /// Walks the tree in paint order, shaping text and inheriting clip rects.
74    fn emit_text(&mut self, tree: &LayoutTree, frame: &mut Frame) {
75        self.emit_text_node(&tree.root, None, frame);
76    }
77
78    fn emit_text_node(
79        &mut self,
80        node: &rcus_layout::LayoutNode,
81        inherited: Option<rcus_layout::Rect>,
82        frame: &mut Frame,
83    ) {
84        let clip = if node.clip {
85            let rect = match inherited {
86                Some(parent) => intersect(parent, node.rect),
87                None => node.rect,
88            };
89            if rect.width <= 0.0 || rect.height <= 0.0 {
90                return;
91            }
92            Some(rect)
93        } else {
94            inherited
95        };
96        if let Some(text) = node.text.as_deref() {
97            self.emit_text_run(node, text, clip, frame);
98        }
99        for child in &node.children {
100            self.emit_text_node(child, clip, frame);
101        }
102    }
103
104    fn emit_text_run(
105        &mut self,
106        node: &rcus_layout::LayoutNode,
107        text: &str,
108        clip: Option<rcus_layout::Rect>,
109        frame: &mut Frame,
110    ) {
111        if node.rect.width <= 0.0 || node.rect.height <= 0.0 || text.is_empty() {
112            return;
113        }
114        if let Some(clip) = clip {
115            if clip.right() <= node.rect.x || clip.bottom() <= node.rect.y {
116                return;
117            }
118        }
119        let layer = match self.atlases.layer(node.font_size, true, &self.font) {
120            Ok(index) => index,
121            Err(_) => return,
122        };
123        let color = node.color.unwrap_or(self.default_color);
124        let rgba = [color.r, color.g, color.b, color.a];
125        let width_limit = match clip {
126            Some(clip) => (clip.right() - node.rect.x).max(0.0),
127            None => node.rect.width,
128        };
129        let atlas = self.atlases.get_mut(layer);
130        let fitted = atlas.ellipsize(text, width_limit);
131        let baseline = node.rect.y + (node.rect.height - node.font_size) / 2.0 + atlas.ascent();
132        let scissor = clip.filter(|clip| {
133            !(clip.x <= node.rect.x
134                && clip.y <= node.rect.y
135                && clip.right() >= node.rect.right()
136                && clip.bottom() >= node.rect.bottom())
137        });
138        let scissor_index = scissor.map(|clip| {
139            frame.scissors.push(Scissor {
140                x: clip.x,
141                y: clip.y,
142                width: clip.width,
143                height: clip.height,
144            });
145            (frame.scissors.len() - 1) as u16
146        });
147        let mut glyphs = Vec::with_capacity(fitted.chars().count() * 6);
148        self.atlases
149            .get_mut(layer)
150            .shape(&mut glyphs, &fitted, node.rect.x, baseline, rgba, layer);
151        let start = frame.glyphs.len();
152        frame.glyphs.extend_from_slice(&glyphs);
153        for _ in start..frame.glyphs.len() {
154            frame.glyph_scissors.push(scissor_index);
155        }
156    }
157
158    pub fn frame(&self) -> &Frame {
159        &self.frame
160    }
161
162    pub fn viewport(&self) -> Viewport {
163        self.viewport
164    }
165}
166
167/// Draws frames with a solid pass followed by one textured text pass.
168pub struct Renderer {
169    device: wgpu::Device,
170    queue: wgpu::Queue,
171    format: wgpu::TextureFormat,
172    solid: SolidPipeline,
173    text: TextPipeline,
174    quad_buffer: wgpu::Buffer,
175    quad_capacity: usize,
176    glyph_buffer: wgpu::Buffer,
177    glyph_capacity: usize,
178    /// Device pixels per logical pixel, used to scale scissor rectangles.
179    scale_factor: f32,
180    /// The window surface, attached once the window exists.
181    surface: Option<wgpu::Surface<'static>>,
182    config: Option<wgpu::SurfaceConfiguration>,
183}
184
185impl Renderer {
186    pub fn new(
187        device: wgpu::Device,
188        queue: wgpu::Queue,
189        format: wgpu::TextureFormat,
190        atlases: &AtlasSet,
191        scale_factor: f32,
192    ) -> Result<Self> {
193        let solid = SolidPipeline::new(&device, format)?;
194        let mut text = TextPipeline::new(&device, &queue, format)?;
195        text.sync_atlas(&device, &queue, atlases);
196        let quad_buffer = empty_buffer(&device, 4096, "rcus-quad-buffer");
197        let glyph_buffer = empty_buffer(&device, 65536, "rcus-glyph-buffer");
198        Ok(Self {
199            device,
200            queue,
201            format,
202            solid,
203            text,
204            quad_buffer,
205            quad_capacity: 4096,
206            glyph_buffer,
207            glyph_capacity: 65536,
208            scale_factor: scale_factor.max(1.0),
209            surface: None,
210            config: None,
211        })
212    }
213
214    /// Updates the device pixel ratio after a monitor or window change.
215    pub fn set_scale_factor(&mut self, scale_factor: f32) {
216        self.scale_factor = scale_factor.max(1.0);
217    }
218
219    /// Attaches a window surface and configures the swapchain for it.
220    pub fn attach_surface(
221        &mut self,
222        surface: wgpu::Surface<'static>,
223        config: wgpu::SurfaceConfiguration,
224    ) {
225        surface.configure(&self.device, &config);
226        self.config = Some(config);
227        self.surface = Some(surface);
228    }
229
230    /// Reconfigures the swapchain after a window resize.
231    pub fn resize(&mut self, width: u32, height: u32) {
232        if let Some(config) = self.config.as_mut() {
233            config.width = width.max(1);
234            config.height = height.max(1);
235        }
236        self.reconfigure();
237    }
238
239    /// Reconfigures the swapchain after the surface is lost or outdated.
240    fn reconfigure(&mut self) {
241        let Some(config) = self.config.clone() else {
242            return;
243        };
244        if let Some(surface) = self.surface.as_ref() {
245            surface.configure(&self.device, &config);
246        }
247    }
248
249    pub fn format(&self) -> wgpu::TextureFormat {
250        self.format
251    }
252
253    /// Re-uploads the glyph atlas after new characters were rasterized.
254    pub fn upload_atlas(&mut self, atlases: &AtlasSet) {
255        self.text.sync_atlas(&self.device, &self.queue, atlases);
256    }
257
258    fn write_quads(&mut self, vertices: &[Vertex]) {
259        let bytes = bytemuck::cast_slice(vertices);
260        if bytes.len() > self.quad_capacity {
261            self.quad_capacity = bytes.len().next_power_of_two();
262            self.quad_buffer = self
263                .device
264                .create_buffer_init(&wgpu::util::BufferInitDescriptor {
265                    label: Some("rcus-quad-buffer"),
266                    contents: bytes,
267                    usage: wgpu::BufferUsages::VERTEX,
268                });
269            return;
270        }
271        self.queue.write_buffer(&self.quad_buffer, 0, bytes);
272    }
273
274    fn write_glyphs(&mut self, vertices: &[TextVertex]) {
275        let bytes = bytemuck::cast_slice(vertices);
276        if bytes.len() > self.glyph_capacity {
277            self.glyph_capacity = bytes.len().next_power_of_two();
278            self.glyph_buffer = self
279                .device
280                .create_buffer_init(&wgpu::util::BufferInitDescriptor {
281                    label: Some("rcus-glyph-buffer"),
282                    contents: bytes,
283                    usage: wgpu::BufferUsages::VERTEX,
284                });
285            return;
286        }
287        self.queue.write_buffer(&self.glyph_buffer, 0, bytes);
288    }
289
290    /// Draws one frame to the attached surface and presents it.
291    pub fn render(&mut self, frame: &Frame, viewport: Viewport) -> Result<()> {
292        let acquired = match self.surface.as_ref() {
293            Some(surface) => surface.get_current_texture(),
294            None => return Ok(()),
295        };
296        let target = match acquired {
297            Ok(texture) => texture,
298            Err(wgpu::SurfaceError::Lost | wgpu::SurfaceError::Outdated) => {
299                self.reconfigure();
300                return Ok(());
301            }
302            Err(wgpu::SurfaceError::OutOfMemory) => return Err(anyhow!("swapchain out of memory")),
303            Err(error) => return Err(anyhow!("swapchain error: {error:?}")),
304        };
305        let view = target
306            .texture
307            .create_view(&wgpu::TextureViewDescriptor::default());
308        self.draw(frame, viewport, &view)?;
309        target.present();
310        Ok(())
311    }
312
313    /// Draws one frame into a texture the caller owns, and hands back the
314    /// pixels as PNG bytes.
315    ///
316    /// A window presents a swapchain image, so `render` is all it needs. A
317    /// snapshot has nowhere to present: a doc image, a CI job, or a test on a
318    /// machine with no display. This runs the same pipelines against the same
319    /// frame, so what comes back is what the window would have shown.
320    ///
321    /// `width` and `height` are the image size in device pixels; the viewport
322    /// is in logical pixels and is scaled by the device pixel ratio the
323    /// renderer was built with.
324    pub fn snapshot_png(
325        &mut self,
326        frame: &Frame,
327        viewport: Viewport,
328        width: u32,
329        height: u32,
330    ) -> Result<Vec<u8>> {
331        let width = width.max(1);
332        let height = height.max(1);
333        let texture = self.device.create_texture(&wgpu::TextureDescriptor {
334            label: Some("rcus-snapshot"),
335            size: wgpu::Extent3d {
336                width,
337                height,
338                depth_or_array_layers: 1,
339            },
340            mip_level_count: 1,
341            sample_count: 1,
342            dimension: wgpu::TextureDimension::D2,
343            format: wgpu::TextureFormat::Rgba8Unorm,
344            usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
345            view_formats: &[],
346        });
347        let target = texture.create_view(&wgpu::TextureViewDescriptor::default());
348        self.draw(frame, viewport, &target)?;
349        let pixels = self.read_texture(&texture, width, height)?;
350        let image = image::RgbaImage::from_raw(width, height, pixels)
351            .ok_or_else(|| anyhow!("snapshot of {width}x{height} did not decode"))?;
352        // The texture is the device's orientation, top row first, which is what
353        // an image wants as well; no flip is needed.
354        let mut bytes = Vec::new();
355        image
356            .write_to(
357                &mut std::io::Cursor::new(&mut bytes),
358                image::ImageFormat::Png,
359            )
360            .map_err(|error| anyhow!("png encode: {error}"))?;
361        Ok(bytes)
362    }
363
364    /// Copies a texture back to the CPU, padding each row to the alignment
365    /// `copy_texture_to_buffer` requires and trimming it again afterwards.
366    fn read_texture(&self, texture: &wgpu::Texture, width: u32, height: u32) -> Result<Vec<u8>> {
367        const ALIGNMENT: u32 = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;
368        // The alignment is in bytes, not pixels: a row is four bytes per pixel,
369        // and the copy is rejected unless the stride covers the whole row.
370        let row_bytes = width * 4;
371        let padded = row_bytes.div_ceil(ALIGNMENT) * ALIGNMENT;
372        let buffer = self.device.create_buffer(&wgpu::BufferDescriptor {
373            label: Some("rcus-snapshot-readback"),
374            size: u64::from(padded) * u64::from(height),
375            usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
376            mapped_at_creation: false,
377        });
378        let mut encoder = self
379            .device
380            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
381                label: Some("rcus-snapshot-copy"),
382            });
383        encoder.copy_texture_to_buffer(
384            texture.as_image_copy(),
385            wgpu::ImageCopyBuffer {
386                buffer: &buffer,
387                layout: wgpu::ImageDataLayout {
388                    offset: 0,
389                    bytes_per_row: Some(padded),
390                    rows_per_image: Some(height),
391                },
392            },
393            wgpu::Extent3d {
394                width,
395                height,
396                depth_or_array_layers: 1,
397            },
398        );
399        self.queue.submit([encoder.finish()]);
400        let slice = buffer.slice(..);
401        let (sender, receiver) = std::sync::mpsc::channel();
402        slice.map_async(wgpu::MapMode::Read, move |result| {
403            let _ = sender.send(result);
404        });
405        // `Maintain::Wait` blocks until the copy has run and the mapping
406        // callback has fired, which is the only way to read a texture back
407        // without spinning on the queue.
408        self.device.poll(wgpu::Maintain::Wait);
409        receiver
410            .recv()
411            .map_err(|_| anyhow!("the readback channel closed"))?
412            .map_err(|error| anyhow!("mapping the readback: {error}"))?;
413        let mapped = slice.get_mapped_range();
414        let mut pixels = Vec::with_capacity((row_bytes * height) as usize);
415        for row in mapped.chunks(padded as usize) {
416            pixels.extend_from_slice(&row[..row_bytes as usize]);
417        }
418        drop(mapped);
419        buffer.unmap();
420        Ok(pixels)
421    }
422
423    fn draw(
424        &mut self,
425        frame: &Frame,
426        viewport: Viewport,
427        target: &wgpu::TextureView,
428    ) -> Result<()> {
429        if frame.is_empty() {
430            return Ok(());
431        }
432        self.text
433            .set_viewport(&self.queue, viewport.width, viewport.height);
434        if !frame.quads.is_empty() {
435            self.write_quads(&frame.quads);
436        }
437        if !frame.glyphs.is_empty() {
438            self.write_glyphs(&frame.glyphs);
439        }
440        let scale = self.scale_factor;
441        let mut encoder = self
442            .device
443            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
444                label: Some("rcus-encoder"),
445            });
446        {
447            let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
448                label: Some("rcus-pass"),
449                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
450                    view: target,
451                    resolve_target: None,
452                    ops: wgpu::Operations {
453                        load: wgpu::LoadOp::Clear(wgpu::Color {
454                            r: 0.02,
455                            g: 0.02,
456                            b: 0.03,
457                            a: 1.0,
458                        }),
459                        store: wgpu::StoreOp::Store,
460                    },
461                })],
462                depth_stencil_attachment: None,
463                timestamp_writes: None,
464                occlusion_query_set: None,
465            });
466            let width = viewport.width.max(1.0) as u32;
467            let height = viewport.height.max(1.0) as u32;
468            // Both passes group vertices into runs of identical clip rectangles,
469            // so a clipped panel costs one extra draw instead of a scissor
470            // change per rectangle.
471            if !frame.quads.is_empty() {
472                pass.set_pipeline(&self.solid.pipeline);
473                pass.set_vertex_buffer(0, self.quad_buffer.slice(..));
474                draw_runs(frame.quads.len(), &frame.quad_scissors, |run, scissor| {
475                    apply_scissor(&mut pass, frame, scissor, scale, width, height);
476                    pass.draw(run.0 as u32..run.1 as u32, 0..1);
477                });
478            }
479            if !frame.glyphs.is_empty() {
480                pass.set_pipeline(&self.text.pipeline);
481                pass.set_bind_group(0, &self.text.bind_group, &[]);
482                pass.set_vertex_buffer(0, self.glyph_buffer.slice(..));
483                draw_runs(frame.glyphs.len(), &frame.glyph_scissors, |run, scissor| {
484                    apply_scissor(&mut pass, frame, scissor, scale, width, height);
485                    pass.draw(run.0 as u32..run.1 as u32, 0..1);
486                });
487            }
488        }
489        self.queue.submit([encoder.finish()]);
490        Ok(())
491    }
492}
493
494/// Calls `draw` once per run of vertices that share a clip rectangle.
495fn draw_runs(
496    vertices: usize,
497    scissors: &[Option<u16>],
498    mut draw: impl FnMut((usize, usize), Option<u16>),
499) {
500    let mut run_start = 0usize;
501    let mut run_scissor = scissors.first().copied().flatten();
502    for index in 0..=vertices {
503        let scissor = scissors.get(index).copied().flatten();
504        if index == vertices || scissor != run_scissor {
505            if index > run_start {
506                draw((run_start, index), run_scissor);
507            }
508            run_start = index;
509            run_scissor = scissor;
510        }
511    }
512}
513
514fn apply_scissor(
515    pass: &mut wgpu::RenderPass<'_>,
516    frame: &Frame,
517    index: Option<u16>,
518    scale: f32,
519    width: u32,
520    height: u32,
521) {
522    let (x, y, w, h) = match index.and_then(|index| frame.scissors.get(index as usize)) {
523        Some(scissor) => (
524            (scissor.x * scale).floor().max(0.0) as u32,
525            (scissor.y * scale).floor().max(0.0) as u32,
526            (scissor.width * scale).ceil().max(0.0) as u32,
527            (scissor.height * scale).ceil().max(0.0) as u32,
528        ),
529        None => (0, 0, width, height),
530    };
531    pass.set_scissor_rect(
532        x.min(width.saturating_sub(1)),
533        y.min(height.saturating_sub(1)),
534        w.clamp(1, width),
535        h.clamp(1, height),
536    );
537}
538
539fn empty_buffer(device: &wgpu::Device, size: usize, label: &str) -> wgpu::Buffer {
540    device.create_buffer(&wgpu::BufferDescriptor {
541        label: Some(label),
542        size: size as u64,
543        usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
544        mapped_at_creation: false,
545    })
546}