Initial commit.
[mandelwow.git] / support / mod.rs
1 #![allow(dead_code)]
2
3 extern crate genmesh;
4 extern crate obj;
5
6 use std::thread;
7 use std::time::{Duration, Instant};
8 use glium::{self, Display};
9 use glium::vertex::VertexBufferAny;
10
11 pub mod camera;
12
13 pub enum Action {
14     Stop,
15     Continue,
16 }
17
18 pub fn start_loop<F>(mut callback: F) where F: FnMut() -> Action {
19     let mut accumulator = Duration::new(0, 0);
20     let mut previous_clock = Instant::now();
21
22     loop {
23         match callback() {
24             Action::Stop => break,
25             Action::Continue => ()
26         };
27
28         let now = Instant::now();
29         accumulator += now - previous_clock;
30         previous_clock = now;
31
32         let fixed_time_stamp = Duration::new(0, 16666667);
33         while accumulator >= fixed_time_stamp {
34             accumulator -= fixed_time_stamp;
35
36             // if you have a game, update the state here
37         }
38
39         thread::sleep(fixed_time_stamp - accumulator);
40     }
41 }
42
43 /// Returns a vertex buffer that should be rendered as `TrianglesList`.
44 pub fn load_wavefront(display: &Display, data: &[u8]) -> VertexBufferAny {
45     #[derive(Copy, Clone)]
46     struct Vertex {
47         position: [f32; 3],
48         normal: [f32; 3],
49         texture: [f32; 2],
50     }
51
52     implement_vertex!(Vertex, position, normal, texture);
53
54     let mut data = ::std::io::BufReader::new(data);
55     let data = obj::Obj::load(&mut data);
56
57     let mut vertex_data = Vec::new();
58
59     for object in data.object_iter() {
60         for shape in object.group_iter().flat_map(|g| g.indices().iter()) {
61             match shape {
62                 &genmesh::Polygon::PolyTri(genmesh::Triangle { x: v1, y: v2, z: v3 }) => {
63                     for v in [v1, v2, v3].iter() {
64                         let position = data.position()[v.0];
65                         let texture = v.1.map(|index| data.texture()[index]);
66                         let normal = v.2.map(|index| data.normal()[index]);
67
68                         let texture = texture.unwrap_or([0.0, 0.0]);
69                         let normal = normal.unwrap_or([0.0, 0.0, 0.0]);
70
71                         vertex_data.push(Vertex {
72                             position: position,
73                             normal: normal,
74                             texture: texture,
75                         })
76                     }
77                 },
78                 _ => unimplemented!()
79             }
80         }
81     }
82
83     glium::vertex::VertexBuffer::new(display, &vertex_data).unwrap().into_vertex_buffer_any()
84 }