/
gpu_cache.rs
243 lines (222 loc) · 8.87 KB
/
gpu_cache.rs
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
#[macro_use]
extern crate glium;
extern crate rusttype;
extern crate arrayvec;
extern crate unicode_normalization;
use glium::{DisplayBuild, Surface};
use glium::glutin;
use rusttype::{FontCollection, Font, Scale, point, vector, PositionedGlyph};
use rusttype::gpu_cache::{Cache};
use rusttype::Rect;
use std::borrow::Cow;
fn layout_paragraph<'a>(font: &'a Font,
scale: Scale,
width: u32,
text: &str) -> Vec<PositionedGlyph<'a>> {
use unicode_normalization::UnicodeNormalization;
let mut result = Vec::new();
let v_metrics = font.v_metrics(scale);
let advance_height = v_metrics.ascent - v_metrics.descent + v_metrics.line_gap;
let mut caret = point(0.0, v_metrics.ascent);
let mut last_glyph_id = None;
for c in text.nfc() {
if c.is_control() {
match c {
'\r' => {
caret = point(0.0, caret.y + advance_height);
}
'\n' => {},
_ => {}
}
continue;
}
let base_glyph = if let Some(glyph) = font.glyph(c) {
glyph
} else {
continue;
};
if let Some(id) = last_glyph_id.take() {
caret.x += font.pair_kerning(scale, id, base_glyph.id());
}
last_glyph_id = Some(base_glyph.id());
let mut glyph = base_glyph.scaled(scale).positioned(caret);
if let Some(bb) = glyph.pixel_bounding_box() {
if bb.max.x > width as i32 {
caret = point(0.0, caret.y + advance_height);
glyph = glyph.into_unpositioned().positioned(caret);
last_glyph_id = None;
}
}
caret.x += glyph.unpositioned().h_metrics().advance_width;
result.push(glyph);
}
result
}
fn main() {
let font_data = include_bytes!("Arial Unicode.ttf");
let font = FontCollection::from_bytes(font_data as &[u8]).into_font().unwrap();
let display = glutin::WindowBuilder::new()
.with_vsync()
.with_dimensions(512, 512)
.with_title("RustType GPU cache example".into())
.with_srgb(Some(true))
.build_glium()
.unwrap();
let dpi_factor = display.get_window().unwrap().hidpi_factor();
let (cache_width, cache_height) = (512 * dpi_factor as u32, 512 * dpi_factor as u32);
let mut cache = Cache::new(cache_width, cache_height, 0.1, 0.1);
let program = program!(
&display,
140 => {
vertex: "
#version 140
in vec2 position;
in vec2 tex_coords;
in vec4 colour;
out vec2 v_tex_coords;
out vec4 v_colour;
void main() {
gl_Position = vec4(position, 0.0, 1.0);
v_tex_coords = tex_coords;
v_colour = colour;
}
",
fragment: "
#version 140
uniform sampler2D tex;
in vec2 v_tex_coords;
in vec4 v_colour;
out vec4 f_colour;
void main() {
f_colour = v_colour * vec4(1.0, 1.0, 1.0, texture(tex, v_tex_coords).r);
}
"
}).unwrap();
let cache_tex = glium::texture::Texture2d::with_format(
&display,
glium::texture::RawImage2d {
data: Cow::Owned(vec![128u8; cache_width as usize * cache_height as usize]),
width: cache_width,
height: cache_height,
format: glium::texture::ClientFormat::U8
},
glium::texture::UncompressedFloatFormat::U8,
glium::texture::MipmapsOption::NoMipmap).unwrap();
let mut text: String = "A japanese poem:\r
\r
色は匂へど散りぬるを我が世誰ぞ常ならむ有為の奥山今日越えて浅き夢見じ酔ひもせず\r
\r
Feel free to type out some text, and delete it with Backspace. You can also try resizing this window."
.into();
'main: loop {
let width = display.get_window().unwrap().get_inner_size_pixels().unwrap().0;
let glyphs = layout_paragraph(&font, Scale::uniform(24.0 * dpi_factor), width, &text);
for glyph in &glyphs {
cache.queue_glyph(0, glyph.clone());
}
cache.cache_queued(|rect, data| {
cache_tex.main_level().write(glium::Rect {
left: rect.min.x,
bottom: rect.min.y,
width: rect.width(),
height: rect.height()
}, glium::texture::RawImage2d {
data: Cow::Borrowed(data),
width: rect.width(),
height: rect.height(),
format: glium::texture::ClientFormat::U8
});
}).unwrap();
let uniforms = uniform! {
tex: cache_tex.sampled().magnify_filter(glium::uniforms::MagnifySamplerFilter::Nearest)
};
let vertex_buffer = {
#[derive(Copy, Clone)]
struct Vertex {
position: [f32; 2],
tex_coords: [f32; 2],
colour: [f32; 4]
}
implement_vertex!(Vertex, position, tex_coords, colour);
let colour = [0.0, 0.0, 0.0, 1.0];
let (screen_width, screen_height) = {
let (w, h) = display.get_framebuffer_dimensions();
(w as f32, h as f32)
};
let origin = point(0.0, 0.0);
let vertices: Vec<Vertex> = glyphs.iter().flat_map(|g| {
if let Ok(Some((uv_rect, screen_rect))) = cache.rect_for(0, g) {
let gl_rect = Rect {
min: origin
+ (vector(screen_rect.min.x as f32 / screen_width - 0.5,
1.0 - screen_rect.min.y as f32 / screen_height - 0.5)) * 2.0,
max: origin
+ (vector(screen_rect.max.x as f32 / screen_width - 0.5,
1.0 - screen_rect.max.y as f32 / screen_height - 0.5)) * 2.0
};
arrayvec::ArrayVec::<[Vertex; 6]>::from([
Vertex {
position: [gl_rect.min.x, gl_rect.max.y],
tex_coords: [uv_rect.min.x, uv_rect.max.y],
colour: colour
},
Vertex {
position: [gl_rect.min.x, gl_rect.min.y],
tex_coords: [uv_rect.min.x, uv_rect.min.y],
colour: colour
},
Vertex {
position: [gl_rect.max.x, gl_rect.min.y],
tex_coords: [uv_rect.max.x, uv_rect.min.y],
colour: colour
},
Vertex {
position: [gl_rect.max.x, gl_rect.min.y],
tex_coords: [uv_rect.max.x, uv_rect.min.y],
colour: colour },
Vertex {
position: [gl_rect.max.x, gl_rect.max.y],
tex_coords: [uv_rect.max.x, uv_rect.max.y],
colour: colour
},
Vertex {
position: [gl_rect.min.x, gl_rect.max.y],
tex_coords: [uv_rect.min.x, uv_rect.max.y],
colour: colour
}])
} else {
arrayvec::ArrayVec::new()
}
}).collect();
glium::VertexBuffer::new(
&display,
&vertices).unwrap()
};
let mut target = display.draw();
target.clear_color(1.0, 1.0, 1.0, 0.0);
target.draw(&vertex_buffer,
glium::index::NoIndices(glium::index::PrimitiveType::TrianglesList),
&program, &uniforms,
&glium::DrawParameters {
blend: glium::Blend::alpha_blending(),
..Default::default()
}).unwrap();
target.finish().unwrap();
for event in display.poll_events() {
match event {
glutin::Event::KeyboardInput(_, _, Some(glutin::VirtualKeyCode::Escape)) |
glutin::Event::Closed => break 'main,
glutin::Event::ReceivedCharacter(c) => if c != '\u{7f}' {
text.push(c);
},
glutin::Event::KeyboardInput(
glutin::ElementState::Pressed,
_,
Some(glutin::VirtualKeyCode::Back)) => {
text.pop();
},
_ => {}
}
}
}
}