Port to glium 0.17 and glutin 0.9.
[mandelwow.git] / main.rs
1 extern crate mandelwow_lib;
2
3 extern crate cgmath;
4 #[macro_use(uniform)]
5 extern crate glium;
6 extern crate glutin;
7
8 use cgmath::{Euler, Matrix4, Rad, SquareMatrix, Vector3, Vector4, Zero};
9 use cgmath::conv::array4x4;
10 use glium::{Surface};
11 use glutin::ElementState::Pressed;
12 use glutin::WindowEvent::KeyboardInput;
13 use glutin::VirtualKeyCode;
14 use mandelwow_lib::*;
15 use std::f32::consts::PI;
16 use timer::Timer;
17
18 #[cfg(target_os = "emscripten")]
19 use std::os::raw::{c_int, c_void};
20
21 fn gl_info(display : &glium::Display) {
22     if cfg!(feature = "logging") {
23         let version = *display.get_opengl_version();
24         let api = match version {
25             glium::Version(glium::Api::Gl, _, _) => "OpenGL",
26             glium::Version(glium::Api::GlEs, _, _) => "OpenGL ES"
27         };
28         println!("{} context verson: {}", api, display.get_opengl_version_string());
29     }
30 }
31
32 #[cfg(target_os = "emscripten")]
33 #[allow(non_camel_case_types)]
34 type em_callback_func = unsafe extern fn();
35 #[cfg(target_os = "emscripten")]
36 extern {
37     fn emscripten_set_main_loop(func : em_callback_func, fps : c_int, simulate_infinite_loop : c_int);
38 }
39
40 #[cfg(target_os = "emscripten")]
41 thread_local!(static MAIN_LOOP_CALLBACK: std::cell::RefCell<*mut c_void> =
42               std::cell::RefCell::new(std::ptr::null_mut()));
43
44 #[cfg(target_os = "emscripten")]
45 pub fn set_main_loop_callback<F>(callback : F) where F : FnMut() -> support::Action {
46     MAIN_LOOP_CALLBACK.with(|log| {
47             *log.borrow_mut() = &callback as *const _ as *mut c_void;
48             });
49
50     unsafe { emscripten_set_main_loop(wrapper::<F>, 0, 1); }
51
52     unsafe extern "C" fn wrapper<F>() where F : FnMut() -> support::Action {
53         MAIN_LOOP_CALLBACK.with(|z| {
54             let closure = *z.borrow_mut() as *mut F;
55             (*closure)();
56         });
57     }
58 }
59
60 #[cfg(not(target_os = "emscripten"))]
61 pub fn set_main_loop_callback<F>(callback : F) where F : FnMut() -> support::Action {
62     support::start_loop(callback);
63 }
64
65 fn main() {
66     let mut soundplayer = sound::start();
67
68     let mut events_loop = glutin::EventsLoop::new();
69     let window = glutin::WindowBuilder::new()
70         .with_dimensions(1280, 720)
71         //.with_fullscreen(glutin::get_primary_monitor())
72         .with_title("MandelWow");
73     let context = glutin::ContextBuilder::new()
74         .with_gl_profile(glutin::GlProfile::Core)
75         .with_depth_buffer(24)
76         .with_vsync(true)
77         .with_srgb(true);
78     let display = glium::Display::new(window, context, &events_loop).unwrap();
79     gl_info(&display);
80
81     let mut text = text::Text::new(&display, 'A');
82     let mandelwow_program = mandelwow::program(&display);
83     let bounding_box_program = bounding_box::solid_fill_program(&display);
84     let shaded_program = shaded_cube::shaded_program(&display);
85
86     let mut timer = Timer::new();
87     let mut camera = support::camera::CameraState::new();
88     let mut bounding_box_enabled = true;
89     let mut fullscreen = true;
90
91     // These are the bounds of the 3D Mandelwow section which we render in 3-space.
92     let bounds = Cube {
93         xmin: -2.0,
94         xmax:  0.7,
95         ymin: -1.0,
96         ymax:  1.0,
97         zmin: -1.1,
98         zmax:  1.1,
99     };
100     let mandelwow_bbox = bounding_box::BoundingBox::new(&display, &bounds, &bounding_box_program);
101     let shaded_cube = ShadedCube::new(&display, &shaded_program);
102
103     const SEA_XSIZE: usize = 40;
104     const SEA_ZSIZE: usize = 25;
105     let sea_xmin = -20.0f32;
106     let sea_xmax =  20.0f32;
107     let sea_y = -2.5;
108     let sea_zmin =  -2.0f32;
109     let sea_zmax = -27.0f32;
110     let sea_xstep = (sea_xmax - sea_xmin) / (SEA_XSIZE as f32);
111     let sea_zstep = (sea_zmax - sea_zmin) / (SEA_ZSIZE as f32);
112     println!("xstep={} ystep={:?}", sea_xstep, sea_zstep);
113
114     let mut sea = [[Vector3::zero(); SEA_ZSIZE]; SEA_XSIZE];
115     for x in 0..SEA_XSIZE {
116         for z in 0..SEA_ZSIZE {
117             sea[x][z] = Vector3 {
118                 x: sea_xmin + (x as f32) * sea_xstep,
119                 y: sea_y,
120                 z: sea_zmin + (z as f32) * sea_zstep,
121             };
122         }
123     }
124
125     let mut last_hit = 0.0f32;
126     let mut hit_time = 0.0f32;
127     set_main_loop_callback(|| {
128         let t = timer.t;
129         let new_hit = sound::hit_event(&mut soundplayer);
130         if new_hit > last_hit {
131             hit_time = t;
132         }
133         last_hit = new_hit;
134         let hit_delta = t - hit_time;
135         let hit_scale = 1. / (1. + hit_delta * hit_delta * 15.0) + 1.;
136
137         camera.update();
138         let perspview = camera.get_perspview();
139
140         // Vary the wow factor to slice the Mandelwow along its 4th dimension.
141         let wmin = -0.8;
142         let wmax =  0.8;
143         let wsize = wmax - wmin;
144         let wow = (((t * 0.7).sin() + 1.0) / 2.0) * wsize + wmin;
145
146         //println!("t={} w={:?} camera={:?}", t, w, camera.get_pos());
147
148         let mut frame = display.draw();
149         frame.clear_color_and_depth((0.0, 0.0, 0.0, 1.0), 1.0);
150
151         let rotation = Matrix4::from(
152             Euler { x: Rad(t.sin() / 3.), y: Rad(t.sin() / 2.), z: Rad(t / 1.5)});
153         let z_trans = -3.0;  // Send the model back a little bit so it fits the screen.
154         let scale =
155             Matrix4::from_diagonal(Vector4::new(hit_scale, hit_scale, hit_scale, 1.0));
156         let model2 =
157             Matrix4::from_translation(Vector3::unit_z() * z_trans) * rotation * scale;
158         let model = array4x4(model2);
159
160         // Draw the bounding box before the fractal, when the Z-buffer is still clear,
161         // so the lines behind the semi-translucent areas will be drawn.
162         if bounding_box_enabled {
163             let uniforms = uniform! {
164                 model: model,
165                 view:  camera.get_view(),
166                 perspective: camera.get_perspective(),
167             };
168             mandelwow_bbox.draw(&mut frame, &uniforms);
169         }
170
171         let text_rot = Matrix4::from_angle_x(cgmath::Deg(-90.0f32));
172         let text_pos = Matrix4::from_translation(Vector3 { x: 0.0, y: 0.501, z: 0.0f32}) * text_rot;
173         for x in 0..SEA_XSIZE {
174             for z in 0..SEA_ZSIZE {
175                 let wave = ((x as f32 / SEA_XSIZE as f32 * PI * 5.0 + t * 2.0).sin() +
176                             (z as f32 / SEA_ZSIZE as f32 * PI * 3.0 + t * 3.0).sin()) * 0.3;
177                 let model = Matrix4::from_translation(
178                     sea[x][z] + Vector3 {x: 0., y: wave, z: 0.});
179                 let uniforms = uniform! {
180                     model: array4x4(model),
181                     perspview: perspview,
182                     col: [0., (1. - wave).abs() * 0.5,  wave.abs()],
183                 };
184                 shaded_cube.draw(&mut frame, &uniforms);
185                 text.model = model * text_pos;
186                 text.character = (x + z * SEA_XSIZE) as u8 as char;
187                 text.draw(&mut frame, &perspview);
188             }
189         }
190
191         mandelwow::draw(&display, &mut frame, &mandelwow_program, model, &camera, &bounds, wow);
192
193         frame.finish().unwrap();
194
195         let mut action = support::Action::Continue;
196         events_loop.poll_events(|event| {
197             if let glutin::Event::WindowEvent { event, .. } = event {
198                 camera.process_input(&event);
199                 match event {
200                     glutin::WindowEvent::Closed => {
201                         action = support::Action::Stop
202                     },
203                     KeyboardInput { input, .. } => {
204                         if input.state == glutin::ElementState::Pressed {
205                             if let Some(key) = input.virtual_keycode {
206                                 match key {
207                                     VirtualKeyCode::Escape | VirtualKeyCode::Q => {
208                                         action = support::Action::Stop;
209                                     },
210                                     _ => (),
211                                 }
212                             }
213                         }
214                     },
215 /*
216                     KeyboardInput { input: glutin::KeyboardInput { state: Pressed, virtual_keycode: Some(VirtualKeyCode::Escape), .. } } |
217                     KeyboardInput { input: glutin::KeyboardInput { state: Pressed, virtual_keycode: Some(VirtualKeyCode::Q), .. } } => {
218                         return support::Action::Stop
219                     },
220                     KeyboardInput { state: Pressed, virtual_keycode: Some(VirtualKeyCode::B) } => {
221                         bounding_box_enabled ^= true;
222                     },
223                     KeyboardInput { state: Pressed, virtual_keycode: Some(VirtualKeyCode::P) } => {
224                         timer.pause ^= true;
225                     },
226                     KeyboardInput { state: Pressed, virtual_keycode: Some(VirtualKeyCode::PageUp) } => {
227                         timer.t += 0.01;
228                     },
229                     KeyboardInput { state: Pressed, virtual_keycode: Some(VirtualKeyCode::PageDown) } => {
230                         timer.t -= 0.01;
231                     },
232                     KeyboardInput { state: Pressed, virtual_keycode: Some(VirtualKeyCode::F10) } => {
233                         screenshot(&display);
234                     },
235                     KeyboardInput { state: Pressed, virtual_keycode: Some(VirtualKeyCode::F11) } => {
236                         fullscreen ^= true;
237                         if fullscreen {
238                             // Not implemented on Linux
239                             glutin::WindowBuilder::new()
240                                 .with_fullscreen(glutin::get_primary_monitor())
241                                 .with_depth_buffer(24)
242                                 .rebuild_glium(&display).unwrap();
243                         } else {
244                             glutin::WindowBuilder::new()
245                                 .rebuild_glium(&display).unwrap();
246                         }
247                     },
248 */
249                     _ => (),
250                 }
251             }
252         });
253
254         timer.update();
255
256         action
257     });
258 }