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