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