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
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
//! A fast text renderer for [`luminance`], powered by [`glyph_brush`].
//!
//! Initially forked and modified from [glow_glyph](https://github.com/hecrj/glow_glyph) by [hecrj](https://github.com/hecrj). Many thanks to [hecrj](https://github.com/hecrj)!
//!
//! [`luminance`]: https://github.com/phaazon/luminance-rs
//! [`glyph_brush`]: https://github.com/alexheretic/glyph-brush/tree/master/glyph-brush
#![deny(unused_results)]
mod builder;
mod pipeline;
mod region;

pub use region::Region;

use luminance::{
    backend,
    context::GraphicsContext,
    pipeline::PipelineError,
    pipeline::{Pipeline as LuminancePipeline, TextureBinding},
    pixel::NormR8UI,
    pixel::NormUnsigned,
    shader::types::Mat44,
    shading_gate::ShadingGate,
    tess::Interleaved,
    texture::Dim2,
};

use pipeline::Pipeline;

pub use builder::GlyphBrushBuilder;
pub use glyph_brush::ab_glyph;
pub use glyph_brush::{
    BuiltInLineBreaker, Extra, FontId, GlyphCruncher, GlyphPositioner, GlyphVertex,
    HorizontalAlign, Layout, LineBreak, LineBreaker, Section, SectionGeometry, SectionGlyph,
    SectionGlyphIter, SectionText, Text, VerticalAlign,
};
pub use pipeline::{Instance, LeftTop, RightBottom, TexLeftTop, TexRightBottom, VertexColor};

use ab_glyph::{Font, FontArc, Rect};

use core::hash::BuildHasher;
use std::borrow::Cow;

use glyph_brush::{BrushAction, BrushError, DefaultSectionHasher};
use log::{log_enabled, warn};

pub trait GlyphBrushBackend:
    backend::pipeline::PipelineTexture<Dim2, NormR8UI>
    + backend::texture::Texture<Dim2, NormR8UI>
    + backend::shader::Shader
    + for<'a> backend::shader::Uniformable<'a, Mat44<f32>, Target = Mat44<f32>>
    + for<'a> backend::shader::Uniformable<
        'a,
        TextureBinding<Dim2, NormUnsigned>,
        Target = TextureBinding<Dim2, NormUnsigned>,
    > + backend::tess::Tess<(), u32, Instance, Interleaved>
    + backend::pipeline::PipelineBase
    + backend::render_gate::RenderGate
    + backend::tess_gate::TessGate<(), u32, Instance, Interleaved>
{
}

impl<B: ?Sized> GlyphBrushBackend for B where
    B: backend::pipeline::PipelineTexture<Dim2, NormR8UI>
        + backend::texture::Texture<Dim2, NormR8UI>
        + backend::shader::Shader
        + for<'a> backend::shader::Uniformable<'a, Mat44<f32>, Target = Mat44<f32>>
        + for<'a> backend::shader::Uniformable<
            'a,
            TextureBinding<Dim2, NormUnsigned>,
            Target = TextureBinding<Dim2, NormUnsigned>,
        > + backend::tess::Tess<(), u32, Instance, Interleaved>
        + backend::pipeline::PipelineBase
        + backend::render_gate::RenderGate
        + backend::tess_gate::TessGate<(), u32, Instance, Interleaved>
{
}

/// Object allowing glyph drawing, containing cache state. Manages glyph positioning cacheing,
/// glyph draw caching & efficient GPU texture cache updating and re-sizing on demand.
///
/// Build using a [`GlyphBrushBuilder`](struct.GlyphBrushBuilder.html).
pub struct GlyphBrush<B, F = FontArc, H = DefaultSectionHasher>
where
    B: GlyphBrushBackend,
{
    pipeline: Pipeline<B>,
    glyph_brush: glyph_brush::GlyphBrush<Instance, Extra, F, H>,
}

impl<B, F: Font, H: BuildHasher> GlyphBrush<B, F, H>
where
    B: GlyphBrushBackend,
{
    /// Queues a section/layout to be drawn by the next call of
    /// [`draw_queued`](struct.GlyphBrush.html#method.draw_queued). Can be
    /// called multiple times to queue multiple sections for drawing.
    ///
    /// Benefits from caching, see [caching behaviour](#caching-behaviour).
    #[inline]
    pub fn queue<'a, S>(&mut self, section: S)
    where
        S: Into<Cow<'a, Section<'a>>>,
    {
        self.glyph_brush.queue(section)
    }

    /// Queues a section/layout to be drawn by the next call of
    /// [`draw_queued`](struct.GlyphBrush.html#method.draw_queued). Can be
    /// called multiple times to queue multiple sections for drawing.
    ///
    /// Used to provide custom `GlyphPositioner` logic, if using built-in
    /// [`Layout`](enum.Layout.html) simply use
    /// [`queue`](struct.GlyphBrush.html#method.queue)
    ///
    /// Benefits from caching, see [caching behaviour](#caching-behaviour).
    #[inline]
    pub fn queue_custom_layout<'a, S, G>(&mut self, section: S, custom_layout: &G)
    where
        G: GlyphPositioner,
        S: Into<Cow<'a, Section<'a>>>,
    {
        self.glyph_brush.queue_custom_layout(section, custom_layout)
    }

    /// Queues pre-positioned glyphs to be processed by the next call of
    /// [`draw_queued`](struct.GlyphBrush.html#method.draw_queued). Can be
    /// called multiple times.
    #[inline]
    pub fn queue_pre_positioned(
        &mut self,
        glyphs: Vec<SectionGlyph>,
        extra: Vec<Extra>,
        bounds: Rect,
    ) {
        self.glyph_brush.queue_pre_positioned(glyphs, extra, bounds)
    }

    /// Retains the section in the cache as if it had been used in the last
    /// draw-frame.
    ///
    /// Should not be necessary unless using multiple draws per frame with
    /// distinct transforms, see [caching behaviour](#caching-behaviour).
    #[inline]
    pub fn keep_cached_custom_layout<'a, S, G>(&mut self, section: S, custom_layout: &G)
    where
        S: Into<Cow<'a, Section<'a>>>,
        G: GlyphPositioner,
    {
        self.glyph_brush
            .keep_cached_custom_layout(section, custom_layout)
    }

    /// Retains the section in the cache as if it had been used in the last
    /// draw-frame.
    ///
    /// Should not be necessary unless using multiple draws per frame with
    /// distinct transforms, see [caching behaviour](#caching-behaviour).
    #[inline]
    pub fn keep_cached<'a, S>(&mut self, section: S)
    where
        S: Into<Cow<'a, Section<'a>>>,
    {
        self.glyph_brush.keep_cached(section)
    }

    /// Returns the available fonts.
    ///
    /// The `FontId` corresponds to the index of the font data.
    #[inline]
    pub fn fonts(&self) -> &[F] {
        self.glyph_brush.fonts()
    }

    /// Adds an additional font to the one(s) initially added on build.
    ///
    /// Returns a new [`FontId`](struct.FontId.html) to reference this font.
    pub fn add_font(&mut self, font: F) -> FontId {
        self.glyph_brush.add_font(font)
    }
}

impl<B, F: Font + Sync, H: BuildHasher> GlyphBrush<B, F, H>
where
    B: GlyphBrushBackend,
{
    /// Draws all queued sections onto a render target.
    /// See [`queue`](struct.GlyphBrush.html#method.queue).
    ///
    /// Trims the cache, see [caching behaviour](#caching-behaviour).
    ///
    /// # Panics
    /// Panics if the provided `target` has a texture format that does not match
    /// the `render_format` provided on creation of the `GlyphBrush`.
    #[inline]
    pub fn draw_queued<'a>(
        &mut self,
        pipeline: &mut LuminancePipeline<'a, B>,
        shading_gate: &mut ShadingGate<'a, B>,
        target_width: u32,
        target_height: u32,
    ) -> Result<(), PipelineError> {
        self.draw_queued_with_transform(
            pipeline,
            shading_gate,
            orthographic_projection(target_width, target_height),
        )
    }

    /// Draws all queued sections onto a render target, applying a position
    /// transform (e.g. a projection).
    /// See [`queue`](struct.GlyphBrush.html#method.queue).
    ///
    /// Trims the cache, see [caching behaviour](#caching-behaviour).
    ///
    /// # Panics
    /// Panics if the provided `target` has a texture format that does not match
    /// the `render_format` provided on creation of the `GlyphBrush`.
    #[inline]
    pub fn draw_queued_with_transform<'a>(
        &mut self,
        pipeline: &mut LuminancePipeline<'a, B>,
        shading_gate: &mut ShadingGate<'a, B>,
        transform: [f32; 16],
    ) -> Result<(), PipelineError> {
        //self.process_queued(context);
        self.pipeline.draw(pipeline, shading_gate, transform, None)
    }

    /// Draws all queued sections onto a render target, applying a position
    /// transform (e.g. a projection) and a scissoring region.
    /// See [`queue`](struct.GlyphBrush.html#method.queue).
    ///
    /// Trims the cache, see [caching behaviour](#caching-behaviour).
    ///
    /// # Panics
    /// Panics if the provided `target` has a texture format that does not match
    /// the `render_format` provided on creation of the `GlyphBrush`.
    #[inline]
    pub fn draw_queued_with_transform_and_scissoring<'a>(
        &mut self,
        pipeline: &mut LuminancePipeline<'a, B>,
        shading_gate: &mut ShadingGate<'a, B>,
        transform: [f32; 16],
        region: Region,
    ) -> Result<(), PipelineError> {
        //self.process_queued(context);
        self.pipeline
            .draw(pipeline, shading_gate, transform, Some(region))
    }

    pub fn process_queued<C>(&mut self, context: &mut C)
    where
        C: GraphicsContext<Backend = B>,
    {
        self.process_queued_with_vertex_constructor(context, Instance::from_vertex)
    }

    pub fn process_queued_with_vertex_constructor<C>(
        &mut self,
        context: &mut C,
        into_vertex: impl Fn(GlyphVertex) -> Instance,
    ) where
        C: GraphicsContext<Backend = B>,
    {
        let pipeline = &mut self.pipeline;

        let mut brush_action;

        loop {
            brush_action = self.glyph_brush.process_queued(
                |rect, tex_data| {
                    let offset = [rect.min[0] as u16, rect.min[1] as u16];
                    let size = [rect.width() as u16, rect.height() as u16];

                    pipeline.update_cache(offset, size, tex_data);
                },
                &into_vertex,
            );

            match brush_action {
                Ok(_) => break,
                Err(BrushError::TextureTooSmall { suggested }) => {
                    // TODO: Obtain max texture dimensions
                    let max_image_dimension = 2048;

                    let (new_width, new_height) = if (suggested.0 > max_image_dimension
                        || suggested.1 > max_image_dimension)
                        && (self.glyph_brush.texture_dimensions().0 < max_image_dimension
                            || self.glyph_brush.texture_dimensions().1 < max_image_dimension)
                    {
                        (max_image_dimension, max_image_dimension)
                    } else {
                        suggested
                    };

                    if log_enabled!(log::Level::Warn) {
                        warn!(
                            "Increasing glyph texture size {old:?} -> {new:?}. \
                             Consider building with `.initial_cache_size({new:?})` to avoid \
                             resizing",
                            old = self.glyph_brush.texture_dimensions(),
                            new = (new_width, new_height),
                        );
                    }

                    pipeline.increase_cache_size(context, new_width, new_height);
                    self.glyph_brush.resize_texture(new_width, new_height);
                }
            }
        }

        match brush_action.unwrap() {
            BrushAction::Draw(verts) => {
                self.pipeline.upload(context, &verts);
            }
            BrushAction::ReDraw => {}
        };
    }
}

impl<B, F: Font, H: BuildHasher> GlyphBrush<B, F, H>
where
    B: GlyphBrushBackend,
{
    fn new<C>(context: &mut C, raw_builder: glyph_brush::GlyphBrushBuilder<F, H>) -> Self
    where
        C: GraphicsContext<Backend = B>,
    {
        let glyph_brush = raw_builder.build();
        let (cache_width, cache_height) = glyph_brush.texture_dimensions();

        GlyphBrush {
            pipeline: Pipeline::new(context, cache_width, cache_height),
            glyph_brush,
        }
    }
}

/// Helper function to generate a generate a transform matrix.
#[rustfmt::skip]
pub fn orthographic_projection(width: u32, height: u32) -> [f32; 16] {
    [
        2.0 / width as f32, 0.0, 0.0, 0.0,
        0.0, -2.0 / height as f32, 0.0, 0.0,
        0.0, 0.0, 1.0, 0.0,
        -1.0, 1.0, 0.0, 1.0,
    ]
}

impl<B, F: Font, H: BuildHasher> GlyphCruncher<F> for GlyphBrush<B, F, H>
where
    B: GlyphBrushBackend,
{
    #[inline]
    fn glyphs_custom_layout<'a, 'b, S, L>(
        &'b mut self,
        section: S,
        custom_layout: &L,
    ) -> SectionGlyphIter<'b>
    where
        L: GlyphPositioner + std::hash::Hash,
        S: Into<Cow<'a, Section<'a>>>,
    {
        self.glyph_brush
            .glyphs_custom_layout(section, custom_layout)
    }

    #[inline]
    fn glyph_bounds_custom_layout<'a, S, L>(
        &mut self,
        section: S,
        custom_layout: &L,
    ) -> Option<Rect>
    where
        L: GlyphPositioner + std::hash::Hash,
        S: Into<Cow<'a, Section<'a>>>,
    {
        self.glyph_brush
            .glyph_bounds_custom_layout(section, custom_layout)
    }

    #[inline]
    fn fonts(&self) -> &[F] {
        self.glyph_brush.fonts()
    }
}

impl<B, F, H> std::fmt::Debug for GlyphBrush<B, F, H>
where
    B: GlyphBrushBackend,
{
    #[inline]
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "GlyphBrush")
    }
}