nannou_draw 0.20.0

A simple and expressive API for drawing 2D and 3D graphics, built on Bevy for nannou - the creative-coding framework.
Documentation
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
397
398
399
400
401
402
403
404
405
//! Text layout and measurement via parley.

use std::borrow::Cow;

use bevy::prelude::*;
use nannou_core::geom;
use parley::Alignment;
use parley::style::{FontFamily, FontFamilyName, StyleProperty, WordBreak};

pub use self::layout::Layout;

pub mod font;
pub mod glyph;
pub mod layout;

/// The type used for scalar values.
pub type Scalar = nannou_core::geom::scalar::Default;

/// The point type used when working with text.
pub type Point = nannou_core::geom::Point2;

/// The type used to specify `FontSize` in font points.
pub type FontSize = u32;

/// Alignment along an axis.
#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, PartialOrd, Ord)]
pub enum Align {
    Start,
    Middle,
    End,
}

/// A type used for referring to typographic alignment of `Text`.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum Justify {
    /// Align text to the start of the bounding `Rect`'s *x* axis.
    Left,
    /// Symmetrically align text along the *y* axis.
    Center,
    /// Align text to the end of the bounding `Rect`'s *x* axis.
    Right,
}

/// The way in which text should wrap around the width.
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum Wrap {
    /// Wrap at the first character that exceeds the width.
    Character,
    /// Wrap at the first word that exceeds the width.
    Whitespace,
}

/// A builder for laying out **Text** immediately.
pub struct Builder<'a> {
    text: Cow<'a, str>,
    layout_builder: layout::Builder,
    text_cx: font::SharedTextCx,
}

/// Laid-out text ready for measurement and glyph extraction.
pub struct Text {
    string: String,
    parley_layout: parley::Layout<Color>,
    layout: Layout,
    rect: geom::Rect,
    // The factor by which the parley layout is scaled relative to `rect`, e.g. the window
    // scale factor when rasterising glyphs at physical pixel resolution. All public
    // measurements are divided by this so that the API always works in logical points.
    scale: f32,
}

impl<'a> Builder<'a> {
    /// Create a new text builder.
    pub fn new(s: &'a str, text_cx: font::SharedTextCx) -> Self {
        Builder {
            text: Cow::Borrowed(s),
            layout_builder: Default::default(),
            text_cx,
        }
    }

    /// Apply the given function to the inner text layout.
    fn map_layout<F>(mut self, map: F) -> Self
    where
        F: FnOnce(layout::Builder) -> layout::Builder,
    {
        self.layout_builder = map(self.layout_builder);
        self
    }

    /// The font size to use for the text.
    pub fn font_size(self, size: FontSize) -> Self {
        self.map_layout(|l| l.font_size(size))
    }

    /// Specify whether or not text should be wrapped around some width and how to do so.
    pub fn line_wrap(self, line_wrap: Option<Wrap>) -> Self {
        self.map_layout(|l| l.line_wrap(line_wrap))
    }

    /// Specify that the **Text** should not wrap lines around the width.
    pub fn no_line_wrap(self) -> Self {
        self.map_layout(|l| l.no_line_wrap())
    }

    /// Line wrap the **Text** at the beginning of the first word that exceeds the width.
    pub fn wrap_by_word(self) -> Self {
        self.map_layout(|l| l.wrap_by_word())
    }

    /// Line wrap the **Text** at the beginning of the first character that exceeds the width.
    pub fn wrap_by_character(self) -> Self {
        self.map_layout(|l| l.wrap_by_character())
    }

    /// Specify the font family used for displaying the text.
    pub fn font_family(self, family: impl Into<String>) -> Self {
        self.map_layout(|l| l.font_family(family))
    }

    /// Describe the end along the *x* axis to which the text should be aligned.
    pub fn justify(self, justify: Justify) -> Self {
        self.map_layout(|l| l.justify(justify))
    }

    /// Align the text to the left of its bounding **Rect**'s *x* axis range.
    pub fn left_justify(self) -> Self {
        self.map_layout(|l| l.left_justify())
    }

    /// Align the text to the middle of its bounding **Rect**'s *x* axis range.
    pub fn center_justify(self) -> Self {
        self.map_layout(|l| l.center_justify())
    }

    /// Align the text to the right of its bounding **Rect**'s *x* axis range.
    pub fn right_justify(self) -> Self {
        self.map_layout(|l| l.right_justify())
    }

    /// Specify how much vertical space should separate each line of text.
    pub fn line_spacing(self, spacing: Scalar) -> Self {
        self.map_layout(|l| l.line_spacing(spacing))
    }

    /// Specify how the whole text should be aligned along the y axis of its bounding rectangle.
    pub fn y_align(self, align: Align) -> Self {
        self.map_layout(|l| l.y_align(align))
    }

    /// Align the top edge of the text with the top edge of its bounding rectangle.
    pub fn align_top(self) -> Self {
        self.map_layout(|l| l.align_top())
    }

    /// Align the middle of the text with the middle of the bounding rect along the y axis.
    pub fn align_middle_y(self) -> Self {
        self.map_layout(|l| l.align_middle_y())
    }

    /// Align the bottom edge of the text with the bottom edge of its bounding rectangle.
    pub fn align_bottom(self) -> Self {
        self.map_layout(|l| l.align_bottom())
    }

    /// Set all the parameters via an existing `Layout`.
    pub fn layout(self, layout: &Layout) -> Self {
        self.map_layout(|l| l.layout(layout))
    }

    /// Build the text layout within the given `rect`.
    pub fn build(self, rect: geom::Rect) -> Text {
        let layout = self.layout_builder.build();
        let mut inner = self.text_cx.0.lock().unwrap();
        Text::layout_with_inner(&mut inner, &self.text, &layout, rect, 1.0)
    }
}

impl Text {
    /// Compute a parley layout using an already-locked inner context.
    pub(crate) fn layout_with_inner(
        inner: &mut font::NannouTextCxInner,
        text: &str,
        layout: &Layout,
        rect: geom::Rect,
        scale: f32,
    ) -> Self {
        let font_size = layout.font_size as f32;

        let mut builder = inner
            .layout
            .ranged_builder(&mut inner.font, text, scale, true);

        builder.push_default(StyleProperty::FontSize(font_size));

        if let Some(ref family) = layout.font_family {
            // `parse` resolves generic names like "monospace"; fall back to treating
            // the whole string as a family name.
            let name = FontFamilyName::parse(family).unwrap_or(FontFamilyName::named(family));
            builder.push_default(StyleProperty::FontFamily(FontFamily::Single(name)));
        }

        if let Some(spacing) = (layout.line_spacing != 0.0).then_some(layout.line_spacing) {
            builder.push_default(StyleProperty::LineHeight(
                parley::style::LineHeight::Absolute(font_size + spacing),
            ));
        }

        if let Some(Wrap::Character) = layout.line_wrap {
            builder.push_default(StyleProperty::WordBreak(WordBreak::BreakAll));
        }

        let mut parley_layout = builder.build(text);

        match layout.line_wrap {
            None => parley_layout.break_all_lines(None),
            Some(Wrap::Whitespace) | Some(Wrap::Character) => {
                parley_layout.break_all_lines(Some(rect.w() * scale));
            }
        }
        let alignment = match layout.justify {
            Justify::Left => Alignment::Start,
            Justify::Center => Alignment::Center,
            Justify::Right => Alignment::End,
        };
        parley_layout.align(alignment, parley::AlignmentOptions::default());

        Text {
            string: text.to_string(),
            parley_layout,
            layout: layout.clone(),
            rect,
            scale,
        }
    }

    /// The layout parameters.
    pub fn layout(&self) -> &Layout {
        &self.layout
    }

    /// The rectangle used to layout the text.
    pub fn layout_rect(&self) -> geom::Rect {
        self.rect
    }

    /// The width of the laid-out text.
    pub fn width(&self) -> Scalar {
        self.parley_layout.width() / self.scale
    }

    /// The height of the laid-out text.
    pub fn height(&self) -> Scalar {
        self.parley_layout.height() / self.scale
    }

    /// The number of lines in the text.
    pub fn num_lines(&self) -> usize {
        self.parley_layout.len()
    }

    /// The bounding box of the text, positioned according to `y_align`.
    pub fn bounding_rect(&self) -> geom::Rect {
        let w = self.width();
        let h = self.height();
        if w == 0.0 && h == 0.0 {
            return geom::Rect::from_w_h(0.0, 0.0);
        }
        let offset = self.position_offset();
        // Convert parley top-down to nannou y-up.
        let x = geom::Range::new(offset.x, offset.x + w);
        let y = geom::Range::new(offset.y - h, offset.y);
        geom::Rect { x, y }
    }

    /// Per-line bounding rects in nannou coordinate space.
    pub fn line_rects(&self) -> Vec<geom::Rect> {
        let offset = self.position_offset();
        let scale = self.scale;
        self.parley_layout
            .lines()
            .map(|line| {
                let metrics = line.metrics();
                let top = offset.y + (metrics.ascent - metrics.baseline) / scale;
                let bottom = offset.y - (metrics.baseline + metrics.descent) / scale;
                let line_x = offset.x + metrics.offset / scale;
                let line_w = (metrics.advance - metrics.trailing_whitespace) / scale;
                let x = geom::Range::new(line_x, line_x + line_w);
                let y = geom::Range::new(bottom, top);
                geom::Rect { x, y }
            })
            .collect()
    }

    /// The text content of each line.
    pub fn lines(&self) -> Vec<&str> {
        self.parley_layout
            .lines()
            .map(|line| {
                let range = line.text_range();
                &self.string[range]
            })
            .collect()
    }

    /// Per-glyph bounding rects (one per glyph cluster).
    pub fn glyphs(&self) -> Vec<geom::Rect> {
        let offset = self.position_offset();
        let scale = self.scale;
        let mut rects = Vec::new();
        for line in self.parley_layout.lines() {
            for item in line.items() {
                let parley::PositionedLayoutItem::GlyphRun(glyph_run) = item else {
                    continue;
                };
                let run_metrics = glyph_run.run().metrics();
                for glyph in glyph_run.positioned_glyphs() {
                    let gx = offset.x + glyph.x / scale;
                    let gy = offset.y - glyph.y / scale;
                    let x = geom::Range::new(gx, gx + glyph.advance / scale);
                    let y = geom::Range::new(
                        gy - run_metrics.descent / scale,
                        gy + run_metrics.ascent / scale,
                    );
                    rects.push(geom::Rect { x, y });
                }
            }
        }
        rects
    }

    /// Path events for every glyph, relative to the center of the layout rect.
    pub fn path_events(&self) -> Vec<lyon::path::PathEvent> {
        glyph::text_path_events(&self.parley_layout, self.position_offset(), self.scale)
    }

    pub(crate) fn parley_layout(&self) -> &parley::Layout<Color> {
        &self.parley_layout
    }

    pub(crate) fn position_offset_value(&self) -> Vec2 {
        self.position_offset()
    }

    /// Offset to convert parley's top-left y-down layout into nannou's
    /// center-origin y-up coordinates, accounting for `y_align`.
    fn position_offset(&self) -> Vec2 {
        let text_h = self.height();
        let rect_h = self.rect.h();
        let rect_w = self.rect.w();
        let y_offset = match self.layout.y_align {
            Align::End => rect_h / 2.0,
            Align::Middle => text_h / 2.0,
            Align::Start => -rect_h / 2.0 + text_h,
        };
        // When line breaking is unbounded, parley aligns lines within the widest line
        // rather than the layout rect, so shift the whole block to restore
        // rect-relative justification.
        let x_offset = match self.layout.line_wrap {
            Some(_) => -rect_w / 2.0,
            None => {
                let align_w = rect_w - self.width();
                let factor = match self.layout.justify {
                    Justify::Left => 0.0,
                    Justify::Center => 0.5,
                    Justify::Right => 1.0,
                };
                -rect_w / 2.0 + align_w * factor
            }
        };
        Vec2::new(x_offset, y_offset)
    }
}

/// Determine the total height of a block of text with the given number of lines, font size and
/// `line_spacing` (the space that separates each line of text).
pub fn height_by_lines(num_lines: usize, font_size: FontSize, line_spacing: Scalar) -> Scalar {
    if num_lines > 0 {
        num_lines as Scalar * font_size as Scalar + (num_lines - 1) as Scalar * line_spacing
    } else {
        0.0
    }
}

/// The position offset required to shift the associated text into the given bounding rectangle.
pub fn position_offset(
    num_lines: usize,
    font_size: FontSize,
    line_spacing: f32,
    bounding_rect: geom::Rect,
    y_align: Align,
) -> Vec2 {
    let x_offset = bounding_rect.x.start;
    let y_offset = {
        let total_text_height = height_by_lines(num_lines, font_size, line_spacing);
        let total_text_y_range = geom::Range::new(0.0, total_text_height);
        let total_text_y = match y_align {
            Align::Start => total_text_y_range.align_start_of(bounding_rect.y),
            Align::Middle => total_text_y_range.align_middle_of(bounding_rect.y),
            Align::End => total_text_y_range.align_end_of(bounding_rect.y),
        };
        total_text_y.end
    };
    geom::vec2(x_offset, y_offset)
}