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