/
main.rs
219 lines (182 loc) · 8.05 KB
/
main.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
extern crate core;
use std::collections::HashMap;
use std::default::Default;
use glium::{Blend, DrawParameters, implement_vertex, program, Surface, uniform};
use glium::index::{NoIndices, PrimitiveType};
use glutin::dpi::PhysicalSize;
use glam::Mat4;
use glutin::event::MouseScrollDelta;
use artery_font::{ArteryFont, CodepointType, ImageType, PixelFormat, Rect};
#[derive(Debug, Copy, Clone)]
struct Vertex {
position: [f32; 2],
tex_coord: [f32; 2],
}
implement_vertex!(Vertex, position, tex_coord);
#[derive(Debug, Copy, Clone)]
struct Quad {
plane_bounds: Rect,
atlas_bounds: Rect
}
impl Quad {
fn vertices(&self, x_offset: f32, y_offset: f32) -> impl Iterator<Item=Vertex> {
[
Vertex { position: [x_offset + self.plane_bounds.left , y_offset + self.plane_bounds.bottom], tex_coord: [self.atlas_bounds.left , self.atlas_bounds.bottom] },
Vertex { position: [x_offset + self.plane_bounds.right, y_offset + self.plane_bounds.bottom], tex_coord: [self.atlas_bounds.right, self.atlas_bounds.bottom] },
Vertex { position: [x_offset + self.plane_bounds.left , y_offset + self.plane_bounds.top ], tex_coord: [self.atlas_bounds.left , self.atlas_bounds.top ] },
Vertex { position: [x_offset + self.plane_bounds.left , y_offset + self.plane_bounds.top ], tex_coord: [self.atlas_bounds.left , self.atlas_bounds.top ] },
Vertex { position: [x_offset + self.plane_bounds.right, y_offset + self.plane_bounds.bottom], tex_coord: [self.atlas_bounds.right, self.atlas_bounds.bottom] },
Vertex { position: [x_offset + self.plane_bounds.right, y_offset + self.plane_bounds.top ], tex_coord: [self.atlas_bounds.right, self.atlas_bounds.top ] },
].into_iter()
}
}
#[derive(Debug, Copy, Clone)]
struct Glyph {
advance: f32,
quad: Option<Quad>
}
impl Glyph {
fn vertices(&self, x_offset: f32, y_offset: f32) -> impl Iterator<Item=Vertex> + '_ {
self.quad.iter().flat_map(move |q|q.vertices(x_offset, y_offset))
}
}
fn main() {
let event_loop = glutin::event_loop::EventLoop::new();
let wb = glutin::window::WindowBuilder::new()
.with_inner_size(PhysicalSize::new(1280.0, 720.0))
.with_resizable(false);
let cb = glutin::ContextBuilder::new();
let display = glium::Display::new(wb, cb, &event_loop).unwrap();
let (opengl_texture, glyphs, line_height, px_range) = {
let arfont = ArteryFont::read(&include_bytes!("../data/test.arfont")[..]).unwrap();
let image = arfont.images.first().unwrap();
let variant = arfont.variants.first().unwrap();
assert_eq!(variant.image_type, ImageType::Msdf);
assert_eq!(variant.codepoint_type, CodepointType::Unicode);
let line_height = variant.metrics.line_height;
let pxrange = variant.metrics.distance_range / variant.metrics.font_size;
let mut glyphs = HashMap::<char, Glyph>::new();
for glyph in &variant.glyphs {
let unicode = std::char::from_u32(glyph.codepoint).unwrap();
let advance = glyph.advance.horizontal;
assert_eq!(glyph.advance.vertical, 0.0, "character: {}", unicode);
assert_eq!(glyph.image, 0);
glyphs.insert(unicode, Glyph {
advance,
quad: match glyph.is_drawable() {
true => Some(Quad {
plane_bounds: glyph.plane_bounds,
atlas_bounds: glyph.image_bounds.scaled(1.0 / image.width as f32, 1.0 / image.height as f32)
}),
false => None
}
});
}
assert_eq!(image.channels, 3);
assert_eq!(image.pixel_format, PixelFormat::Unsigned8);
let image = glium::texture::RawImage2d::from_raw_rgb(image.data.clone(), (image.width, image.height));
let opengl_texture = glium::texture::Texture2d::new(&display, image).unwrap();
(opengl_texture, glyphs, line_height, pxrange)
};
let text = "Hello World!\nThis an example for text rendering\nusing msdf fonts";
// building the vertex buffer, which contains all the vertices that we will draw
let vertex_buffer = {
let mut vertices = Vec::new();
let mut x;
let mut y = 2.2;
for line in text.lines() {
x = 0.2;
for glyph in line.chars().map(|c|glyphs[&c]) {
for v in glyph.vertices(x, y) {
vertices.push(v);
}
x += glyph.advance;
}
y -= line_height * 0.55;
}
glium::VertexBuffer::new(&display,
vertices.as_slice()
).unwrap()
};
// compiling shaders and linking them together
let program = program!(&display,
450 => {
vertex: "
#version 450 core
in vec2 position;
in vec2 tex_coord;
out vec2 v_tex_coords;
uniform mat4 matrix;
void main() {
gl_Position = matrix * vec4(position, 0.0, 1.0);
v_tex_coords = tex_coord;
}
",
fragment: "
#version 450 core
in vec2 v_tex_coords;
out vec4 f_color;
uniform sampler2D tex;
float median(float r, float g, float b) {
return max(min(r, g), min(max(r, g), b));
}
uniform float screenPxRange;
void main() {
vec3 msd = texture(tex, v_tex_coords).rgb;
float sd = median(msd.r, msd.g, msd.b);
float screenPxDistance = screenPxRange * (sd - 0.5);
float opacity = clamp(screenPxDistance + 0.5, 0.0, 1.0);
f_color = vec4(1, 1, 1, opacity);
}
"
}
).unwrap();
let mut scale = 10.0;
// Here we draw the black background and triangle to the screen using the previously
// initialised resources.
//
// In this case we use a closure for simplicity, however keep in mind that most serious
// applications should probably use a function that takes the resources as an argument.
let draw = move |scale| {
// building the uniforms
let uniforms = uniform! {
matrix: Mat4::orthographic_rh(0.0, (16.0 / 9.0) * scale, 0.0, scale, 0.0, 1.0).to_cols_array_2d(),
tex: &opengl_texture,
screenPxRange: (720.0 / scale) * px_range
};
// drawing a frame
let mut target = display.draw();
target.clear_color(0.3, 0.3, 0.3, 1.0);
target.draw(&vertex_buffer, NoIndices(PrimitiveType::TrianglesList), &program, &uniforms, &DrawParameters {
blend: Blend::alpha_blending(),
..Default::default()
}).unwrap();
target.finish().unwrap();
};
// Draw the triangle to the screen.
draw(scale);
// the main loop
event_loop.run(move |event, _, control_flow| {
*control_flow = match event {
glutin::event::Event::WindowEvent { event, .. } => match event {
// Break from the main loop when the window is closed.
glutin::event::WindowEvent::CloseRequested => glutin::event_loop::ControlFlow::Exit,
// Redraw the triangle when the window is resized.
glutin::event::WindowEvent::Resized(..) => {
draw(scale);
glutin::event_loop::ControlFlow::Poll
},
glutin::event::WindowEvent::MouseWheel { delta, .. } => {
scale += match delta {
MouseScrollDelta::LineDelta(_, v) => v,
MouseScrollDelta::PixelDelta(px) => px.y as f32 / 100.0
};
draw(scale);
glutin::event_loop::ControlFlow::Poll
},
_ => glutin::event_loop::ControlFlow::Poll,
},
_ => glutin::event_loop::ControlFlow::Poll,
};
});
}