1use clairlune_scene::GridSpec;
11use clairlune_scene::glyphs::GLYPHS;
12use skrifa::instance::{LocationRef, Size};
13use skrifa::outline::{DrawSettings, OutlinePen};
14use skrifa::{FontRef, MetadataProvider};
15
16pub static FONT_DATA: &[u8] = include_bytes!("../assets/fonts/JetBrainsMono-Regular.ttf");
18
19const SUPERSAMPLE: u32 = 8;
21const QUAD_STEPS: u32 = 8;
23const CUBIC_STEPS: u32 = 12;
24const DESCENT_ROOM_EM: f64 = 0.22;
26
27#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
29pub struct GlyphAtlas {
30 pub cell_w: u32,
31 pub cell_h: u32,
32 masks: Vec<u8>,
33}
34
35#[derive(Debug)]
36pub enum AtlasError {
37 Font(skrifa::raw::ReadError),
38}
39
40impl std::fmt::Display for AtlasError {
41 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
42 match self {
43 AtlasError::Font(e) => write!(f, "font parse error: {e}"),
44 }
45 }
46}
47
48impl std::error::Error for AtlasError {}
49
50impl GlyphAtlas {
51 pub fn for_grid(spec: &GridSpec) -> Self {
53 Self::with_font(FONT_DATA, spec.cell_w, spec.cell_h, spec.font_px)
54 .expect("bundled font parses")
55 }
56
57 pub fn with_font(
59 font: &[u8],
60 cell_w: u32,
61 cell_h: u32,
62 font_px: f64,
63 ) -> Result<Self, AtlasError> {
64 let face = FontRef::new(font).map_err(AtlasError::Font)?;
65 let location = LocationRef::default();
67 let metrics = face.metrics(Size::unscaled(), location);
68 let glyph_metrics = face.glyph_metrics(Size::unscaled(), location);
69 let outlines = face.outline_glyphs();
70 let charmap = face.charmap();
71 let upm = f64::from(metrics.units_per_em);
72 let scale = font_px / upm;
73 let cap = metrics.cap_height.map_or(0.73 * upm, f64::from);
74 let content = (cap + DESCENT_ROOM_EM * upm) * scale;
75 let baseline = (f64::from(cell_h) - content) * 0.5 + cap * scale;
76 let cell_len = (cell_w * cell_h) as usize;
77 let mut masks = vec![0u8; cell_len * GLYPHS.len()];
78 for (i, &ch) in GLYPHS.iter().enumerate() {
79 if ch == ' ' {
80 continue;
81 }
82 let Some(id) = charmap.map(ch) else {
83 continue;
84 };
85 let Some(glyph) = outlines.get(id) else {
86 continue;
87 };
88 let advance = f64::from(glyph_metrics.advance_width(id).unwrap_or(0.0)) * scale;
89 let mut outline = Flattener {
90 segs: Vec::new(),
91 ox: (f64::from(cell_w) - advance) * 0.5,
92 baseline,
93 scale,
94 cur: (0.0, 0.0),
95 start: (0.0, 0.0),
96 };
97 let settings = DrawSettings::unhinted(Size::unscaled(), location);
98 if glyph.draw(settings, &mut outline).is_err() {
99 continue;
100 }
101 rasterize(
102 &outline.segs,
103 cell_w,
104 cell_h,
105 &mut masks[i * cell_len..(i + 1) * cell_len],
106 );
107 }
108 Ok(Self {
109 cell_w,
110 cell_h,
111 masks,
112 })
113 }
114
115 pub fn fits(&self, cell_w: u32, cell_h: u32) -> bool {
118 let len = (cell_w as usize).saturating_mul(cell_h as usize);
119 (self.cell_w, self.cell_h) == (cell_w, cell_h)
120 && len > 0
121 && self.masks.len() >= len
122 && self.masks.len().is_multiple_of(len)
123 }
124
125 #[inline]
128 pub fn mask(&self, glyph: u8) -> &[u8] {
129 let len = (self.cell_w * self.cell_h) as usize;
130 let start = glyph as usize * len;
131 self.masks
132 .get(start..start + len)
133 .unwrap_or(&self.masks[..len])
134 }
135}
136
137#[derive(Clone, Copy, Debug)]
138struct Seg {
139 x0: f64,
140 y0: f64,
141 x1: f64,
142 y1: f64,
143}
144
145struct Flattener {
147 segs: Vec<Seg>,
148 ox: f64,
149 baseline: f64,
150 scale: f64,
151 cur: (f64, f64),
152 start: (f64, f64),
153}
154
155impl Flattener {
156 fn map(&self, x: f32, y: f32) -> (f64, f64) {
157 (
158 self.ox + f64::from(x) * self.scale,
159 self.baseline - f64::from(y) * self.scale,
160 )
161 }
162
163 fn push(&mut self, p: (f64, f64)) {
164 if p != self.cur {
165 self.segs.push(Seg {
166 x0: self.cur.0,
167 y0: self.cur.1,
168 x1: p.0,
169 y1: p.1,
170 });
171 }
172 self.cur = p;
173 }
174}
175
176impl OutlinePen for Flattener {
177 fn move_to(&mut self, x: f32, y: f32) {
178 let p = self.map(x, y);
179 self.cur = p;
180 self.start = p;
181 }
182
183 fn line_to(&mut self, x: f32, y: f32) {
184 let p = self.map(x, y);
185 self.push(p);
186 }
187
188 fn quad_to(&mut self, x1: f32, y1: f32, x: f32, y: f32) {
189 let p0 = self.cur;
190 let c = self.map(x1, y1);
191 let p1 = self.map(x, y);
192 for i in 1..=QUAD_STEPS {
193 let t = f64::from(i) / f64::from(QUAD_STEPS);
194 let u = 1.0 - t;
195 let px = u * u * p0.0 + 2.0 * u * t * c.0 + t * t * p1.0;
196 let py = u * u * p0.1 + 2.0 * u * t * c.1 + t * t * p1.1;
197 self.push((px, py));
198 }
199 }
200
201 fn curve_to(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, x: f32, y: f32) {
202 let p0 = self.cur;
203 let c1 = self.map(x1, y1);
204 let c2 = self.map(x2, y2);
205 let p1 = self.map(x, y);
206 for i in 1..=CUBIC_STEPS {
207 let t = f64::from(i) / f64::from(CUBIC_STEPS);
208 let u = 1.0 - t;
209 let (a, b, c, d) = (u * u * u, 3.0 * u * u * t, 3.0 * u * t * t, t * t * t);
210 let px = a * p0.0 + b * c1.0 + c * c2.0 + d * p1.0;
211 let py = a * p0.1 + b * c1.1 + c * c2.1 + d * p1.1;
212 self.push((px, py));
213 }
214 }
215
216 fn close(&mut self) {
217 let s = self.start;
218 self.push(s);
219 }
220}
221
222fn rasterize(segs: &[Seg], w: u32, h: u32, out: &mut [u8]) {
224 let s = SUPERSAMPLE;
225 let mut counts = vec![0u32; (w * h) as usize];
226 let mut xs: Vec<(f64, i32)> = Vec::with_capacity(32);
227 for py in 0..h {
228 for sy in 0..s {
229 let y = f64::from(py) + (f64::from(sy) + 0.5) / f64::from(s);
230 xs.clear();
231 for g in segs {
232 let crosses = (g.y0 <= y && y < g.y1) || (g.y1 <= y && y < g.y0);
233 if crosses {
234 let t = (y - g.y0) / (g.y1 - g.y0);
235 let dir = if g.y1 > g.y0 { 1 } else { -1 };
236 xs.push((g.x0 + t * (g.x1 - g.x0), dir));
237 }
238 }
239 if xs.is_empty() {
240 continue;
241 }
242 xs.sort_by(|a, b| a.0.total_cmp(&b.0).then(a.1.cmp(&b.1)));
243 let mut winding = 0;
244 let mut k = 0;
245 let row = (py * w) as usize;
246 for px in 0..w {
247 for sx in 0..s {
248 let x = f64::from(px) + (f64::from(sx) + 0.5) / f64::from(s);
249 while k < xs.len() && xs[k].0 <= x {
250 winding += xs[k].1;
251 k += 1;
252 }
253 if winding != 0 {
254 counts[row + px as usize] += 1;
255 }
256 }
257 }
258 }
259 }
260 let total = s * s;
261 for (o, &c) in out.iter_mut().zip(&counts) {
262 *o = ((c * 255 + total / 2) / total) as u8;
263 }
264}
265
266#[cfg(test)]
267mod tests {
268 use super::*;
269 use clairlune_scene::glyphs::{EMPTY, id};
270 use clairlune_scene::grid_spec;
271
272 fn ink(atlas: &GlyphAtlas, g: u8) -> u32 {
273 atlas.mask(g).iter().map(|&a| u32::from(a)).sum()
274 }
275
276 #[test]
277 fn glyphs_have_ink_and_space_is_empty() {
278 let atlas = GlyphAtlas::for_grid(&grid_spec(3840, 2160));
279 assert_eq!(ink(&atlas, EMPTY), 0);
280 for g in 1..GLYPHS.len() as u8 {
281 assert!(
282 ink(&atlas, g) > 0,
283 "glyph {:?} is blank",
284 GLYPHS[g as usize]
285 );
286 }
287 assert!(ink(&atlas, id('@')) > ink(&atlas, id('.')));
289 assert!(ink(&atlas, id('#')) > ink(&atlas, id('-')));
290 }
291
292 #[test]
293 fn atlas_is_deterministic() {
294 let spec = grid_spec(640, 360);
295 assert_eq!(GlyphAtlas::for_grid(&spec), GlyphAtlas::for_grid(&spec));
296 }
297}