1use clairlune_scene::glyphs::GLYPHS;
11use clairlune_scene::{GridSpec, SceneGraph};
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
19pub static KANA_FONT: &[u8] = include_bytes!("../assets/fonts/ClairluneKana.ttf");
22
23const SUPERSAMPLE: u32 = 8;
25const QUAD_STEPS: u32 = 8;
27const CUBIC_STEPS: u32 = 12;
28const DESCENT_ROOM_EM: f64 = 0.22;
30
31#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
33pub struct GlyphAtlas {
34 pub cell_w: u32,
35 pub cell_h: u32,
36 masks: Vec<u8>,
37}
38
39#[derive(Debug)]
40pub enum AtlasError {
41 Font(skrifa::raw::ReadError),
42}
43
44impl std::fmt::Display for AtlasError {
45 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
46 match self {
47 AtlasError::Font(e) => write!(f, "font parse error: {e}"),
48 }
49 }
50}
51
52impl std::error::Error for AtlasError {}
53
54impl GlyphAtlas {
55 pub fn for_grid(spec: &GridSpec) -> Self {
57 Self::with_font(FONT_DATA, spec.cell_w, spec.cell_h, spec.font_px)
58 .expect("bundled font parses")
59 }
60
61 pub fn for_graph(graph: &SceneGraph) -> Self {
63 Self::for_letters(&graph.grid, &graph.letters)
64 }
65
66 pub fn for_letters(spec: &GridSpec, letters: &str) -> Self {
70 let chars = clairlune_scene::glyphs::letters(letters);
71 let (w, h) = (spec.cell_w, spec.cell_h);
72 let mut atlas = Self::rasterize_chars(FONT_DATA, &chars, w, h, spec.font_px, false)
73 .expect("bundled font parses");
74 let len = (w * h) as usize;
75 let kana: Vec<char> = chars
76 .iter()
77 .map(|&c| if is_kana(c) { c } else { ' ' })
78 .collect();
79 if kana.iter().any(|&c| c != ' ') {
80 let k = Self::rasterize_chars(KANA_FONT, &kana, w, h, spec.font_px, true)
81 .expect("bundled kana font parses");
82 for (i, _) in kana.iter().enumerate().filter(|(_, c)| **c != ' ') {
83 atlas.masks[i * len..(i + 1) * len]
84 .copy_from_slice(&k.masks[i * len..(i + 1) * len]);
85 }
86 }
87 for (i, &c) in chars.iter().enumerate() {
88 if let Some(dots) = braille_dots(c) {
89 braille(dots, w, h, &mut atlas.masks[i * len..(i + 1) * len]);
90 }
91 }
92 atlas
93 }
94
95 pub fn can_render_char(c: char) -> bool {
97 if c == ' ' || c.is_control() {
98 return false;
99 }
100 if is_kana(c) || braille_dots(c).is_some() {
101 return true;
102 }
103 let Ok(face) = FontRef::new(FONT_DATA) else {
104 return false;
105 };
106 let Some(id) = face.charmap().map(c) else {
107 return false;
108 };
109 face.outline_glyphs().get(id).is_some()
110 }
111
112 pub fn for_char_set(chars: &[char], cell_w: u32, cell_h: u32, font_px: f64) -> Self {
116 let (w, h) = (cell_w, cell_h);
117 let mut atlas = Self::rasterize_chars(FONT_DATA, chars, w, h, font_px, false)
118 .expect("bundled font parses");
119 let len = (w * h) as usize;
120 let kana: Vec<char> = chars
121 .iter()
122 .map(|&c| if is_kana(c) { c } else { ' ' })
123 .collect();
124 if kana.iter().any(|&c| c != ' ') {
125 let k = Self::rasterize_chars(KANA_FONT, &kana, w, h, font_px, true)
126 .expect("bundled kana font parses");
127 for (i, _) in kana.iter().enumerate().filter(|(_, c)| **c != ' ') {
128 atlas.masks[i * len..(i + 1) * len]
129 .copy_from_slice(&k.masks[i * len..(i + 1) * len]);
130 }
131 }
132 for (i, &c) in chars.iter().enumerate() {
133 if let Some(dots) = braille_dots(c) {
134 braille(dots, w, h, &mut atlas.masks[i * len..(i + 1) * len]);
135 }
136 }
137 atlas
138 }
139
140 pub fn with_font(
142 font: &[u8],
143 cell_w: u32,
144 cell_h: u32,
145 font_px: f64,
146 ) -> Result<Self, AtlasError> {
147 Self::with_chars(font, &GLYPHS, cell_w, cell_h, font_px)
148 }
149
150 pub fn with_chars(
153 font: &[u8],
154 chars: &[char],
155 cell_w: u32,
156 cell_h: u32,
157 font_px: f64,
158 ) -> Result<Self, AtlasError> {
159 Self::rasterize_chars(font, chars, cell_w, cell_h, font_px, false)
160 }
161
162 fn rasterize_chars(
164 font: &[u8],
165 chars: &[char],
166 cell_w: u32,
167 cell_h: u32,
168 font_px: f64,
169 narrow: bool,
170 ) -> Result<Self, AtlasError> {
171 let face = FontRef::new(font).map_err(AtlasError::Font)?;
172 let location = LocationRef::default();
174 let metrics = face.metrics(Size::unscaled(), location);
175 let glyph_metrics = face.glyph_metrics(Size::unscaled(), location);
176 let outlines = face.outline_glyphs();
177 let charmap = face.charmap();
178 let upm = f64::from(metrics.units_per_em);
179 let scale = font_px / upm;
180 let cap = metrics.cap_height.map_or(0.73 * upm, f64::from);
181 let content = (cap + DESCENT_ROOM_EM * upm) * scale;
182 let baseline = (f64::from(cell_h) - content) * 0.5 + cap * scale;
183 let cell_len = (cell_w * cell_h) as usize;
184 let mut masks = vec![0u8; cell_len * chars.len()];
185 for (i, &ch) in chars.iter().enumerate() {
186 if ch == ' ' {
187 continue;
188 }
189 let Some(id) = charmap.map(ch) else {
190 continue;
191 };
192 let Some(glyph) = outlines.get(id) else {
193 continue;
194 };
195 let mut advance = f64::from(glyph_metrics.advance_width(id).unwrap_or(0.0)) * scale;
196 let room = f64::from(cell_w) * 0.94;
197 let sx = if narrow && advance > room {
198 room / advance
199 } else {
200 1.0
201 };
202 advance *= sx;
203 let mut outline = Flattener {
204 segs: Vec::new(),
205 ox: (f64::from(cell_w) - advance) * 0.5,
206 baseline,
207 scale,
208 sx,
209 cur: (0.0, 0.0),
210 start: (0.0, 0.0),
211 };
212 let settings = DrawSettings::unhinted(Size::unscaled(), location);
213 if glyph.draw(settings, &mut outline).is_err() {
214 continue;
215 }
216 rasterize(
217 &outline.segs,
218 cell_w,
219 cell_h,
220 &mut masks[i * cell_len..(i + 1) * cell_len],
221 );
222 }
223 Ok(Self {
224 cell_w,
225 cell_h,
226 masks,
227 })
228 }
229
230 pub fn fits(&self, cell_w: u32, cell_h: u32) -> bool {
233 let len = (cell_w as usize).saturating_mul(cell_h as usize);
234 (self.cell_w, self.cell_h) == (cell_w, cell_h)
235 && len > 0
236 && self.masks.len() >= len
237 && self.masks.len().is_multiple_of(len)
238 }
239
240 #[inline]
243 pub fn mask(&self, glyph: u8) -> &[u8] {
244 let len = (self.cell_w * self.cell_h) as usize;
245 let start = glyph as usize * len;
246 self.masks
247 .get(start..start + len)
248 .unwrap_or(&self.masks[..len])
249 }
250}
251
252#[derive(Clone, Copy, Debug)]
253struct Seg {
254 x0: f64,
255 y0: f64,
256 x1: f64,
257 y1: f64,
258}
259
260struct Flattener {
262 segs: Vec<Seg>,
263 ox: f64,
264 baseline: f64,
265 scale: f64,
266 sx: f64,
268 cur: (f64, f64),
269 start: (f64, f64),
270}
271
272impl Flattener {
273 fn map(&self, x: f32, y: f32) -> (f64, f64) {
274 (
275 self.ox + f64::from(x) * self.scale * self.sx,
276 self.baseline - f64::from(y) * self.scale,
277 )
278 }
279
280 fn push(&mut self, p: (f64, f64)) {
281 if p != self.cur {
282 self.segs.push(Seg {
283 x0: self.cur.0,
284 y0: self.cur.1,
285 x1: p.0,
286 y1: p.1,
287 });
288 }
289 self.cur = p;
290 }
291}
292
293impl OutlinePen for Flattener {
294 fn move_to(&mut self, x: f32, y: f32) {
295 let p = self.map(x, y);
296 self.cur = p;
297 self.start = p;
298 }
299
300 fn line_to(&mut self, x: f32, y: f32) {
301 let p = self.map(x, y);
302 self.push(p);
303 }
304
305 fn quad_to(&mut self, x1: f32, y1: f32, x: f32, y: f32) {
306 let p0 = self.cur;
307 let c = self.map(x1, y1);
308 let p1 = self.map(x, y);
309 for i in 1..=QUAD_STEPS {
310 let t = f64::from(i) / f64::from(QUAD_STEPS);
311 let u = 1.0 - t;
312 let px = u * u * p0.0 + 2.0 * u * t * c.0 + t * t * p1.0;
313 let py = u * u * p0.1 + 2.0 * u * t * c.1 + t * t * p1.1;
314 self.push((px, py));
315 }
316 }
317
318 fn curve_to(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, x: f32, y: f32) {
319 let p0 = self.cur;
320 let c1 = self.map(x1, y1);
321 let c2 = self.map(x2, y2);
322 let p1 = self.map(x, y);
323 for i in 1..=CUBIC_STEPS {
324 let t = f64::from(i) / f64::from(CUBIC_STEPS);
325 let u = 1.0 - t;
326 let (a, b, c, d) = (u * u * u, 3.0 * u * u * t, 3.0 * u * t * t, t * t * t);
327 let px = a * p0.0 + b * c1.0 + c * c2.0 + d * p1.0;
328 let py = a * p0.1 + b * c1.1 + c * c2.1 + d * p1.1;
329 self.push((px, py));
330 }
331 }
332
333 fn close(&mut self) {
334 let s = self.start;
335 self.push(s);
336 }
337}
338
339fn rasterize(segs: &[Seg], w: u32, h: u32, out: &mut [u8]) {
341 let s = SUPERSAMPLE;
342 let mut counts = vec![0u32; (w * h) as usize];
343 let mut xs: Vec<(f64, i32)> = Vec::with_capacity(32);
344 for py in 0..h {
345 for sy in 0..s {
346 let y = f64::from(py) + (f64::from(sy) + 0.5) / f64::from(s);
347 xs.clear();
348 for g in segs {
349 let crosses = (g.y0 <= y && y < g.y1) || (g.y1 <= y && y < g.y0);
350 if crosses {
351 let t = (y - g.y0) / (g.y1 - g.y0);
352 let dir = if g.y1 > g.y0 { 1 } else { -1 };
353 xs.push((g.x0 + t * (g.x1 - g.x0), dir));
354 }
355 }
356 if xs.is_empty() {
357 continue;
358 }
359 xs.sort_by(|a, b| a.0.total_cmp(&b.0).then(a.1.cmp(&b.1)));
360 let mut winding = 0;
361 let mut k = 0;
362 let row = (py * w) as usize;
363 for px in 0..w {
364 for sx in 0..s {
365 let x = f64::from(px) + (f64::from(sx) + 0.5) / f64::from(s);
366 while k < xs.len() && xs[k].0 <= x {
367 winding += xs[k].1;
368 k += 1;
369 }
370 if winding != 0 {
371 counts[row + px as usize] += 1;
372 }
373 }
374 }
375 }
376 }
377 let total = s * s;
378 for (o, &c) in out.iter_mut().zip(&counts) {
379 *o = ((c * 255 + total / 2) / total) as u8;
380 }
381}
382
383fn is_kana(c: char) -> bool {
385 ('\u{30A0}'..='\u{30FF}').contains(&c)
386}
387
388fn braille_dots(c: char) -> Option<u8> {
390 let v = u32::from(c);
391 (0x2801..=0x28FF).contains(&v).then(|| (v - 0x2800) as u8)
392}
393
394fn braille(dots: u8, w: u32, h: u32, out: &mut [u8]) {
398 const PLACE: [(u32, u32); 8] = [
401 (0, 0),
402 (0, 1),
403 (0, 2),
404 (1, 0),
405 (1, 1),
406 (1, 2),
407 (0, 3),
408 (1, 3),
409 ];
410 let (fw, fh) = (f64::from(w), f64::from(h));
411 let r = (fw * 0.14).min(fh * 0.07);
412 let centres: Vec<(f64, f64)> = PLACE
413 .iter()
414 .enumerate()
415 .filter(|(n, _)| dots & (1 << n) != 0)
416 .map(|(_, &(c, row))| {
417 (
418 fw * (0.3 + 0.4 * f64::from(c)),
419 fh * (0.17 + 0.2 * f64::from(row)),
420 )
421 })
422 .collect();
423 let s = f64::from(SUPERSAMPLE);
424 for y in 0..h {
425 for x in 0..w {
426 let mut hit = 0u32;
427 for sy in 0..SUPERSAMPLE {
428 for sx in 0..SUPERSAMPLE {
429 let px = f64::from(x) + (f64::from(sx) + 0.5) / s;
430 let py = f64::from(y) + (f64::from(sy) + 0.5) / s;
431 if centres
432 .iter()
433 .any(|&(cx, cy)| (px - cx) * (px - cx) + (py - cy) * (py - cy) <= r * r)
434 {
435 hit += 1;
436 }
437 }
438 }
439 out[(y * w + x) as usize] =
440 ((hit * 255 + SUPERSAMPLE * SUPERSAMPLE / 2) / (SUPERSAMPLE * SUPERSAMPLE)) as u8;
441 }
442 }
443}
444
445#[cfg(test)]
446mod tests {
447 use super::*;
448 use clairlune_scene::glyphs::{EMPTY, id};
449 use clairlune_scene::grid_spec;
450
451 fn ink(atlas: &GlyphAtlas, g: u8) -> u32 {
452 atlas.mask(g).iter().map(|&a| u32::from(a)).sum()
453 }
454
455 #[test]
456 fn glyphs_have_ink_and_space_is_empty() {
457 let atlas = GlyphAtlas::for_grid(&grid_spec(3840, 2160));
458 assert_eq!(ink(&atlas, EMPTY), 0);
459 for g in 1..GLYPHS.len() as u8 {
460 assert!(
461 ink(&atlas, g) > 0,
462 "glyph {:?} is blank",
463 GLYPHS[g as usize]
464 );
465 }
466 assert!(ink(&atlas, id('@')) > ink(&atlas, id('.')));
468 assert!(ink(&atlas, id('#')) > ink(&atlas, id('-')));
469 }
470
471 #[test]
472 fn every_letter_set_has_ink_where_its_glyphs_do() {
473 let spec = clairlune_scene::graph::grid_spec(1920, 1080);
474 let text = GlyphAtlas::for_grid(&spec);
475 assert_eq!(GlyphAtlas::for_letters(&spec, "text"), text);
476 for set in clairlune_scene::glyphs::LETTERS {
477 let a = GlyphAtlas::for_letters(&spec, set);
478 for (g, c) in clairlune_scene::glyphs::letters(set).iter().enumerate() {
479 let g = g as u8;
480 assert_eq!(ink(&a, g) == 0, g == EMPTY, "{set}: {c:?} ({g})");
481 }
482 }
483 let b = GlyphAtlas::for_letters(&spec, "braille");
485 assert!(ink(&b, id('.')) * 4 < ink(&b, id('@')));
486 }
487
488 #[test]
489 fn atlas_is_deterministic() {
490 let spec = grid_spec(640, 360);
491 assert_eq!(GlyphAtlas::for_grid(&spec), GlyphAtlas::for_grid(&spec));
492 }
493}