nsys-gl-utils 0.11.4

OpenGL and graphics utilities
Documentation
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
use std::sync::{Arc, RwLock};
use lazy_static::lazy_static;
use strum::IntoEnumIterator;
use winit;

use math_utils as math;
use math_utils::num_traits as num;

use crate::{tile, Render};
use super::*;

/// A type to implement winit ApplicationHandler trait
pub struct App {
  pub render             : Render <Default>,
  pub mouse_position     : (f64, f64),
  pub mouse_button_event : Option <winit::event::ElementState>,
  pub running            : bool
}

impl App {
  pub fn new (
    glium_display : glium::Display <glutin::surface::WindowSurface>,
    window        : winit::window::Window
  ) -> Self {
    let mut render = Render::<Default>::new (glium_display, window);
    render.demo_init();
    let mouse_position      = (0.0, 0.0);
    let mouse_button_event  = None;
    let running             = true;
    Self {
      render, mouse_position, mouse_button_event, running
    }
  }
}

impl winit::application::ApplicationHandler for App {
  // required
  fn resumed (&mut self, _event_loop : &winit::event_loop::ActiveEventLoop) { }

  fn window_event (&mut self,
    _event_loop : &winit::event_loop::ActiveEventLoop,
    _window_id  : winit::window::WindowId,
    event       : winit::event::WindowEvent
  ) {
    // winit events:
    // TODO: review
    // - window events includes input events received by the window
    // - device events are received independent of window focus
    // there may be differences in the events received depending on platform:
    // - on Linux keyboard input is received as both a device and window event
    // - on Windows only mouse motion device events are received, all other
    //   input is received as window events
    self.render.demo_handle_winit_window_event (
      event,
      &mut self.running,
      &mut self.mouse_position,
      &mut self.mouse_button_event)
  }
}

impl Render <Default> {
  /// Initializes "demo" state such as example mesh instances and viewport text
  /// tiles.
  ///
  /// This should normally be called immediately after render context creation
  /// as some assumptions are made about the current state (see Panics below).
  /// The renderer can be returned to this state with the `reset` method.
  ///
  /// After `demo_init`, `demo_handle_winit_event` can be called on incoming
  /// events to interact with the demo.
  ///
  /// A usage example is provided in `./examples/demo.rs`.
  ///
  /// # Panics
  ///
  /// A prerequisite is that the first four `viewport_resources` entries are
  /// empty.
  ///
  /// The currently allocated per-instance buffers should be empty.
  // TODO: doctests, make safe to call from any state?
  fn demo_init (&mut self) {
    use draw3d::*;

    println!(">>> Initializing gl-utils demo...");
    println!("  Press 'Q' or 'Esc' to quit");
    println!("  Horizontal movement: 'W', 'A', 'S', 'D'");
    println!("  Vertical movement: 'Space', 'LCtrl' or 'R', 'F'");
    println!("  Rotation: 'Up', 'Down', 'Left', 'Right' or 'H', 'J', 'K', 'L'");
    println!("  Zoom in/out 3D (perspective): 'I', 'O'");
    println!("  Zoom in/out 3D (orthographic): 'Alt+I', 'Alt+O'");
    println!("  Zoom in/out 2D: 'Shift+Alt+I', 'Shift+Alt+O'");
    println!("  Toggle split into 4 viewports with orthographic views: 'X'");
    println!("  Screenshot: 'F10'");

    // set pointer texture
    self.resource.draw2d.draw_pointer =
      Some (DefaultTexturePointerId::Hand as PointerTextureIndexRepr);
    // hide hardware cursor
    self.window.set_cursor_visible (false);

    //
    // 3D per-instance data
    //
    // aabb lines vertex data
    let aabb_lines_vertex = [vertex::Vert3dOrientationScaleColor {
      position:    [-0.5, 2.5, 1.0],
      orientation: math::Matrix3::identity().into_col_arrays(),
      scale:       [0.5, 0.5, 1.0],
      color:       color::rgba_u8_to_rgba_f32 (color::DEBUG_PINK)
    }];
    // aabb triangles vertex data
    let aabb_triangles_vertex = [vertex::Vert3dOrientationScaleColor {
      color: color::rgba_u8_to_rgba_f32 (color::DEBUG_GREY),
      .. aabb_lines_vertex[0]
    }];
    // grid vertex data
    let grid_vertex_data = Default::debug_grid_vertices();
    // hemisphere vertex data
    let hemisphere_vertex = [vertex::Vert3dOrientationScaleColor {
      position:    [2.5, 2.5, 0.0],
      orientation: math::Matrix3::identity().into_col_arrays(),
      scale:       [0.5, 0.5, 0.5],
      color:       color::rgba_u8_to_rgba_f32 (color::DEBUG_VIOLET)
    }];
    // sphere vertex data
    // sphere: 1.0 diameter
    let sphere_vertex = [vertex::Vert3dOrientationScaleColor {
      position:    [1.5, 2.5, 0.5],
      orientation: math::Matrix3::identity().into_col_arrays(),
      scale:       [0.5, 0.5, 0.5],
      color:       color::rgba_u8_to_rgba_f32 (color::DEBUG_RED)
    }];
    // capsule vertex data
    let capsule_vertex = [vertex::Vert3dOrientationScaleColor {
      position:    [0.5, 2.5, 1.0],
      orientation: math::Matrix3::identity().into_col_arrays(),
      scale:       [0.5, 0.5, 1.0],
      color:       color::rgba_u8_to_rgba_f32 (color::DEBUG_AZURE)
    }];
    // cylinder vertex data
    let cylinder_vertex = [vertex::Vert3dOrientationScaleColor {
      position:    [3.5, 2.5, 1.0],
      orientation: math::Matrix3::identity().into_col_arrays(),
      scale:       [0.5, 0.5, 1.0],
      color:       color::rgba_u8_to_rgba_f32 (color::DEBUG_LIGHT_BLUE)
    }];
    let aabb_lines               = Some (&aabb_lines_vertex[..]);
    let aabb_triangles           = Some (&aabb_triangles_vertex[..]);
    let aabb_lines_and_triangles = None;
    let meshes = {
      let mut v = VecMap::with_capacity (MeshId::COUNT);
      assert!(v.insert (MeshId::Grid       as usize, &grid_vertex_data[..])
        .is_none());
      assert!(v.insert (MeshId::Hemisphere as usize, &hemisphere_vertex[..])
        .is_none());
      assert!(v.insert (MeshId::Sphere     as usize, &sphere_vertex[..])
        .is_none());
      assert!(v.insert (MeshId::Capsule    as usize, &capsule_vertex[..])
        .is_none());
      assert!(v.insert (MeshId::Cylinder   as usize, &cylinder_vertex[..])
        .is_none());
      v
    };
    // note: no billboard instances are created here, instead they are assigned
    // to share instances with meshes
    let billboards = VecMap::new();
    self.resource.draw3d.instance_vertices_set (
      &self.glium_display,
      draw3d::InstancesInit {
        aabb_lines, aabb_triangles, aabb_lines_and_triangles, meshes, billboards
      }
    );
    // tile billboards
    for mesh_id in MeshId::iter() {
      let key = mesh_id as usize;
      self.resource.draw3d.tile_billboard_create (
        &self.glium_display, &self.resource.tileset_128x128_texture,
        key, self.resource.draw3d.instanced_meshes()[key].instances_range.clone(),
        format!("{:?}", mesh_id).as_str()
      );
    }
    let aabb_billboard_key = MeshId::COUNT;
    self.resource.draw3d.tile_billboard_create (
      &self.glium_display, &self.resource.tileset_128x128_texture,
      aabb_billboard_key,  // start immediately after mesh billboards
      self.resource.draw3d.instanced_aabb_lines().clone(),
      "Aabb"
    );

    let (width, height) = self.window.inner_size().into();
    let [_tile_width, tile_height] =
      self.resource.tile_dimensions (DefaultTilesetId::EasciiAcorn128);
    //
    // 2D per-viewport tiles
    //
    let mut tile_2d_vertices = tile::vertices ("Viewport0", (0, 0));
    let viewport0_tile_range = 0..tile_2d_vertices.len() as u32;
    tile_2d_vertices.extend (tile::vertices ("Viewport1: +Y", (0, 0)));
    let viewport1_tile_range = viewport0_tile_range.end..tile_2d_vertices.len()
      as u32;
    tile_2d_vertices.extend (tile::vertices ("Viewport2: +X", (0, 0)));
    let viewport2_tile_range = viewport1_tile_range.end..tile_2d_vertices.len()
      as u32;
    tile_2d_vertices.extend (tile::vertices ("Viewport3: -Z", (0, 0)));
    let viewport3_tile_range = viewport2_tile_range.end..tile_2d_vertices.len()
      as u32;
    //let center_tile = ((width / tile_width) / 2) as i32;
    let fps_row = ((height / tile_height) - 1) as i32;
    tile_2d_vertices.extend (tile::vertices ("FPS: 0     ", (fps_row, 0)));
    let viewport4_tile_range = viewport3_tile_range.end..tile_2d_vertices.len()
      as u32;
    self.resource.draw2d.tile_2d_vertices = glium::VertexBuffer::dynamic (
      &self.glium_display, &tile_2d_vertices[..]
    ).unwrap();
    let tile_color_2d_vertices = {
      let tiles  = tile::vertices ("abc123",    (2, 0));
      let colors = vec![
        ( [1.0, 0.0, 0.0, 1.0], [0.0, 0.0, 0.0, 0.0] ),
        ( [0.0, 1.0, 0.0, 1.0], [0.0, 0.0, 0.0, 0.0] ),
        ( [0.0, 0.0, 1.0, 1.0], [0.0, 0.0, 0.0, 0.0] ),
        ( [0.0, 0.0, 0.0, 0.0], [1.0, 1.0, 0.0, 1.0] ),
        ( [0.0, 0.0, 0.0, 0.0], [1.0, 0.0, 1.0, 1.0] ),
        ( [0.0, 0.0, 0.0, 0.0], [0.0, 1.0, 1.0, 1.0] )
      ];
      tiles.into_iter().zip (colors).map (
        |(vertex::Vert2dTile { tile, row, column }, (fg, bg))|
        vertex::Vert2dTileColor { tile, row, column, fg, bg }
      ).collect::<Vec <_>>()
    };
    let viewport0_tile_color_range = 0..tile_color_2d_vertices.len() as u32;
    self.resource.draw2d.tile_color_2d_vertices = glium::VertexBuffer::dynamic (
      &self.glium_display, &tile_color_2d_vertices[..]
    ).unwrap();
    let draw_tiles = draw2d::Tiles {
      vertex_range: 0..0, origin: (2, 2).into(),
      tileset_id: DefaultTilesetId::EasciiAcorn128
    };
    let draw_tiles_color = draw2d::Tiles {
      vertex_range: 0..0, origin: draw2d::TilesOrigin::World,
      tileset_id: DefaultTilesetId::EasciiAcorn256
    };
    self.resource.draw2d.viewport_resources_set (MAIN_VIEWPORT,
      draw2d::ViewportResources {
        draw_indices: vec![draw2d::DrawIndices {
          rectangle:        None,
          draw_tiles:       Some (draw2d::Tiles {
            vertex_range: viewport0_tile_range,
            .. draw_tiles.clone()
          }),
          draw_color_tiles: Some (draw2d::Tiles {
            vertex_range: viewport0_tile_color_range,
            .. draw_tiles_color
          })
        }],
        .. draw2d::ViewportResources::default()
      }
    );
    self.resource.draw2d.viewport_resources_set (UPPER_LEFT_VIEWPORT,
      draw2d::ViewportResources {
        draw_indices: vec![draw2d::DrawIndices {
          draw_tiles: Some (draw2d::Tiles {
            vertex_range: viewport1_tile_range,
            .. draw_tiles.clone()
          }),
          .. draw2d::DrawIndices::default()
        }],
        .. draw2d::ViewportResources::default()
      }
    );
    self.resource.draw2d.viewport_resources_set (UPPER_RIGHT_VIEWPORT,
      draw2d::ViewportResources {
        draw_indices: vec![draw2d::DrawIndices {
          draw_tiles: Some (draw2d::Tiles {
            vertex_range: viewport2_tile_range,
            .. draw_tiles.clone()
          }),
          .. draw2d::DrawIndices::default()
        }],
        .. draw2d::ViewportResources::default()
      }
    );
    self.resource.draw2d.viewport_resources_set (LOWER_LEFT_VIEWPORT,
      draw2d::ViewportResources {
        draw_indices: vec![draw2d::DrawIndices {
          draw_tiles: Some (draw2d::Tiles {
            vertex_range: viewport3_tile_range,
            .. draw_tiles.clone()
          }),
          .. draw2d::DrawIndices::default()
        }],
        .. draw2d::ViewportResources::default()
      }
    );
    self.resource.draw2d.viewport_resources_set (OVERLAY_VIEWPORT,
      draw2d::ViewportResources {
        draw_indices: vec![draw2d::DrawIndices {
          draw_tiles: Some (draw2d::Tiles {
            vertex_range: viewport4_tile_range,
            .. draw_tiles.clone()
          }),
          .. draw2d::DrawIndices::default()
        }],
        draw_lineloop: false,
        draw_crosshair: false,
        .. draw2d::ViewportResources::default()
      }
    );
    // create overlay viewport
    let overlay = render::viewport::Builder::new (glium::Rect {
      width:  width,
      height: height,
      left:   0,
      bottom: 0
    }).with_camera_3d (false)
      .build();
    assert!(self.viewports.insert (OVERLAY_VIEWPORT, overlay).is_none());
  }

  pub fn demo_handle_winit_window_event (&mut self,
    event              : winit::event::WindowEvent,
    running            : &mut bool,
    mouse_position     : &mut (f64, f64),
    mouse_button_event : &mut Option <winit::event::ElementState>
  ) {
    use std::f32::consts::PI;
    use winit::{event, keyboard};
    use num::Zero;
    log::debug!("demo handle winit window event: {:?}", event);
    // winit deprecated the modifiers field of keyboard input so we have to
    // track modifier changes
    lazy_static!{
      static ref MODIFIERS : Arc <RwLock <keyboard::ModifiersState>> =
        Arc::new (RwLock::new (keyboard::ModifiersState::empty()));
    }
    match event {
      // window resized event
      event::WindowEvent::Resized (physical_size) => {
        log::debug!("window event: {:?}", event);
        self.window_resized (physical_size);
      }
      // window closed event
      event::WindowEvent::CloseRequested => { *running = false; }
      // TODO: for some reason a destroyed event is received on startup even
      // though window has not been destroyed (winit 27.5)
      event::WindowEvent::Destroyed => { /* *running = false; */ }
      // modifiers changed event
      event::WindowEvent::ModifiersChanged (modifiers) =>
        *MODIFIERS.write().unwrap() = modifiers.state(),
      // keyboard input pressed event
      event::WindowEvent::KeyboardInput {
        event: event::KeyEvent {
          state: event::ElementState::Pressed,
          physical_key, logical_key, location, ..
        },
        ..
      } => match (logical_key, location) {
        ( keyboard::Key::Named (keyboard::NamedKey::Control),
          keyboard::KeyLocation::Left
        ) => self.camera3d_move_local_xy (0.0, 0.0, -1.0),
        _ => match physical_key {
          keyboard::PhysicalKey::Code (key_code) => match key_code {
            // quit
            keyboard::KeyCode::KeyQ | keyboard::KeyCode::Escape =>
              *running = false,
            // choose a frame function 0-9
            keyboard::KeyCode::Digit1 => self.frame_fun =
              render::frame_fun_default::<render::resource::Default>,
            // TODO: more frame functions
            // TODO: cycle between frame functions
            //keyboard::KeyCode::Tab => { }
            keyboard::KeyCode::KeyW =>
              self.camera3d_move_local_xy (0.0, 1.0, 0.0),
            keyboard::KeyCode::KeyS =>
              self.camera3d_move_local_xy (0.0, -1.0, 0.0),
            keyboard::KeyCode::KeyD =>
              self.camera3d_move_local_xy (1.0, 0.0, 0.0),
            keyboard::KeyCode::KeyA =>
              self.camera3d_move_local_xy (-1.0, 0.0, 0.0),
            keyboard::KeyCode::Space | keyboard::KeyCode::KeyR =>
              self.camera3d_move_local_xy (0.0, 0.0, 1.0),
            keyboard::KeyCode::KeyF =>
              self.camera3d_move_local_xy (0.0, 0.0, -1.0),
            keyboard::KeyCode::KeyJ | keyboard::KeyCode::ArrowDown => {
              let modifiers = MODIFIERS.read().unwrap();
              if modifiers.alt_key() && modifiers.shift_key() {
                self.camera2d_move_local (0.0, -1.0);
              } else {
                self.camera3d_rotate (
                  math::Rad::zero(),
                  math::Rad (-PI / 12.0),
                  math::Rad::zero());
              }
            }
            keyboard::KeyCode::KeyK | keyboard::KeyCode::ArrowUp => {
              let modifiers = MODIFIERS.read().unwrap();
              if modifiers.alt_key() && modifiers.shift_key() {
                self.camera2d_move_local (0.0, 1.0);
              } else {
                self.camera3d_rotate (
                  math::Rad::zero(),
                  math::Rad (PI / 12.0),
                  math::Rad::zero());
              }
            }
            keyboard::KeyCode::KeyH | keyboard::KeyCode::ArrowLeft => {
              let modifiers = MODIFIERS.read().unwrap();
              if modifiers.alt_key() && modifiers.shift_key() {
                self.camera2d_move_local (-1.0, 0.0);
              } else {
                self.camera3d_rotate (
                  math::Rad (PI / 12.0),
                  math::Rad::zero(),
                  math::Rad::zero());
              }
            }
            keyboard::KeyCode::KeyL | keyboard::KeyCode::ArrowRight => {
              let modifiers = MODIFIERS.read().unwrap();
              if modifiers.alt_key() && modifiers.shift_key() {
                self.camera2d_move_local (1.0, 0.0);
              } else {
                self.camera3d_rotate (
                  math::Rad (-PI / 12.0),
                  math::Rad::zero(),
                  math::Rad::zero());
              }
            }
            keyboard::KeyCode::KeyI => {
              let modifiers = MODIFIERS.read().unwrap();
              if modifiers.alt_key() && modifiers.shift_key() {
                self.camera2d_zoom_shift (1.0);
              } else if modifiers.alt_key() {
                self.camera3d_orthographic_zoom_scale (1.1);
              } else {
                self.camera3d_perspective_fovy_scale (1.0 / 1.1);
              }
            }
            keyboard::KeyCode::KeyO => {
              let modifiers = MODIFIERS.read().unwrap();
              if modifiers.alt_key() && modifiers.shift_key() {
                self.camera2d_zoom_shift (-1.0);
              } else if modifiers.alt_key() {
                self.camera3d_orthographic_zoom_scale (1.0 / 1.1);
              } else {
                self.camera3d_perspective_fovy_scale (1.1);
              }
            }
            // toggle 4-viewport mode
            keyboard::KeyCode::KeyX   => self.demo_toggle_quad_viewports(),
            // end camera controls
            keyboard::KeyCode::F10 | keyboard::KeyCode::PrintScreen =>
              self.screenshot(),
            _ => {}
          }
          keyboard::PhysicalKey::Unidentified (_) => {}
        }
      } // end keyboard input
      event::WindowEvent::MouseInput { button, state, .. } => match button {
        event::MouseButton::Left => *mouse_button_event = Some (state),
        _ => {}
      }
      event::WindowEvent::CursorMoved { position, ..  } => {
        if self.resource.draw2d.draw_pointer.is_some() {
          let (_, height) = self.glium_display.get_framebuffer_dimensions();
          let x = position.x as f32;
          let y = height as f32 - position.y as f32;
          self.resource
            .set_pointer_position (&self.glium_display, [x, y].into());
        }
        *mouse_position = (position.x, position.y);
      }
      _ => {}
    }
  }

  /// Switch between single (perspective) and quad viewport modes (perspective
  /// + three ortho viewports).
  ///
  /// Generally should be called from a render context that was initialized
  /// with `demo_init`.
  ///
  /// # Panics
  ///
  /// If there is a single viewport (other than the `OVERLAY_VIEWPORT`) it must
  /// be `MAIN_VIEWPORT`.
  ///
  /// If there are multiple viewports, they must be exactly the first four
  /// viewports only (other than the `OVERLAY_VIEWPORT`).
  // TODO: doctests, make safe to call from any state?
  fn demo_toggle_quad_viewports (&mut self) {
    if self.viewports.len() <= 2 {
      // switch to four viewports from single viewport
      // main viewport becomes "lower right"
      let (
        left_width, right_width, upper_height, lower_height, position,
        position_2d, zoom_2d
      ) = {
        let lower_right   = &mut self.viewports[MAIN_VIEWPORT];
        let window_width  = lower_right.rect().width;
        let window_height = lower_right.rect().height;
        let left_width    = left_width   (window_width);
        let right_width   = right_width  (window_width);
        let upper_height  = upper_height (window_height);
        let lower_height  = lower_height (window_height);
        lower_right.set_rect (glium::Rect {
          width:  right_width,
          height: lower_height,
          left:   left_width,
          bottom: 0
        });
        ( left_width, right_width, upper_height, lower_height,
          lower_right.camera3d().unwrap().position(),
          lower_right.camera2d().unwrap().position(),
          lower_right.camera2d().unwrap().zoom()
        )
      };

      let upper_left  = render::viewport::Builder::new (glium::Rect {
        width:  left_width,
        height: upper_height,
        left:   0,
        bottom: lower_height
      }).with_zoom_2d (zoom_2d).with_position_2d (position_2d)
        .orthographic_3d (1.0)
        .with_pose_3d (
          // looking down positive Y axis
          math::Pose3 { position, angles: math::Angles3::default() })
        .build();

      let upper_right = render::viewport::Builder::new (glium::Rect {
        width:  right_width,
        height: upper_height,
        left:   left_width,
        bottom: lower_height,
      }).with_zoom_2d (zoom_2d).with_position_2d (position_2d)
        .orthographic_3d (1.0)
        .with_pose_3d (
          math::Pose3 {
            position,
            // looking down positive X axis
            angles: math::Angles3::wrap (
              math::Deg (-90.0).into(),
              math::Rad (0.0),
              math::Rad (0.0))
          })
        .build();

      let lower_left  = render::viewport::Builder::new (glium::Rect {
        width:  left_width,
        height: lower_height,
        left:   0,
        bottom: 0,
      }).with_zoom_2d (zoom_2d).with_position_2d (position_2d)
        .orthographic_3d (1.0)
        .with_pose_3d (
          math::Pose3 {
            position,
            // looking down negative Z axis
            angles: math::Angles3::wrap (
              math::Rad (0.0),
              math::Deg (-90.0).into(),
              math::Rad (0.0))
          })
        .build();

      assert!(self.viewports.insert (UPPER_LEFT_VIEWPORT, upper_left)
        .is_none());
      assert!(self.viewports.insert (UPPER_RIGHT_VIEWPORT, upper_right)
        .is_none());
      assert!(self.viewports.insert (LOWER_LEFT_VIEWPORT, lower_left)
        .is_none());
    } else {
      // switch to single viewport from four viewports
      assert!(self.viewports.len() == 4 || self.viewports.len() == 5);
      assert!(self.viewports.remove (UPPER_LEFT_VIEWPORT) .is_some());
      assert!(self.viewports.remove (UPPER_RIGHT_VIEWPORT).is_some());
      assert!(self.viewports.remove (LOWER_LEFT_VIEWPORT) .is_some());
      let main_viewport   = &mut self.viewports[MAIN_VIEWPORT];
      let (width, height) = self.window.inner_size().into();
      main_viewport.set_rect (glium::Rect {
        width,
        height,
        left:   0,
        bottom: 0
      });
    }
    self.update_viewport_line_loops();
  } // end fn toggle_quad_viewports
}