Add music to emscripten port.
[mandelwow.git] / main.rs
1 extern crate cgmath;
2 #[macro_use(uniform,program,implement_vertex)]
3 extern crate glium;
4 extern crate glutin;
5 extern crate image;
6 extern crate libxm;
7 extern crate sdl2;
8
9 //use cgmath::prelude::*;
10 use cgmath::{Euler, Matrix4, Rad, Vector3};
11 use cube::Cube;
12 use glium::{DisplayBuild, Surface};
13 use glutin::ElementState::Pressed;
14 use glutin::Event::KeyboardInput;
15 use glutin::VirtualKeyCode;
16 use std::os::raw::{c_int, c_void};
17
18 mod bounding_box;
19 mod cube;
20 mod mandelwow;
21 mod sound;
22 mod support;
23
24 fn screenshot(display : &glium::Display) {
25     let image: glium::texture::RawImage2d<u8> = display.read_front_buffer();
26     let image = image::ImageBuffer::from_raw(image.width, image.height, image.data.into_owned()).unwrap();
27     let image = image::DynamicImage::ImageRgba8(image).flipv();
28     let mut output = std::fs::File::create(&std::path::Path::new("screenshot.png")).unwrap();
29     image.save(&mut output, image::ImageFormat::PNG).unwrap();
30 }
31
32 fn gl_info(display : &glium::Display) {
33     let version = *display.get_opengl_version();
34     let api = match version {
35         glium::Version(glium::Api::Gl, _, _) => "OpenGL",
36         glium::Version(glium::Api::GlEs, _, _) => "OpenGL ES"
37     };
38     println!("{} context verson: {}", api, display.get_opengl_version_string());
39 }
40
41 #[allow(non_camel_case_types)]
42 type em_callback_func = unsafe extern fn();
43 extern {
44     fn emscripten_set_main_loop(func : em_callback_func, fps : c_int, simulate_infinite_loop : c_int);
45 }
46
47 thread_local!(static MAIN_LOOP_CALLBACK: std::cell::RefCell<*mut c_void> =
48               std::cell::RefCell::new(std::ptr::null_mut()));
49
50 pub fn set_main_loop_callback<F>(callback : F) where F : FnMut() {
51     MAIN_LOOP_CALLBACK.with(|log| {
52             *log.borrow_mut() = &callback as *const _ as *mut c_void;
53             });
54
55     unsafe { emscripten_set_main_loop(wrapper::<F>, 0, 1); }
56
57     unsafe extern "C" fn wrapper<F>() where F : FnMut() {
58         MAIN_LOOP_CALLBACK.with(|z| {
59             let closure = *z.borrow_mut() as *mut F;
60             (*closure)();
61         });
62     }
63 }
64
65 fn main() {
66     let _soundplayer = sound::start();
67
68     let display = glutin::WindowBuilder::new()
69         .with_dimensions(600, 600)
70         //.with_fullscreen(glutin::get_primary_monitor())
71         .with_depth_buffer(24)
72         .with_vsync()
73         .with_title(format!("MandelWow"))
74         .build_glium()
75         .unwrap();
76
77     gl_info(&display);
78
79     let mandelwow_program = mandelwow::program(&display);
80     let bounding_box_program = bounding_box::solid_fill_program(&display);
81
82     let mut camera = support::camera::CameraState::new();
83     let mut t: f32 = 0.0;
84     let mut pause = false;
85     let mut bounding_box_enabled = true;
86     let mut fullscreen = true;
87
88     // These are the bounds of the 3D Mandelwow section which we render in 3-space.
89     let bounds = Cube {
90         xmin: -2.0,
91         xmax:  0.7,
92         ymin: -1.0,
93         ymax:  1.0,
94         zmin: -1.1,
95         zmax:  1.1,
96     };
97
98     //support::start_loop(|| {
99     set_main_loop_callback(|| {
100         camera.update();
101
102         if !pause {
103             // Increment time
104             t += 0.01;
105         }
106
107         // Vary the wow factor to slice the Mandelwow along its 4th dimension.
108         let wmin = -0.8;
109         let wmax =  0.8;
110         let wsize = wmax - wmin;
111         let wow = (((t * 0.7).sin() + 1.0) / 2.0) * wsize + wmin;
112
113         //println!("t={} w={:?} camera={:?}", t, w, camera.get_pos());
114
115         let mut frame = display.draw();
116         frame.clear_color_and_depth((0.0, 0.0, 0.0, 1.0), 1.0);
117
118         let rotation = cgmath::Matrix4::from(
119             Euler { x: Rad(t.sin() / 3.), y: Rad(t.sin() / 2.), z: Rad(t)});
120         let z_trans = -2.0;  // Send the model back a little bit so it fits the screen.
121         let model2 =
122             Matrix4::from_translation(Vector3::unit_z() * z_trans) * rotation;
123         let model = cgmath::conv::array4x4(model2);
124
125         // Draw the bounding box before the fractal, when the Z-buffer is still clear,
126         // so the lines behind the semi-translucent areas will be drawn.
127         if bounding_box_enabled {
128             let uniforms = uniform! {
129                 model: model,
130                 view:  camera.get_view(),
131                 perspective: camera.get_perspective(),
132             };
133             bounding_box::draw(&display, &mut frame, &bounding_box_program, &uniforms, &bounds);
134         }
135
136         mandelwow::draw(&display, &mut frame, &mandelwow_program, model, &camera, &bounds, wow);
137         frame.finish().unwrap();
138
139         for ev in display.poll_events() {
140             match ev {
141                 glutin::Event::Closed |
142                 KeyboardInput(Pressed, _, Some(VirtualKeyCode::Escape)) |
143                 KeyboardInput(Pressed, _, Some(VirtualKeyCode::Q)) => {
144                     //return support::Action::Stop
145                 },
146                 KeyboardInput(Pressed, _, Some(VirtualKeyCode::B)) => {
147                     bounding_box_enabled ^= true;
148                 },
149                 KeyboardInput(Pressed, _, Some(VirtualKeyCode::P)) => {
150                     pause ^= true;
151                 },
152                 KeyboardInput(Pressed, _, Some(VirtualKeyCode::PageUp)) => {
153                     t += 0.01;
154                 },
155                 KeyboardInput(Pressed, _, Some(VirtualKeyCode::PageDown)) => {
156                     t -= 0.01;
157                 },
158                 KeyboardInput(Pressed, _, Some(VirtualKeyCode::F10)) => {
159                     screenshot(&display);
160                 },
161                 KeyboardInput(Pressed, _, Some(VirtualKeyCode::F11)) => {
162                     fullscreen ^= true;
163                     if fullscreen {
164                         // Not implemented on Linux
165                         glutin::WindowBuilder::new()
166                             .with_fullscreen(glutin::get_primary_monitor())
167                             .with_depth_buffer(24)
168                             .rebuild_glium(&display).unwrap();
169                     } else {
170                         //glutin::WindowBuilder::new()
171                         //    .rebuild_glium(&display).unwrap();
172                     }
173                 },
174                 ev => camera.process_input(&ev),
175             }
176         }
177
178         //support::Action::Continue
179     });
180 }