1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
use math;
use math::*;
use ::{node, Node,NodeT};
use window;

#[derive(Clone)]
pub struct Camera{
    node: Node,
    view: Mat4,
    projection: Mat4,
    proj_view: Mat4,
    aspect_ratio: f32,
    znear: f32,
    zfar: f32,
    fov: Deg<f32>,
    at: Pnt3,
    up: Unit<Vec3>,
}

pub struct Builder{
    eye: Pnt3,
    look_at: Pnt3,
    fov: Deg<f32>,
    aspect_ratio: f32,
    znear_far:  Option<(f32,f32)>,
    up: Unit<Vec3>,
    do_roll: bool,
}

impl Builder{
    pub fn new(aspect_ratio: f32) -> Builder{
        Builder{
           eye: math::origin(),
           look_at: math::pnt3(0., 0., -1.),
           fov: Deg(60f32),
           aspect_ratio: aspect_ratio,
           znear_far:  None,
           up: Unit::new_unchecked(Vec3::y()),
           do_roll: false,
       }
    }


    /// Creates a camera Builder using a window to extract the needed info
    ///
    /// Takes event_stream and viewport from the window passed as parameter
    pub fn from_window(window: &mut window::WindowT) -> Builder{
        Builder::new(window.aspect_ratio())
    }

    pub fn clip_planes(&mut self, znear: f32, zfar: f32) -> &mut Builder{
        self.znear_far = Some((znear, zfar));
        self
    }

    pub fn up_axis(&mut self, up: Unit<Vec3>) -> &mut Builder{
        self.up = up;
        self
    }

    pub fn position(&mut self, pos: Pnt3) -> &mut Builder{
        self.eye = pos;
        self
    }

    pub fn look_at(&mut self, target: Pnt3) -> &mut Builder{
        self.look_at = target;
        self
    }

    pub fn fov(&mut self, fov: Deg<f32>) -> &mut Builder{
        self.fov = fov;
        self
    }

    pub fn aspect_ratio(&mut self, aspect_ratio: f32) -> &mut Builder{
        self.aspect_ratio = aspect_ratio;
        self
    }

    pub fn do_roll(&mut self, do_roll: bool) -> &mut Builder{
        self.do_roll = do_roll;
        self
    }

    pub fn create(&self) -> Camera{
        if let Some((near, far)) = self.znear_far{
            Camera::new_with_frustrum(self.eye, self.look_at, self.up, self.fov, self.aspect_ratio, near, far)
        }else{
            Camera::new(self.eye, self.look_at, self.up, self.fov, self.aspect_ratio)
        }
    }
}

impl Camera{
    //TODO: Add up vector, probably builder
    /// Create a new camera.
    pub fn new(eye: Pnt3, look_at: Pnt3, up: Unit<Vec3>, fov: Deg<f32>, aspect_ratio: f32) -> Camera {
        let half_fov = fov/2.0;
        let tan = half_fov.tan();
        let dist = math::norm(&(look_at-eye)) / tan;

        let znear = dist / 100.0;
        let zfar = dist * 10.0;

        Camera::new_with_frustrum(eye, look_at, up, fov, aspect_ratio, znear, zfar)
    }

    /// Creates a new camera from frustrum values.
    pub fn new_with_frustrum(eye:     Pnt3,
                             look_at: Pnt3,
                             up:      Unit<Vec3>,
                             fov:     Deg<f32>,
                             aspect_ratio: f32,
                             znear:  f32,
                             zfar:   f32) -> Camera {

        let node = Node::new_look_at(eye, look_at, *up);

        let view = node.inv_global_transformation();

        let mut camera = Camera {
            fov:             fov.to_deg(),
            znear:           znear,
            zfar:            zfar,
            view:            view,
            aspect_ratio:    aspect_ratio,
            proj_view:       one(),
            projection:      one(),
            at:              look_at,
            up:              up,
            node:            node
        };
        camera.refresh_projection();
        camera
    }

    pub fn projection(&self) -> Mat4{
        self.projection
    }

    pub fn view(&self) -> Mat4{
        self.view
    }

    pub fn proj_view(&self) -> Mat4{
        self.proj_view
    }

    pub fn fov(&self) -> Deg<f32>{
        self.fov
    }

    pub fn set_fov(&mut self, fov: Deg<f32>){
        self.fov = fov;
        self.refresh_projection();
    }

    pub fn near_far_clip(&self) -> (f32,f32){
        (self.znear, self.zfar)
    }

    pub fn set_near(&mut self, near: f32){
        self.znear = near;
        self.refresh_projection();
    }

    pub fn set_far(&mut self, far: f32){
        self.zfar = far;
        self.refresh_projection();
    }

    pub fn set_near_far(&mut self, near: f32, far: f32){
        self.znear = near;
        self.zfar = far;
        self.refresh_projection();
    }

    pub fn set_aspect_ratio(&mut self, aspect: f32){
        self.aspect_ratio = aspect;
    }

    fn refresh_projection(&mut self){
        let proj = Perspective3::new(self.aspect_ratio, self.fov.to_rad().value(), self.znear, self.zfar);
        self.projection = *proj.as_matrix();
        self.proj_view = self.projection * self.view;
    }
}

impl NodeT for Camera{
    fn node(&self) -> &Node{
        &self.node
    }

    fn node_mut(&mut self) -> &mut Node{
        &mut self.node
    }

    fn set_scale(&mut self, _scale: &Vec3){
        // camera can't be scaled
        // TODO: Node without scale so this method is not even available
    }

    fn update_with_parent_flags(&mut self, parent: Option<&Node>, flags: node::Flags) -> bool {
        if self.node.update_with_parent_flags(parent, flags) {
            self.view = self.node.global_transformation().fast_orthonormal_inverse();
            self.proj_view = self.projection * self.view;
            true
        }else{
            false
        }
    }
}

pub trait CameraT: NodeT{
    fn projection(&self) -> Mat4;

    fn view(&self) -> Mat4;

    fn proj_view(&self) -> Mat4;

    fn fov(&self) -> Deg<f32>;

    fn set_fov(&mut self, fov: Deg<f32>);

    fn near_far_clip(&self) -> (f32,f32);

    fn set_near(&mut self, near: f32);

    fn set_far(&mut self, far: f32);

    fn set_near_far(&mut self, near: f32, far: f32);

    fn set_aspect_ratio(&mut self, aspect: f32);
}

impl CameraT for Camera{
    fn projection(&self) -> Mat4{
        self.projection
    }

    fn view(&self) -> Mat4{
        self.view
    }

	fn proj_view(&self) -> Mat4{
        self.proj_view
    }

    fn fov(&self) -> Deg<f32>{
        self.fov
    }

    fn set_fov(&mut self, fov: Deg<f32>){
        self.fov = fov;
        self.refresh_projection();
    }

    fn near_far_clip(&self) -> (f32,f32){
        (self.znear, self.zfar)
    }

    fn set_near(&mut self, near: f32){
        self.znear = near;
        self.refresh_projection();
    }

    fn set_far(&mut self, far: f32){
        self.zfar = far;
        self.refresh_projection();
    }

    fn set_near_far(&mut self, near: f32, far: f32){
        self.znear = near;
        self.zfar = far;
        self.refresh_projection();
    }

    fn set_aspect_ratio(&mut self, aspect: f32){
        self.aspect_ratio = aspect;
    }
}

pub mod arcball_camera {
    use math;
    use math::*;
    use ::{node, Node,NodeT};
    use window::events::*;
    use window;
    use events::{self, StreamT};
    use util::ValueCache;
    use std::mem;
    use super::{Camera, CameraT};

    pub struct ArcballCamera{
        camera: Camera,
        target: ValueCache<Pnt3>,
        prev_mouse: Pnt2<f64>,
        mouse_pressed: bool,
        translating: bool,
        window_size: Vec2<i32>,
        window_size_iter: events::IterAsync<'static, Vec2<i32>>,
        prev_camera: Node,
        rolling: bool,
        up: Unit<Vec3>,
        do_roll: bool,
        events: events::IterAsync<'static,window::Event>,
    }

    pub struct Builder{
        events_stream: events::StreamRc<'static,window::Event>,
        window_size: Vec2<i32>,
        eye: Pnt3,
        look_at: Pnt3,
        fov: Deg<f32>,
        aspect_ratio: f32,
        znear_far:  Option<(f32,f32)>,
        up: Unit<Vec3>,
        do_roll: bool,
    }

    impl Builder{
        pub fn new<S: events::StreamT<'static, window::Event>>(events_stream: S,
                window_size: Vec2<i32>) -> Builder{

        Builder{
            events_stream: events_stream.rc(),
            window_size,
            eye: math::origin(),
            look_at: math::pnt3(0., 0., -1.),
            fov: Deg(60f32),
            aspect_ratio: window_size.x as f32 / window_size.y as f32,
            znear_far:  None,
            up: Unit::new_unchecked(Vec3::y()),
            do_roll: false,
        }
        }


        /// Creates an arcball camera Builder using a window to extract the needed info
        ///
        /// Takes event_stream and viewport from the window passed as parameter
        pub fn from_window(window: &mut window::WindowT) -> Builder{
            Builder::new(window.event_stream(), window.size())
        }

        pub fn clip_planes(mut self, znear: f32, zfar: f32) -> Builder{
            self.znear_far = Some((znear, zfar));
            self
        }

        pub fn up_axis(mut self, up: Unit<Vec3>) -> Builder{
            self.up = up;
            self
        }

        pub fn position(mut self, pos: Pnt3) -> Builder{
            self.eye = pos;
            self
        }

        pub fn look_at(mut self, target: Pnt3) -> Builder{
            self.look_at = target;
            self
        }

        pub fn fov(mut self, fov: Deg<f32>) -> Builder{
            self.fov = fov;
            self
        }

        pub fn aspect_ratio(mut self, aspect_ratio: f32) -> Builder{
            self.aspect_ratio = aspect_ratio;
            self
        }

        pub fn do_roll(mut self, do_roll: bool) -> Builder{
            self.do_roll = do_roll;
            self
        }

        pub fn create(self) -> ArcballCamera{
            let camera = if let Some((near, far)) = self.znear_far{
                Camera::new_with_frustrum(self.eye, self.look_at, self.up, self.fov, self.aspect_ratio, near, far)
            }else{
                Camera::new(self.eye, self.look_at, self.up, self.fov, self.aspect_ratio)
            };

            ArcballCamera{
                camera: camera,
                target: ValueCache::new(self.look_at),
                prev_mouse: math::origin(),
                mouse_pressed: false,
                translating: false,
                prev_camera:  Node::identity(),
                window_size: self.window_size,
                window_size_iter: self.events_stream.clone().window().resized().iter_async(),
                rolling: false,
                up: self.up,
                do_roll: self.do_roll,
                events: self.events_stream.iter_async(),
            }
        }
    }

    impl ArcballCamera{
        pub fn target(&self) -> Pnt3{
            *self.target
        }

        pub fn set_target(&mut self, target: &Pnt3){
            *self.target = *target;
        }

        pub fn camera(&self) -> &Camera{
            &self.camera
        }

        pub fn update(&mut self) -> bool {
            self.update_with_parent(None)
        }

        fn poll_window_events<'a>(&'a mut self){
            if let Some(window_size) = self.window_size_iter.by_ref().last(){
                self.window_size = window_size;
            }

            let events: &mut events::IterAsync<'a, window::Event> = unsafe{ mem::transmute(self.events.by_ref()) };
            for event in events {
                match event{
                    window::Event::MousePressed{pos,button,..} => self.mouse_pressed(&pos,button),
                    window::Event::MouseReleased{pos,button,..} => self.mouse_released(&pos,button),
                    window::Event::MouseMoved{pos} => self.mouse_moved(&pos),
                    window::Event::Scroll{scroll} => self.scroll(&scroll),
                    _ => {}
                }
            }
        }

        fn mouse_moved(&mut self, pos: &math::Pnt2<f64>){
            if self.mouse_pressed{
                let diff = *pos - self.prev_mouse;
                let yaw  = Rad(-diff.x as f32 * 0.005);
                let pitch = Rad(-diff.y as f32 * 0.005);
                /*let v_begin = get_arcball_vector(&self.prev_mouse);
                let v_end = get_arcball_vector(&(self.prev_mouse + diff * 0.5f64));
                let perp = rin::math::cross(&v_begin,&v_end);
                let dot = rin::math::dot(&v_begin,&v_end);
                //let angle = dot.min(1.0).acos() * 0.0001;
                //let dot = angle.cos();
                let rot = rin::math::Quat::new(perp.x as f32,perp.y as f32,perp.z as f32, dot as f32);
                self.model_matrix = rin::math::to_homogeneous(&rin::math::to_homogeneous(&rot)) * self.prev_model_matrix;*/

                let rot = if self.rolling{
                    let screen_coords = vec2((pos.x as f32 - self.window_size.x as f32*0.5)/self.window_size.y as f32 * 2.0,
                                        pos.y as f32/self.window_size.y as f32 * 2.0 - 1.0);
                    let prev_screen_coords = vec2((self.prev_mouse.x as f32 - self.window_size.x as f32*0.5)/self.window_size.y as f32 * 2.0,
                                                self.prev_mouse.y as f32/self.window_size.y as f32 * 2.0 - 1.0);
                    math::UnitQuat::from_axis_angle(&self.prev_camera.z_axis(), math::atan2(&prev_screen_coords,&screen_coords).value())
                }else{
                    math::UnitQuat::from_axis_angle(&self.up, yaw.value()) * math::UnitQuat::from_axis_angle(&self.prev_camera.x_axis(), pitch.value())
                };

                let orbit_radius = self.prev_camera.position() - *self.target;

                let rotated = rot * orbit_radius;

                let new_position = self.target.to_vec() + rotated;

                self.camera.set_position(new_position.as_pnt());
                self.camera.set_orientation(&(rot * self.prev_camera.orientation()));
                //self.camera.look_at(&self.target, &self.up);

                if !self.rolling && pitch.abs() > Deg(90f32).to_rad(){
                    self.prev_mouse = *pos;
                    self.prev_camera = self.camera.node().clone();
                    //self.prev_model_matrix = self.model_matrix;
                    //self.prev_camera.set_position(&self.camera.node().position());
                    //self.prev_camera.set_orientation(&self.camera.node().orientation());
                    //self.prev_camera.set_scale(&self.camera.node().scale());
                }
            }
            if self.translating{
                let new_pos = *pos - self.prev_mouse;
                let axis_x = self.camera.x_axis().unwrap();
                let axis_y = self.camera.y_axis().unwrap();
                let max_distance = norm(&(*self.target - self.camera.position()));
                let ratio_x = max_distance/self.window_size.x as f32;
                let ratio_y = max_distance/self.window_size.y as f32;
                let translation = axis_x * -new_pos.x as f32 * ratio_x + axis_y * new_pos.y as f32 * ratio_y;
                self.camera.translate(&translation);
                *self.target += translation;
                self.prev_mouse = *pos;
            }
        }

        fn mouse_pressed(&mut self, pos: &math::Pnt2<f64>, button: window::MouseButton){
            match button{
                window::MouseButton::Left => {
                    self.prev_mouse = *pos;
                    self.mouse_pressed = true;
                    //self.prev_model_matrix = self.model_matrix;
                    self.prev_camera = self.camera.node().clone();
                    let screen_coords = vec2((pos.x as f32 - self.window_size.x as f32*0.5)/self.window_size.y as f32 * 2.0,
                                            pos.y as f32/self.window_size.y as f32 * 2.0 - 1.0);

                    if self.do_roll && math::norm_squared(&screen_coords) > 1.0{
                        self.rolling = true;
                    }else{
                        self.rolling = false;
                    }
                }
                window::MouseButton::Middle => {
                    self.prev_mouse = *pos;
                    self.translating = true;
                }
                _=>{}
            }
        }

        fn mouse_released(&mut self, _pos: &math::Pnt2<f64>, button: window::MouseButton){
            match button{
                window::MouseButton::Left => {
                    self.mouse_pressed = false;
                }
                window::MouseButton::Middle => {
                    self.translating = false;
                }
                _=>{}
            }
        }

        fn scroll(&mut self, scroll: &math::Vec2<f64>){
            let dir = norm(&(*self.target - self.camera.position())) * self.camera.z_axis().unwrap();
            self.camera.translate(&(dir * (scroll.y as f32 * 0.1)));
        }
    }

    impl CameraT for ArcballCamera{
        fn projection(&self) -> Mat4{
            self.camera.projection()
        }

        fn view(&self) -> Mat4{
            self.camera.view()
        }

        fn proj_view(&self) -> Mat4{
            self.camera.proj_view()
        }

        fn fov(&self) -> Deg<f32>{
            self.camera.fov()
        }

        fn set_fov(&mut self, fov: Deg<f32>){
            self.camera.set_fov(fov);
        }

        fn near_far_clip(&self) -> (f32,f32){
            self.camera.near_far_clip()
        }

        fn set_near(&mut self, near: f32){
            self.camera.set_near(near);
        }

        fn set_far(&mut self, far: f32){
            self.camera.set_far(far);
        }

        fn set_near_far(&mut self, near: f32, far: f32){
            self.camera.set_near_far(near,far);
        }

        fn set_aspect_ratio(&mut self, aspect: f32){
            self.camera.aspect_ratio = aspect;
        }
    }

    impl NodeT for ArcballCamera{
        fn node(&self) -> &Node{
            self.camera.node()
        }

        fn node_mut(&mut self) -> &mut Node{
            self.camera.node_mut()
        }

        fn update_with_parent_flags(&mut self, parent: Option<&Node>, flags: node::Flags) -> bool{
            self.poll_window_events();
            if self.target.has_changed(){
                self.camera.look_at(&self.target, &self.up);
            }
            self.target.update();
            self.camera.update_with_parent_flags(parent, flags)
        }
    }


    /*fn get_arcball_vector(pos: &rin::math::Vec2<f64>) -> rin::math::Vec3<f64>{
        let mut p = vec3(pos.x/rin::window::width() as f64 * 2.0 - 1.0,
                        pos.y/rin::window::height() as f64 * 2.0 - 1.0,
                        0.0);
        p.y = -p.y;
        let op_squared = p.x * p.x + p.y * p.y;
        if op_squared <= 1.0{
            p.z = (1.0-op_squared).sqrt();
        }else{
            p = rin::math::normalize(&p);
        }

        p
    }*/
}