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 for_char_set(chars: &[char], cell_w: u32, cell_h: u32, font_px: f64) -> Self {
99 let (w, h) = (cell_w, cell_h);
100 let mut atlas = Self::rasterize_chars(FONT_DATA, chars, w, h, font_px, false)
101 .expect("bundled font parses");
102 let len = (w * h) as usize;
103 let kana: Vec<char> = chars
104 .iter()
105 .map(|&c| if is_kana(c) { c } else { ' ' })
106 .collect();
107 if kana.iter().any(|&c| c != ' ') {
108 let k = Self::rasterize_chars(KANA_FONT, &kana, w, h, font_px, true)
109 .expect("bundled kana font parses");
110 for (i, _) in kana.iter().enumerate().filter(|(_, c)| **c != ' ') {
111 atlas.masks[i * len..(i + 1) * len]
112 .copy_from_slice(&k.masks[i * len..(i + 1) * len]);
113 }
114 }
115 for (i, &c) in chars.iter().enumerate() {
116 if let Some(dots) = braille_dots(c) {
117 braille(dots, w, h, &mut atlas.masks[i * len..(i + 1) * len]);
118 }
119 }
120 atlas
121 }
122
123 pub fn with_font(
125 font: &[u8],
126 cell_w: u32,
127 cell_h: u32,
128 font_px: f64,
129 ) -> Result<Self, AtlasError> {
130 Self::with_chars(font, &GLYPHS, cell_w, cell_h, font_px)
131 }
132
133 pub fn with_chars(
136 font: &[u8],
137 chars: &[char],
138 cell_w: u32,
139 cell_h: u32,
140 font_px: f64,
141 ) -> Result<Self, AtlasError> {
142 Self::rasterize_chars(font, chars, cell_w, cell_h, font_px, false)
143 }
144
145 fn rasterize_chars(
147 font: &[u8],
148 chars: &[char],
149 cell_w: u32,
150 cell_h: u32,
151 font_px: f64,
152 narrow: bool,
153 ) -> Result<Self, AtlasError> {
154 let face = FontRef::new(font).map_err(AtlasError::Font)?;
155 let location = LocationRef::default();
157 let metrics = face.metrics(Size::unscaled(), location);
158 let glyph_metrics = face.glyph_metrics(Size::unscaled(), location);
159 let outlines = face.outline_glyphs();
160 let charmap = face.charmap();
161 let upm = f64::from(metrics.units_per_em);
162 let scale = font_px / upm;
163 let cap = metrics.cap_height.map_or(0.73 * upm, f64::from);
164 let content = (cap + DESCENT_ROOM_EM * upm) * scale;
165 let baseline = (f64::from(cell_h) - content) * 0.5 + cap * scale;
166 let cell_len = (cell_w * cell_h) as usize;
167 let mut masks = vec![0u8; cell_len * chars.len()];
168 for (i, &ch) in chars.iter().enumerate() {
169 if ch == ' ' {
170 continue;
171 }
172 let Some(id) = charmap.map(ch) else {
173 continue;
174 };
175 let Some(glyph) = outlines.get(id) else {
176 continue;
177 };
178 let mut advance = f64::from(glyph_metrics.advance_width(id).unwrap_or(0.0)) * scale;
179 let room = f64::from(cell_w) * 0.94;
180 let sx = if narrow && advance > room {
181 room / advance
182 } else {
183 1.0
184 };
185 advance *= sx;
186 let mut outline = Flattener {
187 segs: Vec::new(),
188 ox: (f64::from(cell_w) - advance) * 0.5,
189 baseline,
190 scale,
191 sx,
192 cur: (0.0, 0.0),
193 start: (0.0, 0.0),
194 };
195 let settings = DrawSettings::unhinted(Size::unscaled(), location);
196 if glyph.draw(settings, &mut outline).is_err() {
197 continue;
198 }
199 rasterize(
200 &outline.segs,
201 cell_w,
202 cell_h,
203 &mut masks[i * cell_len..(i + 1) * cell_len],
204 );
205 }
206 Ok(Self {
207 cell_w,
208 cell_h,
209 masks,
210 })
211 }
212
213 pub fn fits(&self, cell_w: u32, cell_h: u32) -> bool {
216 let len = (cell_w as usize).saturating_mul(cell_h as usize);
217 (self.cell_w, self.cell_h) == (cell_w, cell_h)
218 && len > 0
219 && self.masks.len() >= len
220 && self.masks.len().is_multiple_of(len)
221 }
222
223 #[inline]
226 pub fn mask(&self, glyph: u8) -> &[u8] {
227 let len = (self.cell_w * self.cell_h) as usize;
228 let start = glyph as usize * len;
229 self.masks
230 .get(start..start + len)
231 .unwrap_or(&self.masks[..len])
232 }
233}
234
235#[derive(Clone, Copy, Debug)]
236struct Seg {
237 x0: f64,
238 y0: f64,
239 x1: f64,
240 y1: f64,
241}
242
243struct Flattener {
245 segs: Vec<Seg>,
246 ox: f64,
247 baseline: f64,
248 scale: f64,
249 sx: f64,
251 cur: (f64, f64),
252 start: (f64, f64),
253}
254
255impl Flattener {
256 fn map(&self, x: f32, y: f32) -> (f64, f64) {
257 (
258 self.ox + f64::from(x) * self.scale * self.sx,
259 self.baseline - f64::from(y) * self.scale,
260 )
261 }
262
263 fn push(&mut self, p: (f64, f64)) {
264 if p != self.cur {
265 self.segs.push(Seg {
266 x0: self.cur.0,
267 y0: self.cur.1,
268 x1: p.0,
269 y1: p.1,
270 });
271 }
272 self.cur = p;
273 }
274}
275
276impl OutlinePen for Flattener {
277 fn move_to(&mut self, x: f32, y: f32) {
278 let p = self.map(x, y);
279 self.cur = p;
280 self.start = p;
281 }
282
283 fn line_to(&mut self, x: f32, y: f32) {
284 let p = self.map(x, y);
285 self.push(p);
286 }
287
288 fn quad_to(&mut self, x1: f32, y1: f32, x: f32, y: f32) {
289 let p0 = self.cur;
290 let c = self.map(x1, y1);
291 let p1 = self.map(x, y);
292 for i in 1..=QUAD_STEPS {
293 let t = f64::from(i) / f64::from(QUAD_STEPS);
294 let u = 1.0 - t;
295 let px = u * u * p0.0 + 2.0 * u * t * c.0 + t * t * p1.0;
296 let py = u * u * p0.1 + 2.0 * u * t * c.1 + t * t * p1.1;
297 self.push((px, py));
298 }
299 }
300
301 fn curve_to(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, x: f32, y: f32) {
302 let p0 = self.cur;
303 let c1 = self.map(x1, y1);
304 let c2 = self.map(x2, y2);
305 let p1 = self.map(x, y);
306 for i in 1..=CUBIC_STEPS {
307 let t = f64::from(i) / f64::from(CUBIC_STEPS);
308 let u = 1.0 - t;
309 let (a, b, c, d) = (u * u * u, 3.0 * u * u * t, 3.0 * u * t * t, t * t * t);
310 let px = a * p0.0 + b * c1.0 + c * c2.0 + d * p1.0;
311 let py = a * p0.1 + b * c1.1 + c * c2.1 + d * p1.1;
312 self.push((px, py));
313 }
314 }
315
316 fn close(&mut self) {
317 let s = self.start;
318 self.push(s);
319 }
320}
321
322fn rasterize(segs: &[Seg], w: u32, h: u32, out: &mut [u8]) {
324 let s = SUPERSAMPLE;
325 let mut counts = vec![0u32; (w * h) as usize];
326 let mut xs: Vec<(f64, i32)> = Vec::with_capacity(32);
327 for py in 0..h {
328 for sy in 0..s {
329 let y = f64::from(py) + (f64::from(sy) + 0.5) / f64::from(s);
330 xs.clear();
331 for g in segs {
332 let crosses = (g.y0 <= y && y < g.y1) || (g.y1 <= y && y < g.y0);
333 if crosses {
334 let t = (y - g.y0) / (g.y1 - g.y0);
335 let dir = if g.y1 > g.y0 { 1 } else { -1 };
336 xs.push((g.x0 + t * (g.x1 - g.x0), dir));
337 }
338 }
339 if xs.is_empty() {
340 continue;
341 }
342 xs.sort_by(|a, b| a.0.total_cmp(&b.0).then(a.1.cmp(&b.1)));
343 let mut winding = 0;
344 let mut k = 0;
345 let row = (py * w) as usize;
346 for px in 0..w {
347 for sx in 0..s {
348 let x = f64::from(px) + (f64::from(sx) + 0.5) / f64::from(s);
349 while k < xs.len() && xs[k].0 <= x {
350 winding += xs[k].1;
351 k += 1;
352 }
353 if winding != 0 {
354 counts[row + px as usize] += 1;
355 }
356 }
357 }
358 }
359 }
360 let total = s * s;
361 for (o, &c) in out.iter_mut().zip(&counts) {
362 *o = ((c * 255 + total / 2) / total) as u8;
363 }
364}
365
366fn is_kana(c: char) -> bool {
368 ('\u{30A0}'..='\u{30FF}').contains(&c)
369}
370
371fn braille_dots(c: char) -> Option<u8> {
373 let v = u32::from(c);
374 (0x2801..=0x28FF).contains(&v).then(|| (v - 0x2800) as u8)
375}
376
377fn braille(dots: u8, w: u32, h: u32, out: &mut [u8]) {
381 const PLACE: [(u32, u32); 8] = [
384 (0, 0),
385 (0, 1),
386 (0, 2),
387 (1, 0),
388 (1, 1),
389 (1, 2),
390 (0, 3),
391 (1, 3),
392 ];
393 let (fw, fh) = (f64::from(w), f64::from(h));
394 let r = (fw * 0.14).min(fh * 0.07);
395 let centres: Vec<(f64, f64)> = PLACE
396 .iter()
397 .enumerate()
398 .filter(|(n, _)| dots & (1 << n) != 0)
399 .map(|(_, &(c, row))| {
400 (
401 fw * (0.3 + 0.4 * f64::from(c)),
402 fh * (0.17 + 0.2 * f64::from(row)),
403 )
404 })
405 .collect();
406 let s = f64::from(SUPERSAMPLE);
407 for y in 0..h {
408 for x in 0..w {
409 let mut hit = 0u32;
410 for sy in 0..SUPERSAMPLE {
411 for sx in 0..SUPERSAMPLE {
412 let px = f64::from(x) + (f64::from(sx) + 0.5) / s;
413 let py = f64::from(y) + (f64::from(sy) + 0.5) / s;
414 if centres
415 .iter()
416 .any(|&(cx, cy)| (px - cx) * (px - cx) + (py - cy) * (py - cy) <= r * r)
417 {
418 hit += 1;
419 }
420 }
421 }
422 out[(y * w + x) as usize] =
423 ((hit * 255 + SUPERSAMPLE * SUPERSAMPLE / 2) / (SUPERSAMPLE * SUPERSAMPLE)) as u8;
424 }
425 }
426}
427
428#[cfg(test)]
429mod tests {
430 use super::*;
431 use clairlune_scene::glyphs::{EMPTY, id};
432 use clairlune_scene::grid_spec;
433
434 fn ink(atlas: &GlyphAtlas, g: u8) -> u32 {
435 atlas.mask(g).iter().map(|&a| u32::from(a)).sum()
436 }
437
438 #[test]
439 fn glyphs_have_ink_and_space_is_empty() {
440 let atlas = GlyphAtlas::for_grid(&grid_spec(3840, 2160));
441 assert_eq!(ink(&atlas, EMPTY), 0);
442 for g in 1..GLYPHS.len() as u8 {
443 assert!(
444 ink(&atlas, g) > 0,
445 "glyph {:?} is blank",
446 GLYPHS[g as usize]
447 );
448 }
449 assert!(ink(&atlas, id('@')) > ink(&atlas, id('.')));
451 assert!(ink(&atlas, id('#')) > ink(&atlas, id('-')));
452 }
453
454 #[test]
455 fn every_letter_set_has_ink_where_its_glyphs_do() {
456 let spec = clairlune_scene::graph::grid_spec(1920, 1080);
457 let text = GlyphAtlas::for_grid(&spec);
458 assert_eq!(GlyphAtlas::for_letters(&spec, "text"), text);
459 for set in clairlune_scene::glyphs::LETTERS {
460 let a = GlyphAtlas::for_letters(&spec, set);
461 for (g, c) in clairlune_scene::glyphs::letters(set).iter().enumerate() {
462 let g = g as u8;
463 assert_eq!(ink(&a, g) == 0, g == EMPTY, "{set}: {c:?} ({g})");
464 }
465 }
466 let b = GlyphAtlas::for_letters(&spec, "braille");
468 assert!(ink(&b, id('.')) * 4 < ink(&b, id('@')));
469 }
470
471 #[test]
472 fn atlas_is_deterministic() {
473 let spec = grid_spec(640, 360);
474 assert_eq!(GlyphAtlas::for_grid(&spec), GlyphAtlas::for_grid(&spec));
475 }
476}