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    fn draw(
314        &mut self,
315        frame: &Frame,
316        viewport: Viewport,
317        target: &wgpu::TextureView,
318    ) -> Result<()> {
319        if frame.is_empty() {
320            return Ok(());
321        }
322        self.text
323            .set_viewport(&self.queue, viewport.width, viewport.height);
324        if !frame.quads.is_empty() {
325            self.write_quads(&frame.quads);
326        }
327        if !frame.glyphs.is_empty() {
328            self.write_glyphs(&frame.glyphs);
329        }
330        let scale = self.scale_factor;
331        let mut encoder = self
332            .device
333            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
334                label: Some("rcus-encoder"),
335            });
336        {
337            let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
338                label: Some("rcus-pass"),
339                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
340                    view: target,
341                    resolve_target: None,
342                    ops: wgpu::Operations {
343                        load: wgpu::LoadOp::Clear(wgpu::Color {
344                            r: 0.02,
345                            g: 0.02,
346                            b: 0.03,
347                            a: 1.0,
348                        }),
349                        store: wgpu::StoreOp::Store,
350                    },
351                })],
352                depth_stencil_attachment: None,
353                timestamp_writes: None,
354                occlusion_query_set: None,
355            });
356            let width = viewport.width.max(1.0) as u32;
357            let height = viewport.height.max(1.0) as u32;
358            // Both passes group vertices into runs of identical clip rectangles,
359            // so a clipped panel costs one extra draw instead of a scissor
360            // change per rectangle.
361            if !frame.quads.is_empty() {
362                pass.set_pipeline(&self.solid.pipeline);
363                pass.set_vertex_buffer(0, self.quad_buffer.slice(..));
364                draw_runs(frame.quads.len(), &frame.quad_scissors, |run, scissor| {
365                    apply_scissor(&mut pass, frame, scissor, scale, width, height);
366                    pass.draw(run.0 as u32..run.1 as u32, 0..1);
367                });
368            }
369            if !frame.glyphs.is_empty() {
370                pass.set_pipeline(&self.text.pipeline);
371                pass.set_bind_group(0, &self.text.bind_group, &[]);
372                pass.set_vertex_buffer(0, self.glyph_buffer.slice(..));
373                draw_runs(frame.glyphs.len(), &frame.glyph_scissors, |run, scissor| {
374                    apply_scissor(&mut pass, frame, scissor, scale, width, height);
375                    pass.draw(run.0 as u32..run.1 as u32, 0..1);
376                });
377            }
378        }
379        self.queue.submit([encoder.finish()]);
380        Ok(())
381    }
382}
383
384/// Calls `draw` once per run of vertices that share a clip rectangle.
385fn draw_runs(
386    vertices: usize,
387    scissors: &[Option<u16>],
388    mut draw: impl FnMut((usize, usize), Option<u16>),
389) {
390    let mut run_start = 0usize;
391    let mut run_scissor = scissors.first().copied().flatten();
392    for index in 0..=vertices {
393        let scissor = scissors.get(index).copied().flatten();
394        if index == vertices || scissor != run_scissor {
395            if index > run_start {
396                draw((run_start, index), run_scissor);
397            }
398            run_start = index;
399            run_scissor = scissor;
400        }
401    }
402}
403
404fn apply_scissor(
405    pass: &mut wgpu::RenderPass<'_>,
406    frame: &Frame,
407    index: Option<u16>,
408    scale: f32,
409    width: u32,
410    height: u32,
411) {
412    let (x, y, w, h) = match index.and_then(|index| frame.scissors.get(index as usize)) {
413        Some(scissor) => (
414            (scissor.x * scale).floor().max(0.0) as u32,
415            (scissor.y * scale).floor().max(0.0) as u32,
416            (scissor.width * scale).ceil().max(0.0) as u32,
417            (scissor.height * scale).ceil().max(0.0) as u32,
418        ),
419        None => (0, 0, width, height),
420    };
421    pass.set_scissor_rect(
422        x.min(width.saturating_sub(1)),
423        y.min(height.saturating_sub(1)),
424        w.clamp(1, width),
425        h.clamp(1, height),
426    );
427}
428
429fn empty_buffer(device: &wgpu::Device, size: usize, label: &str) -> wgpu::Buffer {
430    device.create_buffer(&wgpu::BufferDescriptor {
431        label: Some(label),
432        size: size as u64,
433        usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
434        mapped_at_creation: false,
435    })
436}