Skip to content

The native runtime for three.js: three.js, down to the metal. 45× smaller than Electron, on a Sony PS3, and path-traced at 60 fps on ray-tracing GPUs.

3.9 KB
Raw Blame
//! `text.layout.native`: the UI's font slots measured, wrapped and painted by CoreText through
//! the Canvas 2D text machinery (same faces, fallback and emoji advances as `fillText`).

use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::Rc;

use canvas2d::textblock::{self, BlockFont, TextFont};
use pocket_wgpu_render::{PaintedText, TextPainter, TextRunRequest};

/// What one font slot draws with.
#[derive(Clone, Debug)]
pub struct SlotFont {
    /// CSS family list, e.g. `["-apple-system", "PingFang SC", "sans-serif"]`
    pub families: Vec<String>,
    /// CSS weight, 100–900
    pub weight: u16,
    pub italic: bool,
    /// px
    pub size: f32,
    /// the slot's line pitch in px; `None` = the face's normal line height
    pub line_height: Option<f32>,
}

struct Slot {
    font: BlockFont,
    line_height: f32,
}

/// The resolved slots, shared by the core's measurer and wrapper and the renderer's painter.
pub struct SlotFonts {
    slots: Vec<Option<Slot>>,
    widths: RefCell<HashMap<(u8, u32, String), f64>>,
}

const WIDTH_CACHE: usize = 8192;

impl SlotFonts {
    pub fn new(slots: &[Option<SlotFont>]) -> SlotFonts {
        let slots = slots
            .iter()
            .map(|slot| {
                slot.as_ref().map(|s| {
                    let font = BlockFont::new(&TextFont { families: s.families.clone(), weight: s.weight, italic: s.italic, size: s.size as f64 });
                    let line_height = s.line_height.unwrap_or_else(|| font.normal_line_height() as f32);
                    Slot { font, line_height }
                })
            })
            .collect();
        SlotFonts { slots, widths: RefCell::new(HashMap::new()) }
    }
    fn slot(&self, slot: u8) -> Option<&Slot> {
        self.slots.get(slot as usize).and_then(|s| s.as_ref())
    }
    fn width(&self, slot: u8, font: &BlockFont, line: &str, tracking: f32) -> f64 {
        let key = (slot, tracking.to_bits(), line.to_owned());
        if let Some(w) = self.widths.borrow().get(&key) {
            return *w;
        }
        let w = font.measure_spaced(line, tracking as f64);
        let mut widths = self.widths.borrow_mut();
        if widths.len() >= WIDTH_CACHE {
            widths.clear();
        }
        widths.insert(key, w);
        w
    }
    /// `(widest line, lines × line height)` in logical px, `tracking` px after each character.
    pub fn measure(&self, text: &str, slot: u8, tracking: f32, line_height: f32) -> (f32, f32) {
        let Some(s) = self.slot(slot) else { return (0.0, 0.0) };
        if text.is_empty() {
            return (0.0, 0.0);
        }
        let lh = if line_height.is_nan() { s.line_height } else { line_height };
        let mut widest = 0.0f64;
        let mut lines = 0u32;
        for line in text.split('\n') {
            widest = widest.max(self.width(slot, &s.font, line, tracking));
            lines += 1;
        }
        (widest as f32, lines as f32 * lh)
    }
    /// Soft breaks (UTF-16 columns) for one line under `max_width`.
    pub fn wrap(&self, text: &str, slot: u8, max_width: f32) -> Vec<u32> {
        match self.slot(slot) {
            Some(s) => s.font.wrap(text, max_width as f64),
            None => Vec::new(),
        }
    }
    fn paint(&self, run: &TextRunRequest<'_>) -> Option<PaintedText> {
        let s = self.slot(run.slot)?;
        let lh = if run.line_height.is_nan() { s.line_height } else { run.line_height };
        let [r, g, b, _] = run.color.to_le_bytes();
        let block = textblock::paint(&s.font, run.text, [r, g, b, 255], run.align, run.box_width, lh, run.tracking, run.scale)?;
        Some(PaintedText { width: block.width, height: block.height, rgba: block.rgba, offset: block.offset })
    }
}

/// The renderer's side of the provider.
pub(crate) struct Painter(pub Rc<SlotFonts>);

impl TextPainter for Painter {
    fn paint(&mut self, run: &TextRunRequest<'_>) -> Option<PaintedText> {
        self.0.paint(run)
    }
}