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
use self::{
batches::{Batch, DrawCall},
camera::Camera,
mesh::{Mesh, MeshBuilder, Vertex},
shaders::Program,
shaders::{Shader, ShaderType},
sprites::Sprite,
text::{Font, FontError, TextSettings},
textures::Texture,
};
use gl;
use maths::{Vector2f, Vector2u, Vector3f};
use sdl2;
use std::{error, fmt, ptr};
use transform::Transform;
mod batches;
pub mod camera;
pub mod mesh;
pub mod shaders;
pub mod sprites;
pub mod text;
pub mod textures;
#[derive(Debug)]
pub enum DrawingError {
SdlError(String),
GlError(String),
MeshEBONotInitialized,
MeshVAONotInitialized,
ShaderError(shaders::ShaderError),
WindowBuildError(sdl2::video::WindowBuildError),
}
impl fmt::Display for DrawingError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
DrawingError::SdlError(string) => write!(f, "{}", string),
DrawingError::GlError(string) => write!(f, "{}", string),
DrawingError::ShaderError(error) => write!(f, "{}", error),
DrawingError::WindowBuildError(error) => write!(f, "{}", error),
DrawingError::MeshEBONotInitialized => write!(f, "Mesh EBO not initialized"),
DrawingError::MeshVAONotInitialized => write!(f, "Mesh VAO not initialized"),
}
}
}
impl error::Error for DrawingError {
fn cause(&self) -> Option<&error::Error> {
match self {
DrawingError::ShaderError(error) => Some(error),
DrawingError::WindowBuildError(error) => Some(error),
_ => None,
}
}
}
#[derive(Debug, Copy, Clone)]
pub struct WindowSettings<'a> {
pub title: &'a str,
pub width: u32,
pub height: u32,
pub vsync: bool,
}
pub struct GraphicsManager {
window: sdl2::video::Window,
#[allow(dead_code)]
gl_context: sdl2::video::GLContext,
program: Program,
quad: Mesh,
batches: Vec<Batch>,
}
impl GraphicsManager {
pub fn new(sdl: &sdl2::Sdl, window_settings: WindowSettings) -> Result<Self, DrawingError> {
let video = sdl.video().map_err(DrawingError::SdlError)?;
{
let gl_attr = video.gl_attr();
gl_attr.set_context_profile(sdl2::video::GLProfile::Core);
gl_attr.set_context_version(3, 3);
}
let window = video
.window(
window_settings.title,
window_settings.width,
window_settings.height,
).opengl()
.resizable()
.build()
.map_err(DrawingError::WindowBuildError)?;
let gl_context = window.gl_create_context().map_err(DrawingError::GlError)?;
gl::load_with(|s| video.gl_get_proc_address(s) as *const gl::types::GLvoid);
video.gl_set_swap_interval(if window_settings.vsync {
sdl2::video::SwapInterval::VSync
} else {
sdl2::video::SwapInterval::Immediate
});
unsafe {
gl::Enable(gl::DEPTH_TEST);
gl::DepthFunc(gl::LEQUAL);
gl::Enable(gl::BLEND);
gl::BlendFunc(gl::SRC_ALPHA, gl::ONE_MINUS_SRC_ALPHA);
gl::ClearColor(0.3, 0.3, 0.5, 1.0);
}
let vertex_shader =
Shader::from_source(include_str!("shaders/standard.vert"), ShaderType::Vertex)
.map_err(DrawingError::ShaderError)?;
let fragment_shader =
Shader::from_source(include_str!("shaders/standard.frag"), ShaderType::Fragment)
.map_err(DrawingError::ShaderError)?;
let program = Program::from_shaders(vertex_shader, fragment_shader)
.map_err(DrawingError::ShaderError)?;
let quad = MeshBuilder {
vertices: vec![
Vertex {
position: Vector3f::new(0.5, 0.5, 0.0),
uv: Vector2f::new(1.0, 0.0),
},
Vertex {
position: Vector3f::new(0.5, -0.5, 0.0),
uv: Vector2f::new(1.0, 1.0),
},
Vertex {
position: Vector3f::new(-0.5, -0.5, 0.0),
uv: Vector2f::new(0.0, 1.0),
},
Vertex {
position: Vector3f::new(-0.5, 0.5, 0.0),
uv: Vector2f::new(0.0, 0.0),
},
],
indices: vec![0, 1, 2, 0, 2, 3],
}.build();
Ok(Self {
window,
gl_context,
program,
quad,
batches: Vec::new(),
})
}
pub fn window_size(&self) -> Vector2u {
self.window.size().into()
}
pub fn resize(&mut self, width: i32, height: i32) {
unsafe {
gl::Viewport(0, 0, width as gl::types::GLint, height as gl::types::GLint);
}
}
pub fn draw_sprite(&mut self, sprite: &Sprite, transform: &Transform, camera: &Camera) {
let drawcall = DrawCall {
program: self.program,
mesh: self.quad,
texture: sprite.texture(),
tex_position: sprite.gl_position(),
matrix: camera.matrix(self.window.size().into()) * transform.matrix(),
};
self.queue_drawcall(&drawcall);
}
pub fn draw_text(
&mut self,
text: &str,
font: &mut Font,
settings: TextSettings,
transform: &Transform,
camera: &Camera,
) -> Result<(), FontError> {
for char_position in font.get_glyphs(text, settings)? {
let texture = font.texture();
let char_transform = Transform {
position: transform.position + Vector3f::new(
char_position.world_position.x,
char_position.world_position.y,
0.0,
),
scale: Vector3f::new(
transform.scale.x * char_position.world_position.z,
transform.scale.y * char_position.world_position.w,
transform.scale.z,
),
rotation: transform.rotation,
};
let drawcall = DrawCall {
program: self.program,
mesh: self.quad,
texture,
tex_position: char_position.texture_position,
matrix: camera.matrix(self.window.size().into()) * char_transform.matrix(),
};
self.queue_drawcall(&drawcall);
}
Ok(())
}
pub fn queue_drawcall(&mut self, drawcall: &DrawCall) {
for batch in &mut self.batches {
if batch.add(drawcall) {
return;
}
}
self.batches.push(Batch::new(drawcall));
}
pub fn render(&mut self) -> Result<(), DrawingError> {
unsafe {
gl::Clear(gl::COLOR_BUFFER_BIT | gl::DEPTH_BUFFER_BIT);
}
for batch in &self.batches {
self.draw(batch)?
}
self.batches.clear();
self.window.gl_swap_window();
Ok(())
}
fn draw(&self, batch: &Batch) -> Result<(), DrawingError> {
batch.mesh().check()?;
batch.program().set_used();
unsafe {
gl::BindTexture(gl::TEXTURE_2D, batch.texture());
gl::BindVertexArray(batch.mesh().vao());
gl::BindBuffer(gl::ELEMENT_ARRAY_BUFFER, batch.mesh().ebo());
}
batch.buffer_data();
unsafe {
gl::DrawElementsInstanced(
gl::TRIANGLES,
batch.mesh().indices_count() as i32,
gl::UNSIGNED_INT,
ptr::null(),
batch.obj_count() as gl::types::GLint,
);
}
Ok(())
}
}