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)]
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 #[inline]
117 pub fn mask(&self, glyph: u8) -> &[u8] {
118 let len = (self.cell_w * self.cell_h) as usize;
119 let start = glyph as usize * len;
120 &self.masks[start..start + len]
121 }
122}
123
124#[derive(Clone, Copy, Debug)]
125struct Seg {
126 x0: f64,
127 y0: f64,
128 x1: f64,
129 y1: f64,
130}
131
132struct Flattener {
134 segs: Vec<Seg>,
135 ox: f64,
136 baseline: f64,
137 scale: f64,
138 cur: (f64, f64),
139 start: (f64, f64),
140}
141
142impl Flattener {
143 fn map(&self, x: f32, y: f32) -> (f64, f64) {
144 (
145 self.ox + f64::from(x) * self.scale,
146 self.baseline - f64::from(y) * self.scale,
147 )
148 }
149
150 fn push(&mut self, p: (f64, f64)) {
151 if p != self.cur {
152 self.segs.push(Seg {
153 x0: self.cur.0,
154 y0: self.cur.1,
155 x1: p.0,
156 y1: p.1,
157 });
158 }
159 self.cur = p;
160 }
161}
162
163impl OutlinePen for Flattener {
164 fn move_to(&mut self, x: f32, y: f32) {
165 let p = self.map(x, y);
166 self.cur = p;
167 self.start = p;
168 }
169
170 fn line_to(&mut self, x: f32, y: f32) {
171 let p = self.map(x, y);
172 self.push(p);
173 }
174
175 fn quad_to(&mut self, x1: f32, y1: f32, x: f32, y: f32) {
176 let p0 = self.cur;
177 let c = self.map(x1, y1);
178 let p1 = self.map(x, y);
179 for i in 1..=QUAD_STEPS {
180 let t = f64::from(i) / f64::from(QUAD_STEPS);
181 let u = 1.0 - t;
182 let px = u * u * p0.0 + 2.0 * u * t * c.0 + t * t * p1.0;
183 let py = u * u * p0.1 + 2.0 * u * t * c.1 + t * t * p1.1;
184 self.push((px, py));
185 }
186 }
187
188 fn curve_to(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, x: f32, y: f32) {
189 let p0 = self.cur;
190 let c1 = self.map(x1, y1);
191 let c2 = self.map(x2, y2);
192 let p1 = self.map(x, y);
193 for i in 1..=CUBIC_STEPS {
194 let t = f64::from(i) / f64::from(CUBIC_STEPS);
195 let u = 1.0 - t;
196 let (a, b, c, d) = (u * u * u, 3.0 * u * u * t, 3.0 * u * t * t, t * t * t);
197 let px = a * p0.0 + b * c1.0 + c * c2.0 + d * p1.0;
198 let py = a * p0.1 + b * c1.1 + c * c2.1 + d * p1.1;
199 self.push((px, py));
200 }
201 }
202
203 fn close(&mut self) {
204 let s = self.start;
205 self.push(s);
206 }
207}
208
209fn rasterize(segs: &[Seg], w: u32, h: u32, out: &mut [u8]) {
211 let s = SUPERSAMPLE;
212 let mut counts = vec![0u32; (w * h) as usize];
213 let mut xs: Vec<(f64, i32)> = Vec::with_capacity(32);
214 for py in 0..h {
215 for sy in 0..s {
216 let y = f64::from(py) + (f64::from(sy) + 0.5) / f64::from(s);
217 xs.clear();
218 for g in segs {
219 let crosses = (g.y0 <= y && y < g.y1) || (g.y1 <= y && y < g.y0);
220 if crosses {
221 let t = (y - g.y0) / (g.y1 - g.y0);
222 let dir = if g.y1 > g.y0 { 1 } else { -1 };
223 xs.push((g.x0 + t * (g.x1 - g.x0), dir));
224 }
225 }
226 if xs.is_empty() {
227 continue;
228 }
229 xs.sort_by(|a, b| a.0.total_cmp(&b.0).then(a.1.cmp(&b.1)));
230 let mut winding = 0;
231 let mut k = 0;
232 let row = (py * w) as usize;
233 for px in 0..w {
234 for sx in 0..s {
235 let x = f64::from(px) + (f64::from(sx) + 0.5) / f64::from(s);
236 while k < xs.len() && xs[k].0 <= x {
237 winding += xs[k].1;
238 k += 1;
239 }
240 if winding != 0 {
241 counts[row + px as usize] += 1;
242 }
243 }
244 }
245 }
246 }
247 let total = s * s;
248 for (o, &c) in out.iter_mut().zip(&counts) {
249 *o = ((c * 255 + total / 2) / total) as u8;
250 }
251}
252
253#[cfg(test)]
254mod tests {
255 use super::*;
256 use clairlune_scene::glyphs::{EMPTY, id};
257 use clairlune_scene::grid_spec;
258
259 fn ink(atlas: &GlyphAtlas, g: u8) -> u32 {
260 atlas.mask(g).iter().map(|&a| u32::from(a)).sum()
261 }
262
263 #[test]
264 fn glyphs_have_ink_and_space_is_empty() {
265 let atlas = GlyphAtlas::for_grid(&grid_spec(3840, 2160));
266 assert_eq!(ink(&atlas, EMPTY), 0);
267 for g in 1..GLYPHS.len() as u8 {
268 assert!(
269 ink(&atlas, g) > 0,
270 "glyph {:?} is blank",
271 GLYPHS[g as usize]
272 );
273 }
274 assert!(ink(&atlas, id('@')) > ink(&atlas, id('.')));
276 assert!(ink(&atlas, id('#')) > ink(&atlas, id('-')));
277 }
278
279 #[test]
280 fn atlas_is_deterministic() {
281 let spec = grid_spec(640, 360);
282 assert_eq!(GlyphAtlas::for_grid(&spec), GlyphAtlas::for_grid(&spec));
283 }
284}