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
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */

use crate::SurfmanGL;
use crate::SurfmanLayerManager;

use euclid::Angle;
use euclid::Point2D;
use euclid::Rect;
use euclid::RigidTransform3D;
use euclid::Rotation3D;
use euclid::Size2D;
use euclid::Transform3D;
use euclid::UnknownUnit;
use euclid::Vector3D;

use sparkle::gl;
use sparkle::gl::GLuint;
use sparkle::gl::Gl;

use std::ffi::c_void;
use std::rc::Rc;

use surfman::Adapter;
use surfman::Connection;
use surfman::Context as SurfmanContext;
use surfman::ContextAttributes;
use surfman::Device as SurfmanDevice;
use surfman::GLApi;
use surfman::NativeWidget;
use surfman::SurfaceAccess;
use surfman::SurfaceType;

use surfman_chains::SwapChain;
use surfman_chains::SwapChainAPI;
use surfman_chains::SwapChains;
use surfman_chains::SwapChainsAPI;

use webxr_api::util::ClipPlanes;
use webxr_api::ContextId;
use webxr_api::DeviceAPI;
use webxr_api::DiscoveryAPI;
use webxr_api::Display;
use webxr_api::Error;
use webxr_api::Event;
use webxr_api::EventBuffer;
use webxr_api::Floor;
use webxr_api::Frame;
use webxr_api::InputSource;
use webxr_api::LayerGrandManager;
use webxr_api::LayerId;
use webxr_api::LayerInit;
use webxr_api::LayerManager;
use webxr_api::Native;
use webxr_api::Quitter;
use webxr_api::Sender;
use webxr_api::Session;
use webxr_api::SessionBuilder;
use webxr_api::SessionInit;
use webxr_api::SessionMode;
use webxr_api::SomeEye;
use webxr_api::View;
use webxr_api::Viewer;
use webxr_api::ViewerPose;
use webxr_api::Viewport;
use webxr_api::Viewports;
use webxr_api::Views;
use webxr_api::CUBE_BACK;
use webxr_api::CUBE_BOTTOM;
use webxr_api::CUBE_LEFT;
use webxr_api::CUBE_RIGHT;
use webxr_api::CUBE_TOP;
use webxr_api::LEFT_EYE;
use webxr_api::RIGHT_EYE;
use webxr_api::VIEWER;

// How far off the ground are the viewer's eyes?
const HEIGHT: f32 = 1.0;

// What is half the vertical field of view?
const FOV_UP: f32 = 45.0;

// Some guesstimated numbers, hopefully it doesn't matter if these are off by a bit.

// What the distance between the viewer's eyes?
const INTER_PUPILLARY_DISTANCE: f32 = 0.06;

// What is the size of a pixel?
const PIXELS_PER_METRE: f32 = 6000.0;

pub trait GlWindow {
    fn get_render_target(
        &self,
        device: &mut SurfmanDevice,
        context: &mut SurfmanContext,
    ) -> GlWindowRenderTarget;
    fn get_rotation(&self) -> Rotation3D<f32, UnknownUnit, UnknownUnit>;
    fn get_translation(&self) -> Vector3D<f32, UnknownUnit>;

    fn get_mode(&self) -> GlWindowMode {
        GlWindowMode::Blit
    }
}

#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum GlWindowMode {
    Blit,
    StereoLeftRight,
    StereoRedCyan,
    Cubemap,
    Spherical,
}

pub enum GlWindowRenderTarget {
    NativeWidget(NativeWidget),
    SwapChain(SwapChain<SurfmanDevice>),
}

pub struct GlWindowDiscovery {
    connection: Connection,
    adapter: Adapter,
    context_attributes: ContextAttributes,
    factory: Box<dyn Fn() -> Result<Box<dyn GlWindow>, ()>>,
}

impl GlWindowDiscovery {
    pub fn new(
        connection: Connection,
        adapter: Adapter,
        context_attributes: ContextAttributes,
        factory: Box<dyn Fn() -> Result<Box<dyn GlWindow>, ()>>,
    ) -> GlWindowDiscovery {
        GlWindowDiscovery {
            connection,
            adapter,
            context_attributes,
            factory,
        }
    }
}

impl DiscoveryAPI<SurfmanGL> for GlWindowDiscovery {
    fn request_session(
        &mut self,
        mode: SessionMode,
        init: &SessionInit,
        xr: SessionBuilder<SurfmanGL>,
    ) -> Result<Session, Error> {
        if self.supports_session(mode) {
            let granted_features = init.validate(mode, &["local-floor".into()])?;
            let connection = self.connection.clone();
            let adapter = self.adapter.clone();
            let context_attributes = self.context_attributes.clone();
            let window = (self.factory)().or(Err(Error::NoMatchingDevice))?;
            xr.run_on_main_thread(move |grand_manager| {
                GlWindowDevice::new(
                    connection,
                    adapter,
                    context_attributes,
                    window,
                    granted_features,
                    grand_manager,
                )
            })
        } else {
            Err(Error::NoMatchingDevice)
        }
    }

    fn supports_session(&self, mode: SessionMode) -> bool {
        mode == SessionMode::ImmersiveVR || mode == SessionMode::ImmersiveAR
    }
}

pub struct GlWindowDevice {
    device: SurfmanDevice,
    context: SurfmanContext,
    gl: Rc<Gl>,
    window: Box<dyn GlWindow>,
    grand_manager: LayerGrandManager<SurfmanGL>,
    layer_manager: Option<LayerManager>,
    target_swap_chain: Option<SwapChain<SurfmanDevice>>,
    swap_chains: SwapChains<LayerId, SurfmanDevice>,
    read_fbo: GLuint,
    events: EventBuffer,
    clip_planes: ClipPlanes,
    granted_features: Vec<String>,
    shader: Option<GlWindowShader>,
}

impl DeviceAPI for GlWindowDevice {
    fn floor_transform(&self) -> Option<RigidTransform3D<f32, Native, Floor>> {
        let translation = Vector3D::new(0.0, HEIGHT, 0.0);
        Some(RigidTransform3D::from_translation(translation))
    }

    fn viewports(&self) -> Viewports {
        let size = self.viewport_size();
        let viewports = match self.window.get_mode() {
            GlWindowMode::Cubemap | GlWindowMode::Spherical => vec![
                Rect::new(Point2D::new(size.width * 1, size.height * 1), size),
                Rect::new(Point2D::new(size.width * 0, size.height * 1), size),
                Rect::new(Point2D::new(size.width * 2, size.height * 1), size),
                Rect::new(Point2D::new(size.width * 2, size.height * 0), size),
                Rect::new(Point2D::new(size.width * 0, size.height * 0), size),
                Rect::new(Point2D::new(size.width * 1, size.height * 0), size),
            ],
            GlWindowMode::Blit | GlWindowMode::StereoLeftRight | GlWindowMode::StereoRedCyan => {
                vec![
                    Rect::new(Point2D::default(), size),
                    Rect::new(Point2D::new(size.width, 0), size),
                ]
            }
        };
        Viewports { viewports }
    }

    fn create_layer(&mut self, context_id: ContextId, init: LayerInit) -> Result<LayerId, Error> {
        self.layer_manager()?.create_layer(context_id, init)
    }

    fn destroy_layer(&mut self, context_id: ContextId, layer_id: LayerId) {
        self.layer_manager()
            .unwrap()
            .destroy_layer(context_id, layer_id)
    }

    fn begin_animation_frame(&mut self, layers: &[(ContextId, LayerId)]) -> Option<Frame> {
        log::debug!("Begin animation frame for layers {:?}", layers);
        let time_ns = time::precise_time_ns();
        let translation = Vector3D::from_untyped(self.window.get_translation());
        let translation: RigidTransform3D<_, _, Native> =
            RigidTransform3D::from_translation(translation);
        let rotation = Rotation3D::from_untyped(&self.window.get_rotation());
        let rotation = RigidTransform3D::from_rotation(rotation);
        let transform = translation.post_transform(&rotation);
        let sub_images = self.layer_manager().ok()?.begin_frame(layers).ok()?;
        Some(Frame {
            pose: Some(ViewerPose {
                transform,
                views: self.views(transform),
            }),
            inputs: vec![],
            events: vec![],
            time_ns,
            sub_images,
            sent_time: 0,
            hit_test_results: vec![],
        })
    }

    fn end_animation_frame(&mut self, layers: &[(ContextId, LayerId)]) {
        log::debug!("End animation frame for layers {:?}", layers);
        self.device.make_context_current(&self.context).unwrap();
        debug_assert_eq!(self.gl.get_error(), gl::NO_ERROR);

        let _ = self.layer_manager().unwrap().end_frame(layers);

        let window_size = self.window_size();
        let viewport_size = self.viewport_size();

        let framebuffer_object = self
            .device
            .context_surface_info(&self.context)
            .unwrap()
            .map(|info| info.framebuffer_object)
            .unwrap_or(0);
        self.gl
            .bind_framebuffer(gl::FRAMEBUFFER, framebuffer_object);
        debug_assert_eq!(
            (
                self.gl.get_error(),
                self.gl.check_framebuffer_status(gl::FRAMEBUFFER)
            ),
            (gl::NO_ERROR, gl::FRAMEBUFFER_COMPLETE)
        );

        self.gl.clear_color(0.2, 0.3, 0.3, 1.0);
        self.gl.clear(gl::COLOR_BUFFER_BIT);
        debug_assert_eq!(self.gl.get_error(), gl::NO_ERROR);

        for &(_, layer_id) in layers {
            let swap_chain = match self.swap_chains.get(layer_id) {
                Some(swap_chain) => swap_chain,
                None => continue,
            };
            let surface = match swap_chain.take_surface() {
                Some(surface) => surface,
                None => return,
            };
            let texture_size = self.device.surface_info(&surface).size;
            let surface_texture = self
                .device
                .create_surface_texture(&mut self.context, surface)
                .unwrap();
            let texture_id = self.device.surface_texture_object(&surface_texture);
            let texture_target = self.device.surface_gl_texture_target();
            log::debug!("Presenting texture {}", texture_id);

            if let Some(ref shader) = self.shader {
                shader.draw_texture(
                    texture_id,
                    texture_target,
                    texture_size,
                    viewport_size,
                    window_size,
                );
            } else {
                self.blit_texture(texture_id, texture_target, texture_size, window_size);
            }
            debug_assert_eq!(self.gl.get_error(), gl::NO_ERROR);

            let surface = self
                .device
                .destroy_surface_texture(&mut self.context, surface_texture)
                .unwrap();
            swap_chain.recycle_surface(surface);
        }

        match self.target_swap_chain.as_ref() {
            Some(target_swap_chain) => {
                // Rendering to a surfman swap chain
                target_swap_chain
                    .swap_buffers(
                        &mut self.device,
                        &mut self.context,
                        surfman_chains::PreserveBuffer::No,
                    )
                    .unwrap();
            }
            None => {
                // Rendering to a native widget
                let mut surface = self
                    .device
                    .unbind_surface_from_context(&mut self.context)
                    .unwrap()
                    .unwrap();
                self.device
                    .present_surface(&self.context, &mut surface)
                    .unwrap();
                self.device
                    .bind_surface_to_context(&mut self.context, surface)
                    .unwrap();
            }
        }

        debug_assert_eq!(self.gl.get_error(), gl::NO_ERROR);
    }

    fn initial_inputs(&self) -> Vec<InputSource> {
        vec![]
    }

    fn set_event_dest(&mut self, dest: Sender<Event>) {
        self.events.upgrade(dest)
    }

    fn quit(&mut self) {
        self.events.callback(Event::SessionEnd);
    }

    fn set_quitter(&mut self, _: Quitter) {
        // Glwindow currently doesn't have any way to end its own session
        // XXXManishearth add something for this that listens for the window
        // being closed
    }

    fn update_clip_planes(&mut self, near: f32, far: f32) {
        self.clip_planes.update(near, far)
    }

    fn granted_features(&self) -> &[String] {
        &self.granted_features
    }
}

impl Drop for GlWindowDevice {
    fn drop(&mut self) {
        self.gl.delete_framebuffers(&[self.read_fbo]);
        let _ = self.device.destroy_context(&mut self.context);
    }
}

impl GlWindowDevice {
    fn new(
        connection: Connection,
        adapter: Adapter,
        context_attributes: ContextAttributes,
        window: Box<dyn GlWindow>,
        granted_features: Vec<String>,
        grand_manager: LayerGrandManager<SurfmanGL>,
    ) -> Result<GlWindowDevice, Error> {
        let mut device = connection.create_device(&adapter).unwrap();
        let context_descriptor = device
            .create_context_descriptor(&context_attributes)
            .unwrap();
        let mut context = device.create_context(&context_descriptor, None).unwrap();
        device.make_context_current(&context).unwrap();

        let gl = match device.gl_api() {
            GLApi::GL => Gl::gl_fns(gl::ffi_gl::Gl::load_with(|symbol_name| {
                device.get_proc_address(&context, symbol_name)
            })),
            GLApi::GLES => Gl::gles_fns(gl::ffi_gles::Gles2::load_with(|symbol_name| {
                device.get_proc_address(&context, symbol_name)
            })),
        };

        let target_swap_chain = match window.get_render_target(&mut device, &mut context) {
            GlWindowRenderTarget::NativeWidget(native_widget) => {
                let surface_type = SurfaceType::Widget { native_widget };
                let surface = device
                    .create_surface(&context, SurfaceAccess::GPUOnly, surface_type)
                    .unwrap();
                device
                    .bind_surface_to_context(&mut context, surface)
                    .unwrap();
                None
            }
            GlWindowRenderTarget::SwapChain(target_swap_chain) => {
                debug_assert!(target_swap_chain.is_attached());
                Some(target_swap_chain)
            }
        };

        let read_fbo = gl.gen_framebuffers(1)[0];
        let framebuffer_object = device
            .context_surface_info(&context)
            .unwrap()
            .map(|info| info.framebuffer_object)
            .unwrap_or(0);
        gl.bind_framebuffer(gl::FRAMEBUFFER, framebuffer_object);
        debug_assert_eq!(
            (gl.get_error(), gl.check_framebuffer_status(gl::FRAMEBUFFER)),
            (gl::NO_ERROR, gl::FRAMEBUFFER_COMPLETE)
        );

        let swap_chains = SwapChains::new();
        let layer_manager = None;

        let shader = GlWindowShader::new(gl.clone(), window.get_mode());
        debug_assert_eq!(gl.get_error(), gl::NO_ERROR);

        Ok(GlWindowDevice {
            gl,
            window,
            device,
            context,
            read_fbo,
            swap_chains,
            target_swap_chain,
            grand_manager,
            layer_manager,
            events: Default::default(),
            clip_planes: Default::default(),
            granted_features,
            shader,
        })
    }

    fn blit_texture(
        &self,
        texture_id: GLuint,
        texture_target: GLuint,
        texture_size: Size2D<i32, UnknownUnit>,
        window_size: Size2D<i32, Viewport>,
    ) {
        self.gl
            .bind_framebuffer(gl::READ_FRAMEBUFFER, self.read_fbo);
        self.gl.framebuffer_texture_2d(
            gl::READ_FRAMEBUFFER,
            gl::COLOR_ATTACHMENT0,
            texture_target,
            texture_id,
            0,
        );
        self.gl.blit_framebuffer(
            0,
            0,
            texture_size.width,
            texture_size.height,
            0,
            0,
            window_size.width,
            window_size.height,
            gl::COLOR_BUFFER_BIT,
            gl::NEAREST,
        );
    }

    fn layer_manager(&mut self) -> Result<&mut LayerManager, Error> {
        if let Some(ref mut manager) = self.layer_manager {
            return Ok(manager);
        }
        let swap_chains = self.swap_chains.clone();
        let viewports = self.viewports();
        let layer_manager = self.grand_manager.create_layer_manager(move |_, _| {
            Ok(SurfmanLayerManager::new(viewports, swap_chains))
        })?;
        self.layer_manager = Some(layer_manager);
        Ok(self.layer_manager.as_mut().unwrap())
    }

    fn window_size(&self) -> Size2D<i32, Viewport> {
        let window_size = self
            .device
            .context_surface_info(&self.context)
            .unwrap()
            .unwrap()
            .size
            .to_i32();
        Size2D::from_untyped(window_size)
    }

    fn viewport_size(&self) -> Size2D<i32, Viewport> {
        let window_size = self.window_size();
        match self.window.get_mode() {
            GlWindowMode::StereoRedCyan => {
                // This device has a slightly odd characteristic, which is that anaglyphic stereo
                // renders both eyes to the same surface. If we want the two eyes to be parallel,
                // and to agree at distance infinity, this means gettng the XR content to render some
                // wasted pixels, which are stripped off when we render to the target surface.
                // (The wasted pixels are on the right of the left eye and vice versa.)
                let wasted_pixels = (INTER_PUPILLARY_DISTANCE / PIXELS_PER_METRE) as i32;
                Size2D::new(window_size.width + wasted_pixels, window_size.height)
            }
            GlWindowMode::Cubemap => {
                // Cubemap viewports should be square
                let size = 1.max(window_size.width / 3).max(window_size.height / 2);
                Size2D::new(size, size)
            }
            GlWindowMode::Spherical => {
                // Cubemap viewports should be square
                let size = 1.max(window_size.width / 2).max(window_size.height);
                Size2D::new(size, size)
            }
            GlWindowMode::StereoLeftRight | GlWindowMode::Blit => {
                Size2D::new(window_size.width / 2, window_size.height)
            }
        }
    }

    fn views(&self, viewer: RigidTransform3D<f32, Viewer, Native>) -> Views {
        match self.window.get_mode() {
            GlWindowMode::Cubemap | GlWindowMode::Spherical => Views::Cubemap(
                self.view(viewer, VIEWER),
                self.view(viewer, CUBE_LEFT),
                self.view(viewer, CUBE_RIGHT),
                self.view(viewer, CUBE_TOP),
                self.view(viewer, CUBE_BOTTOM),
                self.view(viewer, CUBE_BACK),
            ),
            GlWindowMode::Blit | GlWindowMode::StereoLeftRight | GlWindowMode::StereoRedCyan => {
                Views::Stereo(self.view(viewer, LEFT_EYE), self.view(viewer, RIGHT_EYE))
            }
        }
    }

    fn view<Eye>(
        &self,
        viewer: RigidTransform3D<f32, Viewer, Native>,
        eye: SomeEye<Eye>,
    ) -> View<Eye> {
        let projection = self.perspective();
        let translation = if eye == RIGHT_EYE {
            Vector3D::new(-INTER_PUPILLARY_DISTANCE / 2.0, 0.0, 0.0)
        } else if eye == LEFT_EYE {
            Vector3D::new(INTER_PUPILLARY_DISTANCE / 2.0, 0.0, 0.0)
        } else {
            Vector3D::zero()
        };
        let rotation = if eye == CUBE_TOP {
            Rotation3D::euler(
                Angle::degrees(270.0),
                Angle::degrees(0.0),
                Angle::degrees(90.0),
            )
        } else if eye == CUBE_BOTTOM {
            Rotation3D::euler(
                Angle::degrees(90.0),
                Angle::degrees(0.0),
                Angle::degrees(90.0),
            )
        } else if eye == CUBE_LEFT {
            Rotation3D::around_y(Angle::degrees(-90.0))
        } else if eye == CUBE_RIGHT {
            Rotation3D::around_y(Angle::degrees(90.0))
        } else if eye == CUBE_BACK {
            Rotation3D::euler(
                Angle::degrees(180.0),
                Angle::degrees(0.0),
                Angle::degrees(90.0),
            )
        } else {
            Rotation3D::identity()
        };
        let transform: RigidTransform3D<f32, Viewer, Eye> =
            RigidTransform3D::new(rotation, translation);
        View {
            transform: viewer.pre_transform(&transform.inverse()),
            projection,
        }
    }

    fn perspective<Eye>(&self) -> Transform3D<f32, Eye, Display> {
        let near = self.clip_planes.near;
        let far = self.clip_planes.far;
        // https://github.com/toji/gl-matrix/blob/bd3307196563fbb331b40fc6ebecbbfcc2a4722c/src/mat4.js#L1271
        let fov_up = match self.window.get_mode() {
            GlWindowMode::Spherical | GlWindowMode::Cubemap => Angle::degrees(45.0),
            GlWindowMode::Blit | GlWindowMode::StereoLeftRight | GlWindowMode::StereoRedCyan => {
                Angle::degrees(FOV_UP)
            }
        };
        let f = 1.0 / fov_up.radians.tan();
        let nf = 1.0 / (near - far);
        let viewport_size = self.viewport_size();
        let aspect = viewport_size.width as f32 / viewport_size.height as f32;

        // Dear rustfmt, This is a 4x4 matrix, please leave it alone. Best, ajeffrey.
        {
            #[rustfmt::skip]
            // Sigh, row-major vs column-major
            return Transform3D::row_major(
                f / aspect, 0.0, 0.0,                   0.0,
                0.0,        f,   0.0,                   0.0,
                0.0,        0.0, (far + near) * nf,     -1.0,
                0.0,        0.0, 2.0 * far * near * nf, 0.0,
            );
        }
    }
}

struct GlWindowShader {
    gl: Rc<Gl>,
    buffer: GLuint,
    vao: GLuint,
    program: GLuint,
    mode: GlWindowMode,
}

const VERTEX_ATTRIBUTE: GLuint = 0;
const VERTICES: &[[f32; 2]; 4] = &[[-1.0, -1.0], [-1.0, 1.0], [1.0, -1.0], [1.0, 1.0]];

const PASSTHROUGH_VERTEX_SHADER: &[u8] = b"
  #version 330 core
  layout(location=0) in vec2 coord;
  out vec2 vTexCoord;
  void main(void) {
    gl_Position = vec4(coord, 0.0, 1.0);
    vTexCoord = coord * 0.5 + 0.5;
  }
";

const PASSTHROUGH_FRAGMENT_SHADER: &[u8] = b"
  #version 330 core
  layout(location=0) out vec4 color;
  uniform sampler2D image;
  in vec2 vTexCoord;
  void main() {
    color = texture(image, vTexCoord);
  }
";

const ANAGLYPH_VERTEX_SHADER: &[u8] = b"
  #version 330 core
  layout(location=0) in vec2 coord;
  uniform float wasted; // What fraction of the image is wasted?
  out vec2 left_coord;
  out vec2 right_coord;
  void main(void) {
    gl_Position = vec4(coord, 0.0, 1.0);
    vec2 coordn = coord * 0.5 + 0.5;
    left_coord = vec2(mix(wasted/2, 0.5, coordn.x), coordn.y);
    right_coord = vec2(mix(0.5, 1-wasted/2, coordn.x), coordn.y);
  }
";

const ANAGLYPH_RED_CYAN_FRAGMENT_SHADER: &[u8] = b"
  #version 330 core
  layout(location=0) out vec4 color;
  uniform sampler2D image;
  in vec2 left_coord;
  in vec2 right_coord;
  void main() {
    vec4 left_color = texture(image, left_coord);
    vec4 right_color = texture(image, right_coord);
    float red = left_color.x;
    float green = right_color.y;
    float blue = right_color.z;
    color = vec4(red, green, blue, 1.0);
  }
";

const SPHERICAL_VERTEX_SHADER: &[u8] = b"
  #version 330 core
  layout(location=0) in vec2 coord;
  out vec2 lon_lat;
  const float PI = 3.141592654;
  void main(void) {
    lon_lat = coord * vec2(PI, 0.5*PI);
    gl_Position = vec4(coord, 0.0, 1.0);
  }
";

const SPHERICAL_FRAGMENT_SHADER: &[u8] = b"
  #version 330 core
  layout(location=0) out vec4 color;
  uniform sampler2D image;
  in vec2 lon_lat;
  void main() {
    vec3 direction = vec3(
      sin(lon_lat.x)*cos(lon_lat.y),
      sin(lon_lat.y),
      cos(lon_lat.x)*cos(lon_lat.y)
    );
    vec2 vTexCoord;
    if ((direction.y > abs(direction.x)) && (direction.y > abs(direction.z))) {
      // Looking up
      vTexCoord.x = direction.z / (direction.y*6.0) + 5.0/6.0;
      vTexCoord.y = direction.x / (direction.y*4.0) + 1.0/4.0;
    } else if ((direction.y < -abs(direction.x)) && (direction.y < -abs(direction.z))) {
      // Looking down
      vTexCoord.x = direction.z / (direction.y*6.0) + 1.0/6.0;
      vTexCoord.y = -direction.x / (direction.y*4.0) + 1.0/4.0;
    } else if (direction.z < -abs(direction.x)) {
      // Looking back
      vTexCoord.x = -direction.y / (direction.z*6.0) + 3.0/6.0;
      vTexCoord.y = -direction.x / (direction.z*4.0) + 1.0/4.0;
    } else if (direction.x < -abs(direction.z)) {
      // Looking left
      vTexCoord.x = -direction.z / (direction.x*6.0) + 1.0/6.0;
      vTexCoord.y = -direction.y / (direction.x*4.0) + 3.0/4.0;
    } else if (direction.x > abs(direction.z)) {
      // Looking right
      vTexCoord.x = -direction.z / (direction.x*6.0) + 5.0/6.0;
      vTexCoord.y = direction.y / (direction.x*4.0) + 3.0/4.0;
    } else {
      // Looking ahead
      vTexCoord.x = direction.x / (direction.z*6.0) + 3.0/6.0;
      vTexCoord.y = direction.y / (direction.z*4.0) + 3.0/4.0;
    }
    color = texture(image, vTexCoord);
  }
";

impl GlWindowShader {
    fn new(gl: Rc<Gl>, mode: GlWindowMode) -> Option<GlWindowShader> {
        // The shader source
        let (vertex_source, fragment_source) = match mode {
            GlWindowMode::Blit => {
                return None;
            }
            GlWindowMode::StereoLeftRight | GlWindowMode::Cubemap => {
                (PASSTHROUGH_VERTEX_SHADER, PASSTHROUGH_FRAGMENT_SHADER)
            }
            GlWindowMode::StereoRedCyan => {
                (ANAGLYPH_VERTEX_SHADER, ANAGLYPH_RED_CYAN_FRAGMENT_SHADER)
            }
            GlWindowMode::Spherical => (SPHERICAL_VERTEX_SHADER, SPHERICAL_FRAGMENT_SHADER),
        };

        // TODO: work out why shaders don't work on macos
        if cfg!(target_os = "macos") {
            log::warn!("XR shaders may not render on MacOS.");
        }

        // The four corners of the window in a VAO, set to attribute 0
        let buffer = gl.gen_buffers(1)[0];
        let vao = gl.gen_vertex_arrays(1)[0];
        gl.bind_buffer(gl::ARRAY_BUFFER, buffer);
        unsafe {
            gl.buffer_data(
                gl::ARRAY_BUFFER,
                std::mem::size_of_val(VERTICES) as isize,
                VERTICES as *const _ as *const c_void,
                gl::STATIC_DRAW,
            )
        };
        gl.bind_vertex_array(vao);
        gl.vertex_attrib_pointer(
            VERTEX_ATTRIBUTE,
            VERTICES[0].len() as i32,
            gl::FLOAT,
            false,
            0,
            0,
        );
        gl.enable_vertex_attrib_array(VERTEX_ATTRIBUTE);
        debug_assert_eq!(gl.get_error(), gl::NO_ERROR);

        // The shader program
        let program = gl.create_program();
        let vertex_shader = gl.create_shader(gl::VERTEX_SHADER);
        let fragment_shader = gl.create_shader(gl::FRAGMENT_SHADER);
        gl.shader_source(vertex_shader, &[vertex_source]);
        gl.compile_shader(vertex_shader);
        gl.attach_shader(program, vertex_shader);
        gl.shader_source(fragment_shader, &[fragment_source]);
        gl.compile_shader(fragment_shader);
        gl.attach_shader(program, fragment_shader);
        gl.link_program(program);
        debug_assert_eq!(gl.get_error(), gl::NO_ERROR);

        // Check for errors
        // TODO: something other than panic?
        let mut status = [0];
        unsafe { gl.get_shader_iv(vertex_shader, gl::COMPILE_STATUS, &mut status) };
        assert_eq!(
            status[0],
            gl::TRUE as i32,
            "Failed to compile vertex shader: {}",
            gl.get_shader_info_log(vertex_shader)
        );
        unsafe { gl.get_shader_iv(fragment_shader, gl::COMPILE_STATUS, &mut status) };
        assert_eq!(
            status[0],
            gl::TRUE as i32,
            "Failed to compile fragment shader: {}",
            gl.get_shader_info_log(fragment_shader)
        );
        unsafe { gl.get_program_iv(program, gl::LINK_STATUS, &mut status) };
        assert_eq!(
            status[0],
            gl::TRUE as i32,
            "Failed to link: {}",
            gl.get_program_info_log(program)
        );

        // Clean up
        gl.delete_shader(vertex_shader);
        debug_assert_eq!(gl.get_error(), gl::NO_ERROR);
        gl.delete_shader(fragment_shader);
        debug_assert_eq!(gl.get_error(), gl::NO_ERROR);

        // And we're done
        Some(GlWindowShader {
            gl,
            buffer,
            vao,
            program,
            mode,
        })
    }

    fn draw_texture(
        &self,
        texture_id: GLuint,
        texture_target: GLuint,
        texture_size: Size2D<i32, UnknownUnit>,
        viewport_size: Size2D<i32, Viewport>,
        window_size: Size2D<i32, Viewport>,
    ) {
        self.gl.use_program(self.program);

        self.gl.enable_vertex_attrib_array(VERTEX_ATTRIBUTE);
        self.gl.vertex_attrib_pointer(
            VERTEX_ATTRIBUTE,
            VERTICES[0].len() as i32,
            gl::FLOAT,
            false,
            0,
            0,
        );

        debug_assert_eq!(self.gl.get_error(), gl::NO_ERROR);

        self.gl.active_texture(gl::TEXTURE0);
        self.gl.bind_texture(texture_target, texture_id);

        match self.mode {
            GlWindowMode::StereoRedCyan => {
                let wasted = 1.0
                    - (texture_size.width as f32 / viewport_size.width as f32)
                        .max(0.0)
                        .min(1.0);
                let wasted_location = self.gl.get_uniform_location(self.program, "wasted");
                self.gl.uniform_1f(wasted_location, wasted);
            }
            GlWindowMode::Blit
            | GlWindowMode::Cubemap
            | GlWindowMode::Spherical
            | GlWindowMode::StereoLeftRight => {}
        }

        self.gl
            .viewport(0, 0, window_size.width, window_size.height);
        self.gl
            .draw_arrays(gl::TRIANGLE_STRIP, 0, VERTICES.len() as i32);
        self.gl.disable_vertex_attrib_array(VERTEX_ATTRIBUTE);
        debug_assert_eq!(self.gl.get_error(), gl::NO_ERROR);
    }
}

impl Drop for GlWindowShader {
    fn drop(&mut self) {
        self.gl.delete_buffers(&[self.buffer]);
        self.gl.delete_vertex_arrays(&[self.vao]);
        self.gl.delete_program(self.program);
    }
}