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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
extern crate arrayvec;
extern crate stb_truetype;
extern crate ndarray;
extern crate linked_hash_map;
mod geometry;
mod rasterizer;
mod support;
pub mod gpu_cache;
use std::sync::Arc;
pub use geometry::{Rect, Point, point, Vector, vector, Line, Curve};
use stb_truetype as tt;
#[derive(Clone)]
pub struct FontCollection<'a>(SharedBytes<'a>);
#[derive(Clone)]
pub struct Font<'a> {
info: tt::FontInfo<SharedBytes<'a>>
}
#[derive(Clone)]
pub enum SharedBytes<'a> {
ByRef(&'a [u8]),
ByArc(Arc<Box<[u8]>>)
}
impl<'a> ::std::ops::Deref for SharedBytes<'a> {
type Target = [u8];
fn deref(&self) -> &[u8] {
match *self {
SharedBytes::ByRef(bytes) => bytes,
SharedBytes::ByArc(ref bytes) => &***bytes
}
}
}
impl<'a> From<&'a [u8]> for SharedBytes<'a> {
fn from(bytes: &'a [u8]) -> SharedBytes<'a> {
SharedBytes::ByRef(bytes)
}
}
impl From<Arc<Box<[u8]>>> for SharedBytes<'static> {
fn from(bytes: Arc<Box<[u8]>>) -> SharedBytes<'static> {
SharedBytes::ByArc(bytes)
}
}
impl From<Box<[u8]>> for SharedBytes<'static> {
fn from(bytes: Box<[u8]>) -> SharedBytes<'static> {
SharedBytes::ByArc(Arc::new(bytes))
}
}
impl From<Vec<u8>> for SharedBytes<'static> {
fn from(bytes: Vec<u8>) -> SharedBytes<'static> {
SharedBytes::ByArc(Arc::new(bytes.into_boxed_slice()))
}
}
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Codepoint(pub u32);
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum CodepointOrGlyphId {
Codepoint(Codepoint),
GlyphId(GlyphId)
}
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct GlyphId(pub u32);
#[derive(Clone)]
pub struct Glyph<'a> {
inner: GlyphInner<'a>
}
#[derive(Clone)]
enum GlyphInner<'a> {
Proxy(&'a Font<'a>, u32),
Shared(Arc<SharedGlyphData>)
}
struct SharedGlyphData {
id: u32,
extents: Option<Rect<i32>>,
scale_for_1_pixel: f32,
unit_h_metrics: HMetrics,
shape: Option<Vec<tt::Vertex>>
}
#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
pub struct HMetrics {
pub advance_width: f32,
pub left_side_bearing: f32
}
#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
pub struct VMetrics {
pub ascent: f32,
pub descent: f32,
pub line_gap: f32
}
#[derive(Clone)]
pub struct ScaledGlyph<'a> {
g: Glyph<'a>,
api_scale: Scale,
scale: Vector<f32>
}
#[derive(Clone)]
pub struct PositionedGlyph<'a> {
sg: ScaledGlyph<'a>,
position: Point<f32>,
bb: Option<Rect<i32>>
}
#[derive(Copy, Clone, PartialEq, PartialOrd, Debug)]
pub struct Scale {
pub x: f32,
pub y: f32
}
impl Scale {
pub fn uniform(s: f32) -> Scale {
Scale { x: s, y: s }
}
}
impl From<char> for Codepoint {
fn from(c: char) -> Codepoint {
Codepoint(c as u32)
}
}
impl From<Codepoint> for CodepointOrGlyphId {
fn from(c: Codepoint) -> CodepointOrGlyphId {
CodepointOrGlyphId::Codepoint(c)
}
}
impl From<GlyphId> for CodepointOrGlyphId {
fn from(g: GlyphId) -> CodepointOrGlyphId {
CodepointOrGlyphId::GlyphId(g)
}
}
impl From<char> for CodepointOrGlyphId {
fn from(c: char) -> CodepointOrGlyphId {
Codepoint(c as u32).into()
}
}
impl<'a> FontCollection<'a> {
pub fn from_bytes<B: Into<SharedBytes<'a>>>(bytes: B) -> FontCollection<'a> {
FontCollection(bytes.into())
}
pub fn into_font(self) -> Option<Font<'a>> {
if tt::is_font(&self.0) && tt::get_font_offset_for_index(&self.0, 1).is_none() {
tt::FontInfo::new(self.0, 0).map(
|info| Font {
info: info
})
} else {
None
}
}
pub fn font_at(&self, i: usize) -> Option<Font> {
tt::get_font_offset_for_index(&self.0, i as i32)
.and_then(|o| tt::FontInfo::new(self.0.clone(), o as usize))
.map(|info| Font { info: info })
}
}
impl<'a> Font<'a> {
pub fn v_metrics(&self, scale: Scale) -> VMetrics {
let vm = self.info.get_v_metrics();
let scale = self.info.scale_for_pixel_height(scale.y);
VMetrics {
ascent: vm.ascent as f32 * scale,
descent: vm.descent as f32 * scale,
line_gap: vm.line_gap as f32 * scale
}
}
pub fn glyph_count(&self) -> usize {
self.info.get_num_glyphs() as usize
}
pub fn glyph<C: Into<CodepointOrGlyphId>>(&self, id: C) -> Option<Glyph> {
let gid = match id.into() {
CodepointOrGlyphId::Codepoint(Codepoint(c)) => self.info.find_glyph_index(c),
CodepointOrGlyphId::GlyphId(GlyphId(gid)) => gid
};
Some(Glyph::new(GlyphInner::Proxy(self, gid)))
}
pub fn glyphs_for<I: Iterator>(&self, itr: I) -> GlyphIter<I> where I::Item: Into<CodepointOrGlyphId> {
GlyphIter {
font: self,
itr: itr
}
}
pub fn layout<'b, 'c>(&'b self, s: &'c str, scale: Scale, start: Point<f32>) -> LayoutIter<'b, 'c> {
LayoutIter {
font: self,
chars: s.chars(),
caret: 0.0,
scale: scale,
start: start,
last_glyph: None
}
}
pub fn pair_kerning<A, B>(&self, scale: Scale, first: A, second: B) -> f32
where A: Into<CodepointOrGlyphId>, B: Into<CodepointOrGlyphId>
{
let (first, second) = (self.glyph(first).unwrap(), self.glyph(second).unwrap());
let factor = self.info.scale_for_pixel_height(scale.y) * (scale.x / scale.y);
let kern = self.info.get_glyph_kern_advance(first.id().0, second.id().0);
factor * kern as f32
}
}
pub struct GlyphIter<'a, I: Iterator> where I::Item: Into<CodepointOrGlyphId> {
font: &'a Font<'a>,
itr: I
}
impl<'a, I: Iterator> Iterator for GlyphIter<'a, I> where I::Item: Into<CodepointOrGlyphId> {
type Item = Glyph<'a>;
fn next(&mut self) -> Option<Glyph<'a>> {
self.itr.next().map(|c| self.font.glyph(c).unwrap())
}
}
pub struct LayoutIter<'a, 'b> {
font: &'a Font<'a>,
chars: ::std::str::Chars<'b>,
caret: f32,
scale: Scale,
start: Point<f32>,
last_glyph: Option<GlyphId>
}
impl<'a, 'b> Iterator for LayoutIter<'a, 'b> {
type Item = PositionedGlyph<'a>;
fn next(&mut self) -> Option<PositionedGlyph<'a>> {
self.chars.next().map(|c| {
let g = self.font.glyph(c).unwrap().scaled(self.scale);
if let Some(last) = self.last_glyph {
self.caret += self.font.pair_kerning(self.scale, last, g.id());
}
let g = g.positioned(point(self.start.x + self.caret, self.start.y));
self.caret += g.sg.h_metrics().advance_width;
self.last_glyph = Some(g.id());
g
})
}
}
impl<'a> Glyph<'a> {
fn new(inner: GlyphInner) -> Glyph {
Glyph {
inner: inner
}
}
pub fn font(&self) -> Option<&Font<'a>> {
match self.inner {
GlyphInner::Proxy(f, _) => Some(f),
GlyphInner::Shared(_) => None
}
}
pub fn id(&self) -> GlyphId {
match self.inner {
GlyphInner::Proxy(_, id) => GlyphId(id),
GlyphInner::Shared(ref data) => GlyphId(data.id),
}
}
pub fn scaled(self, scale: Scale) -> ScaledGlyph<'a> {
let (scale_x, scale_y) = match self.inner {
GlyphInner::Proxy(font, _) => {
let scale_y = font.info.scale_for_pixel_height(scale.y);
let scale_x = scale_y * scale.x / scale.y;
(scale_x, scale_y)
}
GlyphInner::Shared(ref data) => {
let scale_y = data.scale_for_1_pixel * scale.y;
let scale_x = scale_y * scale.x / scale.y;
(scale_x, scale_y)
}
};
ScaledGlyph {
g: self,
api_scale: scale,
scale: vector(scale_x, scale_y)
}
}
pub fn standalone(&self) -> Glyph<'static> {
match self.inner {
GlyphInner::Proxy(font, id) => Glyph::new(GlyphInner::Shared(Arc::new(SharedGlyphData {
id: id,
scale_for_1_pixel: font.info.scale_for_pixel_height(1.0),
unit_h_metrics: {
let hm = font.info.get_glyph_h_metrics(id);
HMetrics {
advance_width: hm.advance_width as f32,
left_side_bearing: hm.left_side_bearing as f32
}
},
extents: font.info.get_glyph_box(id).map(|bb| Rect {
min: point(bb.x0 as i32, -(bb.y1 as i32)),
max: point(bb.x1 as i32, -(bb.y0 as i32))
}),
shape: font.info.get_glyph_shape(id)
}))),
GlyphInner::Shared(ref data) => Glyph::new(GlyphInner::Shared(data.clone()))
}
}
}
#[derive(Copy, Clone, Debug)]
pub enum Segment {
Line(Line),
Curve(Curve)
}
#[derive(Clone, Debug)]
pub struct Contour {
pub segments: Vec<Segment>
}
impl<'a> ScaledGlyph<'a> {
pub fn id(&self) -> GlyphId {
self.g.id()
}
pub fn font(&self) -> Option<&Font<'a>> {
self.g.font()
}
pub fn into_unscaled(self) -> Glyph<'a> {
self.g
}
pub fn unscaled(&self) -> &Glyph<'a> {
&self.g
}
pub fn positioned(self, p: Point<f32>) -> PositionedGlyph<'a> {
let bb = match self.g.inner {
GlyphInner::Proxy(font, id) => {
font.info.get_glyph_bitmap_box_subpixel(id,
self.scale.x, self.scale.y,
p.x, p.y)
.map(|bb| Rect {
min: point(bb.x0, bb.y0),
max: point(bb.x1, bb.y1)
})
}
GlyphInner::Shared(ref data) => {
data.extents.map(|bb| Rect {
min: point((bb.min.x as f32 * self.scale.x + p.x).floor() as i32,
(bb.min.y as f32 * self.scale.y + p.y).floor() as i32),
max: point((bb.max.x as f32 * self.scale.x + p.x).ceil() as i32,
(bb.max.y as f32 * self.scale.y + p.y).ceil() as i32)
})
}
};
PositionedGlyph {
sg: self,
position: p,
bb: bb
}
}
pub fn scale(&self) -> Scale {
self.api_scale
}
pub fn h_metrics(&self) -> HMetrics {
match self.g.inner {
GlyphInner::Proxy(font, id) => {
let hm = font.info.get_glyph_h_metrics(id);
HMetrics {
advance_width: hm.advance_width as f32 * self.scale.x,
left_side_bearing: hm.left_side_bearing as f32 * self.scale.x
}
}
GlyphInner::Shared(ref data) => {
HMetrics {
advance_width: data.unit_h_metrics.advance_width * self.scale.x,
left_side_bearing: data.unit_h_metrics.left_side_bearing * self.scale.y
}
}
}
}
fn shape_with_offset(&self, offset: Point<f32>) -> Option<Vec<Contour>> {
use stb_truetype::VertexType;
use std::mem::replace;
match self.g.inner {
GlyphInner::Proxy(font, id) => font.info.get_glyph_shape(id),
GlyphInner::Shared(ref data) => data.shape.clone()
}.map(|shape| {
let mut result = Vec::new();
let mut current = Vec::new();
let mut last = point(0.0, 0.0);
for v in shape {
let end = point(v.x as f32 * self.scale.x + offset.x,
v.y as f32 * self.scale.y + offset.y);
match v.vertex_type() {
VertexType::MoveTo if result.len() != 0 => {
result.push(Contour {
segments: replace(&mut current, Vec::new())
})
}
VertexType::LineTo => {
current.push(Segment::Line(Line {
p: [last, end]
}))
}
VertexType::CurveTo => {
let control = point(v.cx as f32 * self.scale.x + offset.x,
v.cy as f32 * self.scale.y + offset.y);
current.push(Segment::Curve(Curve {
p: [last, control, end]
}))
}
_ => ()
}
last = end;
}
if current.len() > 0 {
result.push(Contour {
segments: replace(&mut current, Vec::new())
});
}
result
})
}
pub fn shape(&self) -> Option<Vec<Contour>> {
self.shape_with_offset(point(0.0, 0.0))
}
pub fn exact_bounding_box(&self) -> Option<Rect<f32>> {
match self.g.inner {
GlyphInner::Proxy(font, id) => font.info.get_glyph_box(id).map(|bb| {
Rect {
min: point(bb.x0 as f32 * self.scale.x, -bb.y1 as f32 * self.scale.y),
max: point(bb.x1 as f32 * self.scale.x, -bb.y0 as f32 * self.scale.y)
}
}),
GlyphInner::Shared(ref data) => data.extents.map(|bb| Rect {
min: point(bb.min.x as f32 * self.scale.x, bb.min.y as f32 * self.scale.y),
max: point(bb.max.x as f32 * self.scale.x, bb.max.y as f32 * self.scale.y)
})
}
}
pub fn standalone(&self) -> ScaledGlyph<'static> {
ScaledGlyph {
g: self.g.standalone(),
api_scale: self.api_scale,
scale: self.scale
}
}
}
impl<'a> PositionedGlyph<'a> {
pub fn id(&self) -> GlyphId {
self.sg.id()
}
pub fn font(&self) -> Option<&Font<'a>> {
self.sg.font()
}
pub fn unpositioned(&self) -> &ScaledGlyph<'a> {
&self.sg
}
pub fn into_unpositioned(self) -> ScaledGlyph<'a> {
self.sg
}
pub fn pixel_bounding_box(&self) -> Option<Rect<i32>> {
self.bb
}
pub fn shape(&self) -> Option<Vec<Contour>> {
self.sg.shape_with_offset(self.position)
}
pub fn scale(&self) -> Scale {
self.sg.api_scale
}
pub fn position(&self) -> Point<f32> {
self.position
}
pub fn draw<O: FnMut(u32, u32, f32)>(&self, o: O) {
use geometry::{Line, Curve};
use stb_truetype::VertexType;
let shape = match self.sg.g.inner {
GlyphInner::Proxy(font, id) => font.info.get_glyph_shape(id).unwrap_or_else(|| Vec::new()),
GlyphInner::Shared(ref data) => data.shape.clone().unwrap_or_else(|| Vec::new())
};
let bb = if let Some(bb) = self.bb.as_ref() {
bb
} else {
return
};
let offset = vector(bb.min.x as f32, bb.min.y as f32);
let mut lines = Vec::new();
let mut curves = Vec::new();
let mut last = point(0.0, 0.0);
for v in shape {
let end = point(v.x as f32 * self.sg.scale.x + self.position.x,
-v.y as f32 * self.sg.scale.y + self.position.y)
- offset;
match v.vertex_type() {
VertexType::LineTo => {
lines.push(Line {
p: [last, end]
})
}
VertexType::CurveTo => {
let control = point(v.cx as f32 * self.sg.scale.x + self.position.x,
-v.cy as f32 * self.sg.scale.y + self.position.y)
- offset;
curves.push(Curve {
p: [last, control, end]
})
}
VertexType::MoveTo => {}
}
last = end;
}
rasterizer::rasterize(&lines, &curves,
(bb.max.x - bb.min.x) as u32,
(bb.max.y - bb.min.y) as u32,
o);
}
pub fn standalone(&self) -> PositionedGlyph<'static> {
PositionedGlyph {
sg: self.sg.standalone(),
bb: self.bb,
position: self.position
}
}
}