Move sound code to sound.rs
[mandelwow.git] / mandelwow.rs
1 // Wow. Such fractal.
2
3 #[macro_use]
4
5 extern crate glium;
6 extern crate glutin;
7 extern crate libxm;
8 extern crate sdl2;
9
10 use glium::{DisplayBuild, Surface};
11 use glium::index::{IndexBuffer, PrimitiveType};
12 use glutin::ElementState::Pressed;
13 use glutin::Event::KeyboardInput;
14 use glutin::VirtualKeyCode;
15
16 mod sound;
17 mod support;
18
19 #[derive(Copy, Clone)]
20 struct Cube {
21     xmin: f32,
22     ymin: f32,
23     zmin: f32,
24     xmax: f32,
25     ymax: f32,
26     zmax: f32,
27 }
28
29 /*
30 fn mand(cx: f32, cy: f32) -> [f32; 3] {
31     let maxiter = 64;
32     let mut iter = maxiter;
33     let mut zx = cx;
34     let mut zy = cy;
35     while iter > 0 {
36         let zx2 = zx * zx;
37         let zy2 = zy * zy;
38         if zx2 + zy2 > 4.0 {
39             return [iter as f32 / maxiter as f32, 1.0, 1.0];
40         }
41         zy = zx * zy * 2.0 + cy;
42         zx = zx2 - zy2 + cx;
43         iter -= 1;
44     }
45
46     [0.0, 0.0, 0.0]
47 }
48 */
49
50 fn mandelwow_program(display: &glium::Display) -> glium::Program {
51     return program!(display,
52         140 => {
53             vertex: r#"
54                 #version 140
55                 uniform mat4 perspective;
56                 uniform mat4 view;
57                 uniform mat4 model;
58                 uniform vec2 z0;
59                 in vec3 position;
60                 out vec2 c;
61                 out vec2 z;
62
63                 void main() {
64                     mat4 modelview = view * model;
65                     gl_Position = perspective * modelview * vec4(position, 1.0);
66                     c = vec2(position.x, position.y);
67                     z = vec2(z0.x, z0.y);
68                 }
69             "#,
70
71             fragment: r#"
72                 #version 140
73                 precision highp float;
74                 in vec2 c;
75                 in vec2 z;
76                 out vec4 f_color;
77
78                 void main() {
79                     float zx = z.x;
80                     float zy = z.y;
81                     int maxiter = 64;
82                     int iter = maxiter;
83                     while (iter > 0) {
84                         float zx2 = zx * zx;
85                         float zy2 = zy * zy;
86                         if (zx2 * zy2 > 4.0) {
87                           float index = 1.0 - float(iter) / float(maxiter);
88                           f_color = vec4(index, index * 0.5, index, index * 0.5);
89                           return;
90                         }
91                         zy = zx * zy * 2.0 + c.y;
92                         zx = zx2 - zy2 + c.x;
93                         iter -= 1;
94                     }
95                     f_color = vec4((sin(z.y) + 1.0) / 2,
96                                    (sin(c.y) + 1.0) / 2,
97                                    (sin(c.x) + 1.0) / 2,
98                                    1.0);
99                 }
100             "#
101         }).unwrap();
102 }
103
104 fn solid_fill_program(display: &glium::Display) -> glium::Program {
105     let vertex_shader_src = r#"
106         #version 140
107         in vec3 position;
108         uniform mat4 perspective;
109         uniform mat4 view;
110         uniform mat4 model;
111
112         void main() {
113             mat4 modelview = view * model;
114             gl_Position = perspective * modelview * vec4(position, 1.0);
115         }
116     "#;
117
118     let fragment_shader_src = r#"
119         #version 140
120
121         out vec4 color;
122
123         void main() {
124             color = vec4(1.0, 1.0, 1.0, 1.0);
125         }
126     "#;
127
128     return glium::Program::from_source(display,
129                                        vertex_shader_src,
130                                        fragment_shader_src,
131                                        None).unwrap();
132 }
133
134 fn bounding_box<U>(display: &glium::Display,
135                    frame: &mut glium::Frame,
136                    program: &glium::Program,
137                    uniforms: &U,
138                    cube: &Cube) where U: glium::uniforms::Uniforms {
139
140     #[derive(Copy, Clone)]
141     struct Vertex { position: [f32; 3] }
142     implement_vertex!(Vertex, position);
143
144     let cube = [
145         Vertex { position: [cube.xmin, cube.ymin, cube.zmin] },
146         Vertex { position: [cube.xmax, cube.ymin, cube.zmin] },
147         Vertex { position: [cube.xmax, cube.ymax, cube.zmin] },
148         Vertex { position: [cube.xmin, cube.ymax, cube.zmin] },
149         Vertex { position: [cube.xmin, cube.ymin, cube.zmax] },
150         Vertex { position: [cube.xmax, cube.ymin, cube.zmax] },
151         Vertex { position: [cube.xmax, cube.ymax, cube.zmax] },
152         Vertex { position: [cube.xmin, cube.ymax, cube.zmax] },
153     ];
154     let vb = glium::VertexBuffer::new(display, &cube).unwrap();
155
156     let params = glium::DrawParameters {
157         depth: glium::Depth {
158             test: glium::draw_parameters::DepthTest::IfLess,
159             write: true,
160             ..Default::default()
161         },
162         blend: glium::Blend::alpha_blending(),
163         ..Default::default()
164     };
165
166     let front_indices = IndexBuffer::new(display, PrimitiveType::LineLoop,
167                                          &[0, 1, 2, 3u16]).unwrap();
168     frame.draw(&vb, &front_indices, program, uniforms, &params).unwrap();
169
170     let back_indices = IndexBuffer::new(display, PrimitiveType::LineLoop,
171                                         &[4, 5, 6, 7u16]).unwrap();
172     frame.draw(&vb, &back_indices, program, uniforms, &params).unwrap();
173
174     let sides_indices = IndexBuffer::new(display, PrimitiveType::LinesList,
175                                          &[0, 4, 1, 5, 2, 6, 3, 7u16]).unwrap();
176     frame.draw(&vb, &sides_indices, program, uniforms, &params).unwrap();
177 }
178
179 fn mandel<U>(display: &glium::Display,
180           frame: &mut glium::Frame,
181           program: &glium::Program,
182           uniforms: &U,
183           bounds: &Cube,
184           z: [f32; 2]) where U: glium::uniforms::Uniforms {
185
186     #[derive(Copy, Clone)]
187     struct Vertex {
188         position: [f32; 3],
189         color: [f32; 3],
190     }
191     implement_vertex!(Vertex, position, color);
192
193     let xmin = bounds.xmin;
194     let xmax = bounds.xmax;
195     let ymin = bounds.ymin;
196     let ymax = bounds.ymax;
197
198     let width = xmax - xmin;
199     let height = ymax - ymin;
200     let xres: usize = 1;
201     let yres: usize = 1;
202     let xstep = width / (xres as f32);
203     let ystep = height / (yres as f32);
204     let vb_size = (xres * 2 + 4) * yres;
205     let mut v : Vec<Vertex> = Vec::with_capacity(vb_size);
206     v.resize(vb_size, Vertex { position: [0.0, 0.0, -1.0], color: [0.0, 0.0, 0.0] });
207     let mut i: usize = 0;
208     let mut vy = ymin;
209     let vz = z[1];
210     for _ in 0..yres {
211         let mut vx = xmin;
212         let c = [0.0, 0.0, 1.0];
213         v[i] = Vertex { position: [vx, vy+ystep, vz], color: c }; i += 1;
214         v[i] = Vertex { position: [vx, vy,       vz], color: c }; i += 1;
215         for _ in 0..xres {
216             //let c = mand(vx, vy);
217             v[i] = Vertex { position: [vx+xstep, vy+ystep, vz], color: c }; i += 1;
218             v[i] = Vertex { position: [vx+xstep, vy,       vz], color: c }; i += 1;
219             vx += xstep;
220         }
221         v[i] = Vertex { position: [vx,   vy, vz], color: c }; i += 1;
222         v[i] = Vertex { position: [xmin, vy, vz], color: c }; i += 1;
223         vy += ystep;
224     }
225
226     //let vb = glium::VertexBuffer::empty_persistent(display, width*height*3).unwrap();
227     let vb = glium::VertexBuffer::new(display, &v).unwrap();
228
229     let indices = glium::index::NoIndices(glium::index::PrimitiveType::TriangleStrip);
230     //let indices = glium::index::NoIndices(glium::index::PrimitiveType::LineStrip);
231     //let indices = glium::IndexBuffer::new(display, PrimitiveType::TrianglesList,
232     //                                      &[0u16, 1, 2]).unwrap();
233
234     let params = glium::DrawParameters {
235         depth: glium::Depth {
236             test: glium::draw_parameters::DepthTest::IfLess,
237             write: true,
238             ..Default::default()
239         },
240         blend: glium::Blend::alpha_blending(),
241         ..Default::default()
242     };
243
244     frame.draw(&vb, &indices, program, uniforms, &params).unwrap();
245 }
246
247 fn mandelwow(display: &glium::Display,
248              mut frame: &mut glium::Frame,
249              program: &glium::Program,
250              model: [[f32; 4]; 4],
251              camera: &support::camera::CameraState,
252              bounds: &Cube,
253              mandel_w: f32) {
254     let mut z0 = [mandel_w, 0f32];
255     let zres = 50;
256     let zmin = bounds.zmin;
257     let zmax = bounds.zmax;
258     let zstep = (zmax - zmin) / zres as f32;
259     let mut zy = zmin;
260     for _ in 0..zres {
261         z0[1] = zy;
262         zy += zstep;
263
264         let uniforms = uniform! {
265             z0: z0,
266             model: model,
267             view:  camera.get_view(),
268             perspective: camera.get_perspective(),
269         };
270
271         mandel(&display, &mut frame, &program, &uniforms, bounds, z0);
272     }
273 }
274
275 fn main() {
276     sound::start();
277
278     let display = glium::glutin::WindowBuilder::new()
279         //.with_dimensions(1024, 768)
280         .with_fullscreen(glutin::get_primary_monitor())
281         .with_depth_buffer(24)
282         .with_vsync()
283         .with_title(format!("MandelWow"))
284         .build_glium()
285         .unwrap();
286
287     let program = mandelwow_program(&display);
288     let bounding_box_program = solid_fill_program(&display);
289
290     let mut camera = support::camera::CameraState::new();
291     let mut t: f32 = 0.0;
292     let mut pause = false;
293     let mut bounding_box_enabled = true;
294     let mut fullscreen = true;
295
296     support::start_loop(|| {
297         camera.update();
298
299         if !pause {
300             // Increment time
301             t += 0.01;
302         }
303
304         // These are the bounds of the 3D Mandelwow section which we render in 3-space.
305         let bounds = Cube {
306             xmin: -2.0,
307             xmax:  0.7,
308             ymin: -1.0,
309             ymax:  1.0,
310             zmin: -1.2,
311             zmax:  1.2,
312         };
313
314         // Vary the wow factor to slice the Mandelwow along its 4th dimension.
315         let wmin = -0.8;
316         let wmax =  0.8;
317         let wsize = wmax - wmin;
318         let wow = (((t * 0.7).sin() + 1.0) / 2.0) * wsize + wmin;
319
320         //println!("t={} w={:?} camera={:?}", t, w, camera.get_pos());
321
322         let mut frame = display.draw();
323         frame.clear_color_and_depth((0.0, 0.0, 0.0, 1.0), 1.0);
324
325         let z_trans = -2.0;  // Send the model back a little bit so it fits the screen.
326         let model = [
327             [ t.cos(),  t.sin(),  0.0,     0.0],
328             [-t.sin(),  t.cos(),  0.0,     0.0],
329             [     0.0,  0.0,      1.0,     0.0],
330             [     0.0,  0.0,      z_trans, 1.0f32]
331         ];
332
333         // Draw the bounding box before the fractal, when the Z-buffer is still clear,
334         // so the lines behind the semi-translucent areas will be drawn.
335         if bounding_box_enabled {
336             let uniforms = uniform! {
337                 model: model,
338                 view:  camera.get_view(),
339                 perspective: camera.get_perspective(),
340             };
341             bounding_box(&display, &mut frame, &bounding_box_program, &uniforms, &bounds);
342         }
343
344         mandelwow(&display, &mut frame, &program, model, &camera, &bounds, wow);
345         frame.finish().unwrap();
346
347         for ev in display.poll_events() {
348             match ev {
349                 glium::glutin::Event::Closed |
350                 KeyboardInput(Pressed, _, Some(VirtualKeyCode::Escape)) |
351                 KeyboardInput(Pressed, _, Some(VirtualKeyCode::Q)) => {
352                     return support::Action::Stop
353                 },
354                 KeyboardInput(Pressed, _, Some(VirtualKeyCode::B)) => {
355                     bounding_box_enabled ^= true;
356                 },
357                 KeyboardInput(Pressed, _, Some(VirtualKeyCode::F)) => {
358                     fullscreen ^= true;
359                     if fullscreen {
360                         glutin::WindowBuilder::new()
361                             .with_fullscreen(glutin::get_primary_monitor())
362                             .rebuild_glium(&display).unwrap();
363                     } else {
364                         glutin::WindowBuilder::new()
365                             .rebuild_glium(&display).unwrap();
366                     }
367                 },
368                 KeyboardInput(Pressed, _, Some(VirtualKeyCode::P)) => {
369                     pause ^= true;
370                 },
371                 KeyboardInput(Pressed, _, Some(VirtualKeyCode::PageUp)) => {
372                     t += 0.01;
373                 },
374                 KeyboardInput(Pressed, _, Some(VirtualKeyCode::PageDown)) => {
375                     t -= 0.01;
376                 },
377                 ev => camera.process_input(&ev),
378             }
379         }
380
381         support::Action::Continue
382     });
383
384 }