rcus-render 0.1.5

wgpu renderer for rcus: solid quads, a runtime glyph atlas, and scissored text
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
//! GPU text. Glyphs are rasterized once into a single-channel atlas and drawn as
//! textured quads, so a 200k-line terminal scrollback costs one atlas bind and
//! one draw call per frame.

use ab_glyph::{Font, FontVec, PxScale, ScaleFont};
use anyhow::{anyhow, Result};

use crate::quad::{push_glyph, GlyphQuad, TextVertex};

const ATLAS_SIZE: u32 = 2048;
const PAD: u32 = 1;

/// Rasterized glyph coverage plus the metrics needed to place it.
#[derive(Clone, Copy, Debug)]
struct Glyph {
    /// Atlas rectangle in pixels.
    x: u16,
    y: u16,
    w: u16,
    h: u16,
    /// Offset from the pen position to the left edge of the bitmap.
    bearing_x: f32,
    /// Distance from the baseline up to the top edge of the bitmap.
    bearing_y: f32,
    advance: f32,
}

impl Glyph {
    fn blank(advance: f32) -> Self {
        Self {
            x: 0,
            y: 0,
            w: 0,
            h: 0,
            bearing_x: 0.0,
            bearing_y: 0.0,
            advance,
        }
    }
}

/// Dynamic glyph coverage atlas for one face at one pixel size.
pub struct GlyphAtlas {
    font: FontVec,
    scale: PxScale,
    size: f32,
    line_height: f32,
    ascent: f32,
    descent: f32,
    space_advance: f32,
    monospace: bool,
    glyphs: std::collections::HashMap<char, Glyph>,
    coverage: Vec<u8>,
    /// Packing cursor, so inserting glyphs stays linear instead of searching.
    pen_x: u32,
    pen_y: u32,
    row_height: u32,
    dirty: bool,
}

impl GlyphAtlas {
    pub fn new(font_bytes: &[u8], size: f32) -> Result<Self> {
        let font = FontVec::try_from_vec(font_bytes.to_vec())
            .map_err(|error| anyhow!("font parse failed: {error:?}"))?;
        let scale = PxScale::from(size.max(1.0));
        let scaled = font.as_scaled(scale);
        let ascent = scaled.ascent();
        let descent = scaled.descent();
        let line_height = (ascent - descent).ceil().max(1.0);
        let space_advance = scaled.h_advance(scaled.glyph_id(' '));
        Ok(Self {
            font,
            scale,
            size: size.max(1.0),
            line_height,
            ascent,
            descent,
            space_advance,
            monospace: false,
            glyphs: std::collections::HashMap::new(),
            coverage: vec![0u8; (ATLAS_SIZE * ATLAS_SIZE) as usize],
            pen_x: PAD,
            pen_y: PAD,
            row_height: 0,
            dirty: true,
        })
    }

    /// Treats every advance as the space advance, which is what a terminal grid
    /// wants and what the bundled DejaVu Sans Mono faces already are.
    pub fn set_monospace(&mut self, enabled: bool) {
        self.monospace = enabled;
    }

    pub fn size(&self) -> f32 {
        self.size
    }

    pub fn line_height(&self) -> f32 {
        self.line_height
    }

    pub fn ascent(&self) -> f32 {
        self.ascent
    }

    pub fn descent(&self) -> f32 {
        self.descent
    }

    /// Cell width for a monospace face, or `None` when proportional.
    pub fn cell_advance(&self) -> Option<f32> {
        self.monospace.then_some(self.space_advance)
    }

    pub fn take_dirty(&mut self) -> bool {
        std::mem::take(&mut self.dirty)
    }

    pub fn coverage(&self) -> &[u8] {
        &self.coverage
    }

    pub fn atlas_size(&self) -> u32 {
        ATLAS_SIZE
    }

    /// Width of `text` in pixels, used for hit testing and truncation.
    pub fn measure(&mut self, text: &str) -> f32 {
        match self.cell_advance() {
            Some(cell) => cell * text.chars().count() as f32,
            None => text.chars().map(|ch| self.advance(ch)).sum(),
        }
    }

    /// Truncates to `max_width`, appending an ellipsis when it does not fit.
    pub fn ellipsize(&mut self, text: &str, max_width: f32) -> String {
        if self.measure(text) <= max_width {
            return text.to_string();
        }
        let ellipsis = "\u{2026}";
        let budget = max_width - self.measure(ellipsis);
        let mut out = String::new();
        let mut width = 0.0;
        for ch in text.chars() {
            let advance = self.advance(ch);
            if width + advance > budget {
                break;
            }
            out.push(ch);
            width += advance;
        }
        out.push_str(ellipsis);
        out
    }

    pub fn advance(&mut self, ch: char) -> f32 {
        if self.monospace {
            return self.space_advance;
        }
        let scaled = self.font.as_scaled(self.scale);
        scaled.h_advance(scaled.glyph_id(ch))
    }

    fn rasterize(&mut self, ch: char) -> Glyph {
        let advance = self.advance(ch);
        let outlined = {
            let scaled = self.font.as_scaled(self.scale);
            scaled.outline_glyph(scaled.scaled_glyph(ch))
        };
        let Some(outlined) = outlined else {
            return Glyph::blank(advance);
        };
        let bounds = outlined.px_bounds();
        let w = bounds.width().max(0.0) as u32;
        let h = bounds.height().max(0.0) as u32;
        if w == 0 || h == 0 {
            return Glyph::blank(advance);
        }
        let Some((x, y)) = self.allocate(w, h) else {
            // The atlas is full. Skipping the glyph keeps the frame correct
            // instead of invalidating cells the current frame already points at.
            return Glyph::blank(advance);
        };
        let mut coverage = vec![0u8; (w * h) as usize];
        outlined.draw(|px, py, value| {
            let index = py as usize * w as usize + px as usize;
            if let Some(slot) = coverage.get_mut(index) {
                *slot = (value.clamp(0.0, 1.0) * 255.0) as u8;
            }
        });
        self.blit(x, y, w, h, &coverage);
        self.dirty = true;
        Glyph {
            x: x as u16,
            y: y as u16,
            w: w as u16,
            h: h as u16,
            bearing_x: bounds.min.x,
            bearing_y: bounds.max.y,
            advance,
        }
    }

    /// First-fit row packing, which keeps insertion linear. Returns `None` once
    /// the atlas is full rather than recycling cells under the running frame.
    fn allocate(&mut self, w: u32, h: u32) -> Option<(u32, u32)> {
        if self.pen_x + w + PAD > ATLAS_SIZE {
            self.pen_x = PAD;
            self.pen_y += self.row_height + PAD;
            self.row_height = 0;
        }
        if self.pen_y + h + PAD > ATLAS_SIZE {
            return None;
        }
        let slot = (self.pen_x, self.pen_y);
        self.pen_x += w + PAD;
        self.row_height = self.row_height.max(h);
        Some(slot)
    }

    fn blit(&mut self, x: u32, y: u32, w: u32, h: u32, coverage: &[u8]) {
        for row in 0..h {
            let source = (row as usize) * w as usize;
            let target = ((y + row) * ATLAS_SIZE + x) as usize;
            self.coverage[target..target + w as usize]
                .copy_from_slice(&coverage[source..source + w as usize]);
        }
    }

    /// Emits one textured quad per visible glyph.
    pub fn shape(
        &mut self,
        out: &mut Vec<TextVertex>,
        text: &str,
        x: f32,
        baseline_y: f32,
        color: [f32; 4],
        layer: usize,
    ) -> f32 {
        let mut pen = x;
        for ch in text.chars() {
            if ch == '\n' || ch == '\r' {
                continue;
            }
            if ch == '\t' {
                pen += self.space_advance * 4.0;
                continue;
            }
            if ch.is_control() {
                continue;
            }
            let glyph = match self.glyphs.get(&ch) {
                Some(glyph) => *glyph,
                None => {
                    let glyph = self.rasterize(ch);
                    self.glyphs.insert(ch, glyph);
                    glyph
                }
            };
            if glyph.w > 0 && glyph.h > 0 {
                let scale = ATLAS_SIZE as f32;
                push_glyph(
                    out,
                    GlyphQuad {
                        left: pen + glyph.bearing_x,
                        top: baseline_y - glyph.bearing_y,
                        width: glyph.w as f32,
                        height: glyph.h as f32,
                        uv: [
                            glyph.x as f32 / scale,
                            glyph.y as f32 / scale,
                            glyph.w as f32 / scale,
                            glyph.h as f32 / scale,
                        ],
                        color,
                        layer: layer as f32,
                    },
                );
            }
            pen += glyph.advance;
        }
        pen - x
    }
}

/// Font metrics without rasterization, which is what the layout engine needs to
/// size and center text. Advances come straight from the font tables, so this
/// is cheap enough to call per node per frame.
#[derive(Clone)]
pub struct TextMetrics {
    /// Shared so the layout engine can own a measurer without re-parsing:
    /// `FontVec` is not `Clone`, but an `Arc` around it is.
    font: std::sync::Arc<FontVec>,
}

impl TextMetrics {
    pub fn new(font_bytes: &[u8]) -> Result<Self> {
        let font = FontVec::try_from_vec(font_bytes.to_vec())
            .map_err(|error| anyhow!("font parse failed: {error:?}"))?;
        Ok(Self {
            font: std::sync::Arc::new(font),
        })
    }

    /// Width of `text` at `size` pixels.
    pub fn measure(&self, text: &str, size: f32) -> f32 {
        let scaled = self.font.as_scaled(PxScale::from(size.max(1.0)));
        text.chars()
            .map(|ch| scaled.h_advance(scaled.glyph_id(ch)))
            .sum()
    }

    /// Ascent plus descent at `size` pixels.
    pub fn line_height(&self, size: f32) -> f32 {
        let scaled = self.font.as_scaled(PxScale::from(size.max(1.0)));
        (scaled.ascent() - scaled.descent()).ceil().max(1.0)
    }

    /// Ascent at `size` pixels, which is where a baseline sits below a box top.
    pub fn ascent(&self, size: f32) -> f32 {
        self.font.as_scaled(PxScale::from(size.max(1.0))).ascent()
    }
}

/// One atlas layer per distinct (pixel size, monospace) pair, uploaded into a
/// single texture array so a frame still needs only one text bind and one draw.
pub struct AtlasSet {
    atlases: Vec<GlyphAtlas>,
    keys: Vec<(u32, bool)>,
    dirty: bool,
}

impl AtlasSet {
    pub fn new() -> Self {
        Self {
            atlases: Vec::new(),
            keys: Vec::new(),
            dirty: true,
        }
    }

    /// Returns the layer index for a style, rasterizing a new layer on demand.
    pub fn layer(&mut self, size: f32, monospace: bool, font: &[u8]) -> Result<usize> {
        let key = (size.max(1.0).to_bits(), monospace);
        if let Some(index) = self.keys.iter().position(|existing| *existing == key) {
            return Ok(index);
        }
        let mut atlas = GlyphAtlas::new(font, size)?;
        atlas.set_monospace(monospace);
        self.atlases.push(atlas);
        self.keys.push(key);
        self.dirty = true;
        Ok(self.atlases.len() - 1)
    }

    pub fn get(&self, index: usize) -> &GlyphAtlas {
        &self.atlases[index]
    }

    pub fn get_mut(&mut self, index: usize) -> &mut GlyphAtlas {
        &mut self.atlases[index]
    }

    pub fn layers(&self) -> usize {
        self.atlases.len()
    }

    pub fn take_dirty(&mut self) -> bool {
        let mut dirty = std::mem::take(&mut self.dirty);
        for atlas in &mut self.atlases {
            dirty |= std::mem::take(&mut atlas.dirty);
        }
        dirty
    }

    pub fn atlases(&self) -> &[GlyphAtlas] {
        &self.atlases
    }
}

impl Default for AtlasSet {
    fn default() -> Self {
        Self::new()
    }
}

/// Texture array size for a layer count.
pub fn atlas_extent(layers: usize) -> wgpu::Extent3d {
    wgpu::Extent3d {
        width: ATLAS_SIZE,
        height: ATLAS_SIZE,
        depth_or_array_layers: layers.max(1) as u32,
    }
}

/// Creates the R8 texture array that backs every glyph layer.
pub fn create_atlas_texture(device: &wgpu::Device, layers: usize) -> wgpu::Texture {
    device.create_texture(&wgpu::TextureDescriptor {
        label: Some("rcus-glyph-atlas"),
        size: atlas_extent(layers),
        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: &[],
    })
}

/// Uploads every layer, one `write_texture` per layer, so a new glyph costs a
/// single small upload instead of rebuilding the array.
pub fn upload_atlas_layers(queue: &wgpu::Queue, texture: &wgpu::Texture, set: &AtlasSet) {
    for (layer, atlas) in set.atlases().iter().enumerate() {
        let size = wgpu::Extent3d {
            width: ATLAS_SIZE,
            height: ATLAS_SIZE,
            depth_or_array_layers: 1,
        };
        queue.write_texture(
            wgpu::ImageCopyTexture {
                texture,
                mip_level: 0,
                origin: wgpu::Origin3d {
                    x: 0,
                    y: 0,
                    z: layer as u32,
                },
                aspect: wgpu::TextureAspect::All,
            },
            atlas.coverage(),
            wgpu::ImageDataLayout {
                offset: 0,
                bytes_per_row: Some(ATLAS_SIZE),
                rows_per_image: Some(ATLAS_SIZE),
            },
            size,
        );
    }
}

/// Array view of the atlas texture, which is what the shader samples.
pub fn atlas_view(texture: &wgpu::Texture) -> wgpu::TextureView {
    texture.create_view(&wgpu::TextureViewDescriptor {
        dimension: Some(wgpu::TextureViewDimension::D2Array),
        ..Default::default()
    })
}