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
use std::mem;
use std::thread;
use std::time::{Duration, Instant};
use glfw;
use glfw::{Context, Key, Action, WindowMode, WindowEvent};
use std::cell::RefCell;
use std::rc::Rc;
use std::sync::mpsc::Receiver;
use std::sync::{Once, ONCE_INIT};
use std::path::Path;
use std::iter::repeat;
use gl;
use gl::types::*;
use image::{ImageBuffer,Rgb};
use image::imageops;
use na::{Point2, Vector2, Vector3, Point3};
use ncollide_procedural::TriMesh3;
use camera::Camera;
use scene::SceneNode;
use line_renderer::LineRenderer;
use point_renderer::PointRenderer;
use post_processing::PostProcessingEffect;
use resource::{FramebufferManager, RenderTarget, Texture, TextureManager, Mesh};
use light::Light;
use text::{TextRenderer, Font};
use window::EventManager;
use camera::ArcBall;
static DEFAULT_WIDTH: u32 = 800u32;
static DEFAULT_HEIGHT: u32 = 600u32;
pub struct Window {
events: Rc<Receiver<(f64, WindowEvent)>>,
unhandled_events: Rc<RefCell<Vec<WindowEvent>>>,
glfw: glfw::Glfw,
window: glfw::Window,
max_dur_per_frame: Option<Duration>,
scene: SceneNode,
light_mode: Light,
background: Vector3<GLfloat>,
line_renderer: LineRenderer,
point_renderer: PointRenderer,
text_renderer: TextRenderer,
framebuffer_manager: FramebufferManager,
post_process_render_target: RenderTarget,
curr_time: Instant,
camera: Rc<RefCell<ArcBall>>
}
impl Window {
#[inline]
pub fn should_close(&self) -> bool {
self.window.should_close()
}
#[inline]
pub fn context(&self) -> &glfw::Glfw {
&self.glfw
}
#[inline]
pub fn glfw_window(&self) -> &glfw::Window {
&self.window
}
#[inline]
pub fn glfw_window_mut(&mut self) -> &mut glfw::Window {
&mut self.window
}
#[inline]
pub fn width(&self) -> f32 {
let (w, _) = self.window.get_size();
w as f32
}
#[inline]
pub fn height(&self) -> f32 {
let (_, h) = self.window.get_size();
h as f32
}
#[inline]
pub fn size(&self) -> Vector2<f32> {
let (w, h) = self.window.get_size();
Vector2::new(w as f32, h as f32)
}
#[inline]
pub fn set_framerate_limit(&mut self, fps: Option<u64>) {
self.max_dur_per_frame = fps.map(|f| { assert!(f != 0); Duration::from_millis(1000 / f) })
}
pub fn set_title(&mut self, title: &str) {
self.window.set_title(title)
}
#[inline]
pub fn close(&mut self) {
self.window.set_should_close(true)
}
#[inline]
pub fn hide(&mut self) {
self.window.hide()
}
#[inline]
pub fn show(&mut self) {
self.window.show()
}
#[inline]
pub fn set_background_color(&mut self, r: f32, g: GLfloat, b: f32) {
self.background.x = r;
self.background.y = g;
self.background.z = b;
}
#[inline]
pub fn draw_line(&mut self, a: &Point3<f32>, b: &Point3<f32>, color: &Point3<f32>) {
self.line_renderer.draw_line(a.clone(), b.clone(), color.clone());
}
#[inline]
pub fn draw_point(&mut self, pt: &Point3<f32>, color: &Point3<f32>) {
self.point_renderer.draw_point(pt.clone(), color.clone());
}
#[inline]
pub fn draw_text(&mut self, text: &str, pos: &Point2<f32>, font: &Rc<Font>, color: &Point3<f32>) {
self.text_renderer.draw_text(text, pos, font, color);
}
pub fn remove(&mut self, sn: &mut SceneNode) {
sn.unlink()
}
pub fn add_group(&mut self) -> SceneNode {
self.scene.add_group()
}
pub fn add_obj(&mut self, path: &Path, mtl_dir: &Path, scale: Vector3<f32>) -> SceneNode {
self.scene.add_obj(path, mtl_dir, scale)
}
pub fn add_mesh(&mut self, mesh: Rc<RefCell<Mesh>>, scale: Vector3<f32>) -> SceneNode {
self.scene.add_mesh(mesh, scale)
}
pub fn add_trimesh(&mut self, descr: TriMesh3<f32>, scale: Vector3<f32>) -> SceneNode {
self.scene.add_trimesh(descr, scale)
}
pub fn add_geom_with_name(&mut self, geometry_name: &str, scale: Vector3<f32>) -> Option<SceneNode> {
self.scene.add_geom_with_name(geometry_name, scale)
}
pub fn add_cube(&mut self, wx: GLfloat, wy: GLfloat, wz: GLfloat) -> SceneNode {
self.scene.add_cube(wx, wy, wz)
}
pub fn add_sphere(&mut self, r: GLfloat) -> SceneNode {
self.scene.add_sphere(r)
}
pub fn add_cone(&mut self, r: GLfloat, h: GLfloat) -> SceneNode {
self.scene.add_cone(r, h)
}
pub fn add_cylinder(&mut self, r: GLfloat, h: GLfloat) -> SceneNode {
self.scene.add_cylinder(r, h)
}
pub fn add_capsule(&mut self, r: GLfloat, h: GLfloat) -> SceneNode {
self.scene.add_capsule(r, h)
}
pub fn add_quad(&mut self, w: f32, h: f32, usubdivs: usize, vsubdivs: usize) -> SceneNode {
self.scene.add_quad(w, h, usubdivs, vsubdivs)
}
pub fn add_quad_with_vertices(&mut self,
vertices: &[Point3<f32>],
nhpoints: usize,
nvpoints: usize)
-> SceneNode {
self.scene.add_quad_with_vertices(vertices, nhpoints, nvpoints)
}
#[doc(hidden)]
pub fn add_texture(&mut self, path: &Path, name: &str) -> Rc<Texture> {
TextureManager::get_global_manager(|tm| tm.add(path, name))
}
pub fn is_closed(&self) -> bool {
false
}
pub fn set_light(&mut self, pos: Light) {
self.light_mode = pos;
}
pub fn new_hidden(title: &str) -> Window {
Window::do_new(title, true, DEFAULT_WIDTH, DEFAULT_HEIGHT)
}
pub fn new(title: &str) -> Window {
Window::do_new(title, false, DEFAULT_WIDTH, DEFAULT_HEIGHT)
}
pub fn new_with_size(title: &str, width: u32, height: u32) -> Window {
Window::do_new(title, false, width, height)
}
fn do_new(title: &str, hide: bool, width: u32, height: u32) -> Window {
static mut GLFW_SINGLETON: Option<glfw::Glfw> = None;
static INIT: Once = ONCE_INIT;
let glfw = unsafe {
INIT.call_once(|| {
GLFW_SINGLETON = Some(glfw::init(glfw::FAIL_ON_ERRORS).unwrap());
});
GLFW_SINGLETON.unwrap().clone()
};
let (mut window, events) = glfw.create_window(width, height, title, WindowMode::Windowed).expect("Unable to open a glfw window.");
window.make_current();
verify!(gl::load_with(|name| window.get_proc_address(name) as *const _));
init_gl();
let mut usr_window = Window {
max_dur_per_frame: None,
glfw: glfw,
window: window,
events: Rc::new(events),
unhandled_events: Rc::new(RefCell::new(Vec::new())),
scene: SceneNode::new_empty(),
light_mode: Light::Absolute(Point3::new(0.0, 10.0, 0.0)),
background: Vector3::new(0.0, 0.0, 0.0),
line_renderer: LineRenderer::new(),
point_renderer: PointRenderer::new(),
text_renderer: TextRenderer::new(),
post_process_render_target: FramebufferManager::new_render_target(width as usize, height as usize),
framebuffer_manager: FramebufferManager::new(),
curr_time: Instant::now(),
camera: Rc::new(RefCell::new(ArcBall::new(Point3::new(0.0f32, 0.0, -1.0), Point3::origin())))
};
usr_window.window.set_framebuffer_size_polling(true);
usr_window.window.set_key_polling(true);
usr_window.window.set_mouse_button_polling(true);
usr_window.window.set_cursor_pos_polling(true);
usr_window.window.set_scroll_polling(true);
if hide {
usr_window.window.hide()
}
let light = usr_window.light_mode.clone();
usr_window.set_light(light);
usr_window
}
#[inline]
pub fn scene(&self) -> &SceneNode {
&self.scene
}
#[inline]
pub fn scene_mut(&mut self) -> &mut SceneNode {
&mut self.scene
}
pub fn snap(&self, out: &mut Vec<u8>) {
let (width, height) = self.window.get_size();
self.snap_rect(out, 0, 0, width as usize, height as usize)
}
pub fn snap_rect(&self, out: &mut Vec<u8>, x: usize, y: usize, width: usize, height: usize) {
let size = (width * height * 3) as usize;
if out.len() < size {
let diff = size - out.len();
out.extend(repeat(0).take(diff));
}
else {
out.truncate(size)
}
unsafe {
gl::PixelStorei(gl::PACK_ALIGNMENT, 1);
gl::ReadPixels(x as i32, y as i32,
width as i32, height as i32,
gl::RGB,
gl::UNSIGNED_BYTE,
mem::transmute(&mut out[0]));
}
}
pub fn snap_image(&self) -> ImageBuffer<Rgb<u8>, Vec<u8>> {
let (width, height) = self.window.get_size();
let mut buf = Vec::new();
self.snap(&mut buf);
let img_opt = ImageBuffer::from_vec(width as u32, height as u32, buf);
let img = img_opt.expect("Buffer created from window was not big enough for image.");
imageops::flip_vertical(&img)
}
pub fn events(&self) -> EventManager {
EventManager::new(self.events.clone(), self.unhandled_events.clone())
}
#[inline]
fn handle_events(&mut self, camera: &mut Option<&mut Camera>) {
let unhandled_events = self.unhandled_events.clone();
let events = self.events.clone();
for event in unhandled_events.borrow().iter() {
self.handle_event(camera, event)
}
for event in glfw::flush_messages(&*events) {
self.handle_event(camera, &event.1)
}
unhandled_events.borrow_mut().clear();
self.glfw.poll_events();
}
fn handle_event(&mut self, camera: &mut Option<&mut Camera>, event: &WindowEvent) {
match *event {
WindowEvent::Key(Key::Escape, _, Action::Release, _) => {
self.close();
},
WindowEvent::FramebufferSize(w, h) => {
self.update_viewport(w as f32, h as f32);
},
_ => { }
}
match *camera {
Some(ref mut cam) => cam.handle_event(&self.window, event),
None => self.camera.borrow_mut().handle_event(&self.window, event)
}
}
pub fn render(&mut self) -> bool {
self.render_with(None, None)
}
pub fn render_with_effect(&mut self, effect: &mut PostProcessingEffect) -> bool {
self.render_with(None, Some(effect))
}
pub fn render_with_camera(&mut self, camera: &mut Camera) -> bool {
self.render_with(Some(camera), None)
}
pub fn render_with_camera_and_effect(&mut self, camera: &mut Camera, effect: &mut PostProcessingEffect) -> bool {
self.render_with(Some(camera), Some(effect))
}
pub fn render_with(&mut self,
camera: Option<&mut Camera>,
post_processing: Option<&mut PostProcessingEffect>)
-> bool {
let mut camera = camera;
self.handle_events(&mut camera);
match camera {
Some(cam) => self.do_render_with(cam, post_processing),
None => {
let self_cam = self.camera.clone();
let mut bself_cam = self_cam.borrow_mut();
self.do_render_with(&mut *bself_cam, post_processing)
}
}
}
fn do_render_with(&mut self,
camera: &mut Camera,
post_processing: Option<&mut PostProcessingEffect>)
-> bool {
let w = self.width();
let h = self.height();
camera.handle_event(&self.window, &WindowEvent::FramebufferSize(w as i32, h as i32));
camera.update(&self.window);
match self.light_mode {
Light::StickToCamera => self.set_light(Light::StickToCamera),
_ => { }
}
let mut post_processing = post_processing;
if post_processing.is_some() {
self.framebuffer_manager.select(&self.post_process_render_target);
}
else {
self.framebuffer_manager.select(&FramebufferManager::screen());
}
for pass in 0usize .. camera.num_passes() {
camera.start_pass(pass, &self.window);
self.render_scene(camera, pass);
}
camera.render_complete(&self.window);
let (znear, zfar) = camera.clip_planes();
match post_processing {
Some(ref mut p) => {
self.framebuffer_manager.select(&FramebufferManager::screen());
p.update(0.016, w, h, znear, zfar);
p.draw(&self.post_process_render_target);
},
None => { }
}
self.text_renderer.render(w, h);
self.window.swap_buffers();
match self.max_dur_per_frame {
None => { },
Some(dur) => {
let elapsed = self.curr_time.elapsed();
if elapsed < dur {
thread::sleep(dur - elapsed);
}
}
}
self.curr_time = Instant::now();
!self.should_close()
}
fn render_scene(&mut self, camera: &mut Camera, pass: usize) {
verify!(gl::ActiveTexture(gl::TEXTURE0));
verify!(gl::ClearColor(self.background.x, self.background.y, self.background.z, 1.0));
verify!(gl::Clear(gl::COLOR_BUFFER_BIT));
verify!(gl::Clear(gl::DEPTH_BUFFER_BIT));
if self.line_renderer.needs_rendering() {
self.line_renderer.render(pass, camera);
}
if self.point_renderer.needs_rendering() {
self.point_renderer.render(pass, camera);
}
self.scene.data_mut().render(pass, camera, &self.light_mode);
}
fn update_viewport(&mut self, w: f32, h: f32) {
verify!(gl::Scissor(0, 0, w as i32, h as i32));
FramebufferManager::screen().resize(w, h);
self.post_process_render_target.resize(w, h);
}
}
fn init_gl() {
verify!(gl::FrontFace(gl::CCW));
verify!(gl::Enable(gl::DEPTH_TEST));
verify!(gl::Enable(gl::SCISSOR_TEST));
verify!(gl::DepthFunc(gl::LEQUAL));
verify!(gl::FrontFace(gl::CCW));
verify!(gl::Enable(gl::CULL_FACE));
verify!(gl::CullFace(gl::BACK));
}