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