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 Self::with_chars(font, &GLYPHS, cell_w, cell_h, font_px)
65 }
66
67 pub fn with_chars(
70 font: &[u8],
71 chars: &[char],
72 cell_w: u32,
73 cell_h: u32,
74 font_px: f64,
75 ) -> Result<Self, AtlasError> {
76 let face = FontRef::new(font).map_err(AtlasError::Font)?;
77 let location = LocationRef::default();
79 let metrics = face.metrics(Size::unscaled(), location);
80 let glyph_metrics = face.glyph_metrics(Size::unscaled(), location);
81 let outlines = face.outline_glyphs();
82 let charmap = face.charmap();
83 let upm = f64::from(metrics.units_per_em);
84 let scale = font_px / upm;
85 let cap = metrics.cap_height.map_or(0.73 * upm, f64::from);
86 let content = (cap + DESCENT_ROOM_EM * upm) * scale;
87 let baseline = (f64::from(cell_h) - content) * 0.5 + cap * scale;
88 let cell_len = (cell_w * cell_h) as usize;
89 let mut masks = vec![0u8; cell_len * chars.len()];
90 for (i, &ch) in chars.iter().enumerate() {
91 if ch == ' ' {
92 continue;
93 }
94 let Some(id) = charmap.map(ch) else {
95 continue;
96 };
97 let Some(glyph) = outlines.get(id) else {
98 continue;
99 };
100 let advance = f64::from(glyph_metrics.advance_width(id).unwrap_or(0.0)) * scale;
101 let mut outline = Flattener {
102 segs: Vec::new(),
103 ox: (f64::from(cell_w) - advance) * 0.5,
104 baseline,
105 scale,
106 cur: (0.0, 0.0),
107 start: (0.0, 0.0),
108 };
109 let settings = DrawSettings::unhinted(Size::unscaled(), location);
110 if glyph.draw(settings, &mut outline).is_err() {
111 continue;
112 }
113 rasterize(
114 &outline.segs,
115 cell_w,
116 cell_h,
117 &mut masks[i * cell_len..(i + 1) * cell_len],
118 );
119 }
120 Ok(Self {
121 cell_w,
122 cell_h,
123 masks,
124 })
125 }
126
127 pub fn fits(&self, cell_w: u32, cell_h: u32) -> bool {
130 let len = (cell_w as usize).saturating_mul(cell_h as usize);
131 (self.cell_w, self.cell_h) == (cell_w, cell_h)
132 && len > 0
133 && self.masks.len() >= len
134 && self.masks.len().is_multiple_of(len)
135 }
136
137 #[inline]
140 pub fn mask(&self, glyph: u8) -> &[u8] {
141 let len = (self.cell_w * self.cell_h) as usize;
142 let start = glyph as usize * len;
143 self.masks
144 .get(start..start + len)
145 .unwrap_or(&self.masks[..len])
146 }
147}
148
149#[derive(Clone, Copy, Debug)]
150struct Seg {
151 x0: f64,
152 y0: f64,
153 x1: f64,
154 y1: f64,
155}
156
157struct Flattener {
159 segs: Vec<Seg>,
160 ox: f64,
161 baseline: f64,
162 scale: f64,
163 cur: (f64, f64),
164 start: (f64, f64),
165}
166
167impl Flattener {
168 fn map(&self, x: f32, y: f32) -> (f64, f64) {
169 (
170 self.ox + f64::from(x) * self.scale,
171 self.baseline - f64::from(y) * self.scale,
172 )
173 }
174
175 fn push(&mut self, p: (f64, f64)) {
176 if p != self.cur {
177 self.segs.push(Seg {
178 x0: self.cur.0,
179 y0: self.cur.1,
180 x1: p.0,
181 y1: p.1,
182 });
183 }
184 self.cur = p;
185 }
186}
187
188impl OutlinePen for Flattener {
189 fn move_to(&mut self, x: f32, y: f32) {
190 let p = self.map(x, y);
191 self.cur = p;
192 self.start = p;
193 }
194
195 fn line_to(&mut self, x: f32, y: f32) {
196 let p = self.map(x, y);
197 self.push(p);
198 }
199
200 fn quad_to(&mut self, x1: f32, y1: f32, x: f32, y: f32) {
201 let p0 = self.cur;
202 let c = self.map(x1, y1);
203 let p1 = self.map(x, y);
204 for i in 1..=QUAD_STEPS {
205 let t = f64::from(i) / f64::from(QUAD_STEPS);
206 let u = 1.0 - t;
207 let px = u * u * p0.0 + 2.0 * u * t * c.0 + t * t * p1.0;
208 let py = u * u * p0.1 + 2.0 * u * t * c.1 + t * t * p1.1;
209 self.push((px, py));
210 }
211 }
212
213 fn curve_to(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, x: f32, y: f32) {
214 let p0 = self.cur;
215 let c1 = self.map(x1, y1);
216 let c2 = self.map(x2, y2);
217 let p1 = self.map(x, y);
218 for i in 1..=CUBIC_STEPS {
219 let t = f64::from(i) / f64::from(CUBIC_STEPS);
220 let u = 1.0 - t;
221 let (a, b, c, d) = (u * u * u, 3.0 * u * u * t, 3.0 * u * t * t, t * t * t);
222 let px = a * p0.0 + b * c1.0 + c * c2.0 + d * p1.0;
223 let py = a * p0.1 + b * c1.1 + c * c2.1 + d * p1.1;
224 self.push((px, py));
225 }
226 }
227
228 fn close(&mut self) {
229 let s = self.start;
230 self.push(s);
231 }
232}
233
234fn rasterize(segs: &[Seg], w: u32, h: u32, out: &mut [u8]) {
236 let s = SUPERSAMPLE;
237 let mut counts = vec![0u32; (w * h) as usize];
238 let mut xs: Vec<(f64, i32)> = Vec::with_capacity(32);
239 for py in 0..h {
240 for sy in 0..s {
241 let y = f64::from(py) + (f64::from(sy) + 0.5) / f64::from(s);
242 xs.clear();
243 for g in segs {
244 let crosses = (g.y0 <= y && y < g.y1) || (g.y1 <= y && y < g.y0);
245 if crosses {
246 let t = (y - g.y0) / (g.y1 - g.y0);
247 let dir = if g.y1 > g.y0 { 1 } else { -1 };
248 xs.push((g.x0 + t * (g.x1 - g.x0), dir));
249 }
250 }
251 if xs.is_empty() {
252 continue;
253 }
254 xs.sort_by(|a, b| a.0.total_cmp(&b.0).then(a.1.cmp(&b.1)));
255 let mut winding = 0;
256 let mut k = 0;
257 let row = (py * w) as usize;
258 for px in 0..w {
259 for sx in 0..s {
260 let x = f64::from(px) + (f64::from(sx) + 0.5) / f64::from(s);
261 while k < xs.len() && xs[k].0 <= x {
262 winding += xs[k].1;
263 k += 1;
264 }
265 if winding != 0 {
266 counts[row + px as usize] += 1;
267 }
268 }
269 }
270 }
271 }
272 let total = s * s;
273 for (o, &c) in out.iter_mut().zip(&counts) {
274 *o = ((c * 255 + total / 2) / total) as u8;
275 }
276}
277
278#[cfg(test)]
279mod tests {
280 use super::*;
281 use clairlune_scene::glyphs::{EMPTY, id};
282 use clairlune_scene::grid_spec;
283
284 fn ink(atlas: &GlyphAtlas, g: u8) -> u32 {
285 atlas.mask(g).iter().map(|&a| u32::from(a)).sum()
286 }
287
288 #[test]
289 fn glyphs_have_ink_and_space_is_empty() {
290 let atlas = GlyphAtlas::for_grid(&grid_spec(3840, 2160));
291 assert_eq!(ink(&atlas, EMPTY), 0);
292 for g in 1..GLYPHS.len() as u8 {
293 assert!(
294 ink(&atlas, g) > 0,
295 "glyph {:?} is blank",
296 GLYPHS[g as usize]
297 );
298 }
299 assert!(ink(&atlas, id('@')) > ink(&atlas, id('.')));
301 assert!(ink(&atlas, id('#')) > ink(&atlas, id('-')));
302 }
303
304 #[test]
305 fn atlas_is_deterministic() {
306 let spec = grid_spec(640, 360);
307 assert_eq!(GlyphAtlas::for_grid(&spec), GlyphAtlas::for_grid(&spec));
308 }
309}