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