1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
use crate::context::{ImageId, TextMetrics};
use crate::renderer::TextureType;
use crate::{Align, Bounds, Extent, ImageFlags, Renderer};
use bitflags::_core::borrow::Borrow;
use rusttype::gpu_cache::Cache;
use rusttype::{Font, Glyph, Point, PositionedGlyph, Scale};
use slab::Slab;
use std::collections::HashMap;

const TEX_WIDTH: usize = 1024;
const TEX_HEIGHT: usize = 1024;

pub type FontId = usize;

#[derive(Debug)]
pub struct LayoutChar {
    id: FontId,
    pub x: f32,
    pub next_x: f32,
    pub c: char,
    pub idx: usize,
    glyph: PositionedGlyph<'static>,
    pub uv: Bounds,
    pub bounds: Bounds,
}

struct FontData {
    font: Font<'static>,
    fallback_fonts: Vec<FontId>,
}

pub struct Fonts {
    fonts: Slab<FontData>,
    fonts_by_name: HashMap<String, FontId>,
    cache: Cache<'static>,
    pub(crate) img: ImageId,
}

impl Fonts {
    pub fn new<R: Renderer>(renderer: &mut R) -> anyhow::Result<Fonts> {
        Ok(Fonts {
            fonts: Default::default(),
            fonts_by_name: Default::default(),
            img: renderer.create_texture(
                TextureType::Alpha,
                TEX_WIDTH,
                TEX_HEIGHT,
                ImageFlags::empty(),
                None,
            )?,
            cache: Cache::builder()
                .multithread(true)
                .dimensions(TEX_WIDTH as u32, TEX_HEIGHT as u32)
                .build(),
        })
    }

    pub fn add_font<N: Into<String>, D: Into<Vec<u8>>>(
        &mut self,
        name: N,
        data: D,
    ) -> anyhow::Result<FontId> {
        let font = Font::<'static>::from_bytes(data.into())?;
        let fd = FontData {
            font,
            fallback_fonts: Default::default(),
        };
        let id = self.fonts.insert(fd);
        self.fonts_by_name.insert(name.into(), id);
        Ok(id)
    }

    pub fn find<N: Borrow<str>>(&self, name: N) -> Option<FontId> {
        self.fonts_by_name.get(name.borrow()).map(ToOwned::to_owned)
    }

    pub fn add_fallback(&mut self, base: FontId, fallback: FontId) {
        if let Some(fd) = self.fonts.get_mut(base) {
            fd.fallback_fonts.push(fallback);
        }
    }

    fn glyph(&self, id: FontId, c: char) -> Option<(FontId, Glyph<'static>)> {
        if let Some(fd) = self.fonts.get(id) {
            let glyph = fd.font.glyph(c);
            if glyph.id().0 != 0 {
                Some((id, glyph))
            } else {
                for id in &fd.fallback_fonts {
                    if let Some(fd) = self.fonts.get(*id) {
                        let glyph = fd.font.glyph(c);
                        if glyph.id().0 != 0 {
                            return Some((*id, glyph));
                        }
                    }
                }
                None
            }
        } else {
            None
        }
    }

    fn render_texture<R: Renderer>(&mut self, renderer: &mut R) -> anyhow::Result<()> {
        let img = self.img.clone();
        self.cache.cache_queued(move |rect, data| {
            renderer
                .update_texture(
                    img.clone(),
                    rect.min.x as usize,
                    rect.min.y as usize,
                    (rect.max.x - rect.min.x) as usize,
                    (rect.max.y - rect.min.y) as usize,
                    data,
                )
                .unwrap();
        })?;
        Ok(())
    }

    pub fn text_metrics(&self, id: FontId, size: f32) -> TextMetrics {
        if let Some(fd) = self.fonts.get(id) {
            let scale = Scale::uniform(size);
            let v_metrics = fd.font.v_metrics(scale);
            TextMetrics {
                ascender: v_metrics.descent,
                descender: v_metrics.descent,
                line_gap: v_metrics.line_gap,
            }
        } else {
            TextMetrics {
                ascender: 0.0,
                descender: 0.0,
                line_gap: 0.0,
            }
        }
    }

    pub fn text_size(&self, text: &str, id: FontId, size: f32, spacing: f32) -> Extent {
        if let Some(fd) = self.fonts.get(id) {
            let scale = Scale::uniform(size);
            let v_metrics = fd.font.v_metrics(scale);
            let mut extent = Extent::new(
                0.0,
                v_metrics.ascent - v_metrics.descent + v_metrics.line_gap,
            );
            let mut last_glyph = None;
            let mut char_count = 0;

            for c in text.chars() {
                if let Some((_, glyph)) = self.glyph(id, c) {
                    let glyph = glyph.scaled(scale);
                    let h_metrics = glyph.h_metrics();
                    extent.width += h_metrics.advance_width;

                    if let Some(last_glyph) = last_glyph {
                        extent.width += fd.font.pair_kerning(scale, last_glyph, glyph.id());
                    }

                    last_glyph = Some(glyph.id());
                    char_count += 1;
                }
            }

            if char_count >= 2 {
                extent.width += spacing * (char_count - 1) as f32;
            }

            extent
        } else {
            Default::default()
        }
    }

    pub fn layout_text<R: Renderer>(
        &mut self,
        renderer: &mut R,
        text: &str,
        id: FontId,
        position: crate::Point,
        size: f32,
        align: Align,
        spacing: f32,
        cache: bool,
        result: &mut Vec<LayoutChar>,
    ) -> anyhow::Result<()> {
        result.clear();

        if let Some(fd) = self.fonts.get(id) {
            let mut offset = Point { x: 0.0, y: 0.0 };
            let scale = Scale::uniform(size);
            let v_metrics = fd.font.v_metrics(scale);

            let sz = if align.contains(Align::CENTER)
                || align.contains(Align::RIGHT)
                || align.contains(Align::MIDDLE)
            {
                self.text_size(text, id, size, spacing)
            } else {
                Extent::new(0.0, 0.0)
            };

            if align.contains(Align::CENTER) {
                offset.x -= sz.width / 2.0;
            } else if align.contains(Align::RIGHT) {
                offset.x -= sz.width;
            }

            if align.contains(Align::MIDDLE) {
                offset.y = v_metrics.descent + sz.height / 2.0;
            } else if align.contains(Align::BOTTOM) {
                offset.y = v_metrics.descent;
            } else if align.contains(Align::TOP) {
                offset.y = v_metrics.ascent;
            }

            let mut position = Point {
                x: position.x + offset.x,
                y: position.y + offset.y,
            };
            let mut last_glyph = None;

            for (idx, c) in text.chars().enumerate() {
                if let Some((id, glyph)) = self.glyph(id, c) {
                    let g = glyph.scaled(scale);
                    let h_metrics = g.h_metrics();

                    let glyph = g.positioned(Point {
                        x: position.x,
                        y: position.y,
                    });

                    let mut next_x = position.x + h_metrics.advance_width;
                    if let Some(last_glyph) = last_glyph {
                        next_x += fd.font.pair_kerning(scale, last_glyph, glyph.id());
                    }

                    if let Some(bb) = glyph.pixel_bounding_box() {
                        self.cache.queue_glyph(id, glyph.clone());

                        result.push(LayoutChar {
                            id,
                            idx,
                            c,
                            x: position.x,
                            next_x,
                            glyph: glyph.clone(),
                            uv: Default::default(),
                            bounds: Bounds {
                                min: (bb.min.x, bb.min.y).into(),
                                max: (bb.max.x, bb.max.y).into(),
                            },
                        });
                    }

                    position.x = next_x;
                    last_glyph = Some(glyph.id());
                }
            }

            if cache {
                self.render_texture(renderer)?;

                for lc in result {
                    if let Ok(Some((uv, _))) = self.cache.rect_for(lc.id, &lc.glyph) {
                        lc.uv = Bounds {
                            min: crate::Point {
                                x: uv.min.x,
                                y: uv.min.y,
                            },
                            max: crate::Point {
                                x: uv.max.x,
                                y: uv.max.y,
                            },
                        };
                    }
                }
            }
        }

        Ok(())
    }
}