nsys-gl-utils 0.11.9

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
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
use derive_more::From;
use glium::{self, uniform};
use strum::{EnumCount, EnumIter, FromRepr};
use vec_map::VecMap;

use math_utils as math;

use crate::{color, mesh, render, shader, vertex, Mesh, Render};

pub const MESH_GRID_DIMS          : u16 = 12;
/// A default scale used when rending 3D sprites
pub const DEFAULT_PIXELS_PER_UNIT : f32 = 64.0;

/// 3d drawing resources.
///
/// ```text
/// [                instance_vertices               ]
/// ```
pub struct Draw3d {
  /// Vertex buffer containing per-instance vertices. Any of the below instanced
  /// types can be rendered at one of these vertices.
  instance_vertices : glium::VertexBuffer <vertex::Vert3dOrientationScaleColor>,

  // TODO: combine abbs with basis vectors as variants of a 'primitive'
  /// Range of per-instance vertices to draw AABB lines
  instanced_aabb_lines     : std::ops::Range <u32>,
  /// Range of per-instance vertices to draw AABB triangles
  instanced_aabb_triangles : std::ops::Range <u32>,
  instanced_billboards     : VecMap <InstancedBillboard>,
  instanced_meshes         : InstancedMeshes,
  pub user_buffers         : VecMap <glium::VertexBuffer <vertex::Vert3dColor>>,
  pub user_draw            : VecMap <UserDraw>,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct UserDraw {
  pub buffer_key        : UserBufferKey,
  /// Slice of the buffer to draw from
  pub range             : std::ops::Range <u32>,
  pub primitive_type    : glium::index::PrimitiveType,
  pub shader_program_id : shader::ProgramId,
  pub draw_pass         : DrawPass
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct UserBufferKey (pub u32);

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum DrawPass {
  Depth,
  NoDepth
}

/// Wireframe meshes matched to ranges of per-instance vertices
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct InstancedMesh {
  /// Slice of `instanced_meshes.line_indices` corresponding to this mesh: each
  /// instance of the mesh will draw an instance of the vertices mapped to by
  /// the range of indices
  pub line_indices_range : std::ops::Range <u32>,
  /// Range of `instance_vertices` corresponding to this mesh: each of these
  /// vertices will draw an instance of this mesh at that location
  pub instances_range    : std::ops::Range <u32>,
  pub shader_program_id  : shader::ProgramId,
  pub draw_pass          : DrawPass
}

/// 3D billboards mapped to ranges of per-instance vertices
pub struct InstancedBillboard {
  pub texture         : glium::Texture2d,
  /// Billboard will be drawn at this range of the `instance_vertices`
  pub instances_range : std::ops::Range <u32>
}

/// Used to initialize per-instance vertex buffers
#[derive(Default)]
pub struct InstancesInit <'a> {
  pub aabb_lines               : Option <&'a [vertex::Vert3dOrientationScaleColor]>,
  pub aabb_triangles           : Option <&'a [vertex::Vert3dOrientationScaleColor]>,
  pub aabb_lines_and_triangles : Option <&'a [vertex::Vert3dOrientationScaleColor]>,
  pub meshes                   : VecMap <&'a [vertex::Vert3dOrientationScaleColor]>,
  pub billboards               : VecMap <&'a [vertex::Vert3dOrientationScaleColor]>
}

#[derive(Clone, Copy, Debug, Eq, PartialEq, From)]
pub struct MeshKey (pub u32);

#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd, EnumCount, EnumIter,
  FromRepr)]
#[repr(u16)]
pub enum MeshId {
  Grid,
  Hemisphere,
  Capsule,
  Cube,
  Cylinder,
  Sphere
}

//
//  private
//

struct InstancedMeshes {
  /// 3D vertices for instanced drawing.
  ///
  /// Multiple instanced meshes are stored here, indexed by slices of
  /// `line_indices`.
  pub vertices     : glium::VertexBuffer <vertex::Vert3dInstanced>,
  /// Indices for drawing instanced 3D meshes in `instanced_vertices`.
  ///
  /// Each separate mesh has a corresponding slice of indices in this index
  /// buffer, with ranges stored in the `instanced_indices_lines_ranges`
  /// field.
  pub line_indices : glium::IndexBuffer <u32>,
  /// Each instanced mesh defines a range of instanced line indices, a shader
  /// program ID, and a range of instance vertices at which to draw an instance
  pub meshes       : VecMap <InstancedMesh>,
  // some uniforms for the capsule shader
  pub capsule_vertex_id_offset : u32,
  pub hemisphere_vertex_count  : u32
}

struct InstancedMeshInit {
  pub instanced_vertex_data     : Vec <vertex::Vert3dInstanced>,
  pub instanced_line_index_data : Vec <u32>,
  pub line_indices_ranges       : VecMap <std::ops::Range <u32>>,
  pub shader_program_ids        : VecMap <shader::ProgramId>,
  pub draw_passes               : VecMap <DrawPass>,
  pub capsule_vertex_id_offset  : u32,
  pub hemisphere_vertex_count   : u32
}

////////////////////////////////////////////////////////////////////////////////
//  impls
////////////////////////////////////////////////////////////////////////////////

impl Draw3d {
  pub fn new (glium_display : &glium::Display <glutin::surface::WindowSurface>) -> Self {
    let instanced_aabb_lines     = 0..0;   // empty
    let instanced_aabb_triangles = 0..0;   // empty
    let instanced_billboards     = VecMap::new();
    let instanced_meshes         = InstancedMeshes::new (glium_display, vec![]);
    let instance_vertices        = glium::VertexBuffer::dynamic (
      glium_display,
      // origin vertex
      &[ vertex::Vert3dOrientationScaleColor {
          position:    [0.0, 0.0, 0.0],
          orientation: math::Matrix3::identity().into_col_arrays(),
          scale:       [1.0, 1.0, 1.0],
          color:       color::rgba_u8_to_rgba_f32 (color::DEBUG_CHARTREUSE)
        }
      ]
    ).unwrap();
    let user_buffers = VecMap::new();
    let user_draw    = VecMap::new();
    Draw3d {
      instance_vertices,
      instanced_aabb_lines,
      instanced_aabb_triangles,
      instanced_billboards,
      instanced_meshes,
      user_buffers,
      user_draw
    }
  }

  pub fn draw (
    render      : &Render <render::resource::Default>,
    glium_frame : &mut glium::Frame
  ) {
    let draw3d = &render.resource.draw3d;
    // draw each viewport 3d
    for (_, viewport) in render.viewports.iter() {
      if let Some (camera3d) = viewport.camera3d() {
        use glium::Surface;
        // draw parameters: viewport
        let draw_parameters_viewport = viewport.draw_parameters();
        // draw parameters: depth test
        let draw_parameters_write_depth = glium::DrawParameters {
          depth: glium::Depth {
            test:  glium::DepthTest::IfLess,
            write: true,
            .. glium::Depth::default()
          },
          .. draw_parameters_viewport.clone()
        };
        // draw parameters: polygon offset
        let draw_parameters_polygon_offset = glium::DrawParameters {
          polygon_offset: glium::draw_parameters::PolygonOffset {
            factor: 1.0,
            units: 1.0 / 1024.0,
            fill: true,
            .. Default::default()
          },
          backface_culling:
            glium::draw_parameters::BackfaceCullingMode::CullCounterClockwise,
          .. draw_parameters_write_depth.clone()
        };
        // uniforms
        let (transform_mat_world_to_view, projection_mat_perspective) =
          camera3d.view_mats();
        let uniforms = uniform!{
          uni_transform_mat_view:         transform_mat_world_to_view,
          uni_projection_mat_perspective: projection_mat_perspective,
          // TODO: variable pixels per unit?
          uni_pixels_per_unit:            DEFAULT_PIXELS_PER_UNIT,
          uni_capsule_vertex_id_offset:
            draw3d.instanced_meshes.capsule_vertex_id_offset,
          uni_hemisphere_vertex_count:
            draw3d.instanced_meshes.hemisphere_vertex_count,
          uni_color: color::rgba_u8_to_rgba_f32 (color::BLACK)
        };

        // draw aabbs lines
        if !draw3d.instanced_aabb_lines.is_empty() {
          let instances_range =
            draw3d.instanced_aabb_lines.start as usize..
            draw3d.instanced_aabb_lines.end   as usize;
          glium_frame.draw (
            draw3d.instance_vertices.slice (instances_range).unwrap(),
            glium::index::IndicesSource::NoIndices {
              primitives: glium::index::PrimitiveType::Points
            },
            &render.resource.shader_programs [
              shader::ProgramId::WorldSpace3dAabbLines as usize
            ],
            &uniforms,
            &draw_parameters_write_depth
          ).unwrap();
        }

        // draw aabbs triangles
        if !draw3d.instanced_aabb_triangles.is_empty() {
          let instances_range =
            draw3d.instanced_aabb_triangles.start as usize..
            draw3d.instanced_aabb_triangles.end   as usize;
          glium_frame.draw (
            draw3d.instance_vertices.slice (instances_range).unwrap(),
            glium::index::IndicesSource::NoIndices {
              primitives: glium::index::PrimitiveType::Points
            },
            &render.resource.shader_programs [
              shader::ProgramId::WorldSpace3dAabbTriangles as usize
            ],
            &uniforms,
            &draw_parameters_polygon_offset
          ).unwrap();
        }

        // draw instanced meshes with depth
        for (_mesh_key, instanced_mesh) in draw3d.instanced_meshes.meshes.iter() {
          if instanced_mesh.draw_pass != DrawPass::Depth {
            continue
          }
          if !instanced_mesh.instances_range.is_empty() {
            let (line_indices_range, instances_range) = (
              instanced_mesh.line_indices_range.start as usize..
              instanced_mesh.line_indices_range.end   as usize,
              instanced_mesh.instances_range.start as usize..
              instanced_mesh.instances_range.end   as usize
            );
            glium_frame.draw (
              (&draw3d.instanced_meshes.vertices,
                draw3d.instance_vertices.slice (instances_range).unwrap()
                  .per_instance().unwrap()
              ),
              draw3d.instanced_meshes.line_indices.slice (line_indices_range)
                .unwrap(),
              &render.resource.shader_programs [instanced_mesh.shader_program_id
                as usize],
              &uniforms,
              &draw_parameters_write_depth
            ).unwrap();
          }
        }

        // user draw calls with depth
        for user_draw in draw3d.user_draw.values() {
          if user_draw.draw_pass != DrawPass::Depth {
            continue
          }
          let vertex_buffer = draw3d.user_buffers
            .get (user_draw.buffer_key.index()).unwrap();
          let vertex_range  =
            user_draw.range.start as usize..
            user_draw.range.end   as usize;
          let uniforms = uniform!{
            uni_transform_mat_view:         transform_mat_world_to_view,
            uni_projection_mat_perspective: projection_mat_perspective,
            // TODO: variable pixels per unit?
            uni_pixels_per_unit:            DEFAULT_PIXELS_PER_UNIT,
            uni_capsule_vertex_id_offset:
              draw3d.instanced_meshes.capsule_vertex_id_offset,
            uni_hemisphere_vertex_count:
              draw3d.instanced_meshes.hemisphere_vertex_count
          };
          glium_frame.draw (
            vertex_buffer.slice (vertex_range).unwrap(),
            glium::index::NoIndices (user_draw.primitive_type),
            &render.resource.shader_programs [user_draw.shader_program_id.index()],
            &uniforms,
            &draw_parameters_write_depth
          ).unwrap();
        }

        // draw instanced meshes w/o depth
        for (_mesh_key, instanced_mesh) in draw3d.instanced_meshes.meshes.iter() {
          if instanced_mesh.draw_pass != DrawPass::NoDepth {
            continue
          }
          if !instanced_mesh.instances_range.is_empty() {
            let (line_indices_range, instances_range) = (
              instanced_mesh.line_indices_range.start as usize..
              instanced_mesh.line_indices_range.end   as usize,
              instanced_mesh.instances_range.start as usize..
              instanced_mesh.instances_range.end   as usize
            );
            glium_frame.draw (
              (&draw3d.instanced_meshes.vertices,
                draw3d.instance_vertices.slice (instances_range).unwrap()
                  .per_instance().unwrap()
              ),
              draw3d.instanced_meshes.line_indices.slice (line_indices_range)
                .unwrap(),
              &render.resource.shader_programs [instanced_mesh.shader_program_id
                as usize],
              &uniforms,
              &draw_parameters_viewport
            ).unwrap();
          }
        }

        // user draw calls with w/o depth
        for user_draw in draw3d.user_draw.values() {
          if user_draw.draw_pass != DrawPass::NoDepth {
            continue
          }
          let vertex_buffer = draw3d.user_buffers
            .get (user_draw.buffer_key.index()).unwrap();
          let vertex_range  =
            user_draw.range.start as usize..
            user_draw.range.end   as usize;
          glium_frame.draw (
            vertex_buffer.slice (vertex_range).unwrap(),
            glium::index::NoIndices (user_draw.primitive_type),
            &render.resource.shader_programs [user_draw.shader_program_id.index()],
            &uniforms,
            &draw_parameters_viewport
          ).unwrap();
        }

        // draw 3d billboards
        // TODO: draw some or all billboards with depth?
        for (_, instanced_billboard) in draw3d.instanced_billboards.iter() {
          let instances_range =
            instanced_billboard.instances_range.start as usize..
            instanced_billboard.instances_range.end   as usize;
          let uniforms = uniform!{
            uni_transform_mat_view:         transform_mat_world_to_view,
            uni_projection_mat_perspective: projection_mat_perspective,
            uni_sampler2d:                  instanced_billboard.texture.sampled()
              .magnify_filter (glium::uniforms::MagnifySamplerFilter::Nearest),
            // TODO: variable pixels per unit?
            uni_pixels_per_unit:            DEFAULT_PIXELS_PER_UNIT
          };
          glium_frame.draw (
            draw3d.instance_vertices.slice (instances_range).unwrap(),
            glium::index::IndicesSource::NoIndices {
              primitives: glium::index::PrimitiveType::Points
            },
            &render.resource.shader_programs [
              shader::ProgramId::WorldSpace3dSprite as usize
            ],
            &uniforms,
            &draw_parameters_viewport
          ).unwrap();
        }
      }
    } // end loop over viewports
  } // end draw

  #[inline]
  pub const fn instance_vertices (&self)
    -> &glium::VertexBuffer <vertex::Vert3dOrientationScaleColor>
  {
    &self.instance_vertices
  }

  #[inline]
  pub const fn instanced_aabb_lines (&self) -> &std::ops::Range <u32> {
    &self.instanced_aabb_lines
  }

  #[inline]
  pub fn set_instanced_aabb_lines (&mut self, range : std::ops::Range <u32>) {
    debug_assert!(range.end <= self.instance_vertices.len() as u32);
    self.instanced_aabb_lines = range;
  }

  #[inline]
  pub const fn instanced_aabb_triangles (&self) -> &std::ops::Range <u32> {
    &self.instanced_aabb_triangles
  }

  #[inline]
  pub fn set_instanced_aabb_triangles (&mut self, range : std::ops::Range <u32>) {
    debug_assert!(range.end <= self.instance_vertices.len() as u32);
    self.instanced_aabb_triangles = range;
  }

  #[inline]
  pub const fn instanced_meshes (&self) -> &VecMap <InstancedMesh> {
    &self.instanced_meshes.meshes
  }

  #[inline]
  pub fn set_instanced_mesh (&mut self,
    mesh_key : MeshKey, mesh : InstancedMesh
  ) {
    let _ = self.instanced_meshes.meshes.insert (mesh_key.index(), mesh);
  }

  /// Re-builds instanced buffers to include given instanced meshes. The
  /// provided instanced mesh keys must not overlap with any of the built-in
  /// `MeshId`s.
  pub fn rebuild_instanced_meshes (&mut self,
    glium_display : &glium::Display <glutin::surface::WindowSurface>,
    user_meshes   : Vec <(MeshKey, Mesh, DrawPass)>
  ) {
    self.instanced_meshes = InstancedMeshes::new (glium_display, user_meshes);
  }

  /// Creates a new vertex buffer holding per-instance 3D vertices for various
  /// instanced meshes (grid, hemisphere, sphere, cylinder, capsule), AABBs, and
  /// tile billboards, and sets the instanced ranges corresponding to each
  pub fn instance_vertices_set (&mut self,
    glium_display  : &glium::Display <glutin::surface::WindowSurface>,
    instances_init : InstancesInit
  ) {
    let mut instance_vertices =
      Vec::with_capacity (instances_init.instance_count());

    self.instanced_aabb_lines     = 0..0;
    self.instanced_aabb_triangles = 0..0;
    for mesh in self.instanced_meshes.meshes.values_mut() {
      mesh.instances_range = 0..0;
    }
    // aabbs: we allow the ranges for lines and triangles to overlap so that
    // aabb_lines_and_triangles can be placed between the lines-only and
    // triangles-only ranges
    if let Some (instances) = instances_init.aabb_lines {
      // lines only
      let start = instance_vertices.len() as u32;
      instance_vertices.extend_from_slice (instances);
      let end   = instance_vertices.len() as u32;
      self.instanced_aabb_lines = start..end;
    }
    if let Some (instances) = instances_init.aabb_lines_and_triangles {
      // lines and triangles
      let start = instance_vertices.len() as u32;
      instance_vertices.extend_from_slice (instances);
      let end   = instance_vertices.len() as u32;
      if self.instanced_aabb_lines.end != 0 {
        debug_assert!(instances_init.aabb_lines.is_none());
        self.instanced_aabb_lines.start = start;
      }
      self.instanced_aabb_lines.end = end;
      self.instanced_aabb_triangles = start..end;
    }
    if let Some (instances) = instances_init.aabb_triangles {
      // triangles only
      let start = instance_vertices.len() as u32;
      instance_vertices.extend_from_slice (instances);
      let end   = instance_vertices.len() as u32;
      if self.instanced_aabb_triangles.end == 0 {
        debug_assert!(instances_init.aabb_lines_and_triangles.is_none());
        self.instanced_aabb_triangles.start = start;
      }
      self.instanced_aabb_triangles.end = end;
    }

    // meshes
    for (mesh_key, instances) in instances_init.meshes.into_iter() {
      let start = instance_vertices.len() as u32;
      instance_vertices.extend_from_slice (instances);
      let end   = instance_vertices.len() as u32;
      self.instanced_meshes.meshes[mesh_key].instances_range = start..end;
    }

    // billboards
    for (billboard_key, instances) in instances_init.billboards.into_iter() {
      let start = instance_vertices.len() as u32;
      instance_vertices.extend_from_slice (instances);
      let end   = instance_vertices.len() as u32;
      self.instanced_billboards[billboard_key].instances_range = start..end;
    }

    // create per instance vertex buffer
    self.instance_vertices = glium::VertexBuffer::dynamic (
      glium_display, instance_vertices.as_slice()
    ).unwrap();
  }

  #[inline]
  pub fn instance_vertices_aabb_lines_write (&self,
    vertex_data : &[vertex::Vert3dOrientationScaleColor]
  ) {
    let range =
      self.instanced_aabb_lines.start as usize..
      self.instanced_aabb_lines.end   as usize;
    self.instance_vertices.slice (range).unwrap().write (vertex_data);
  }

  #[inline]
  pub fn instance_vertices_aabb_triangles_write (&self,
    vertex_data : &[vertex::Vert3dOrientationScaleColor]
  ) {
    let range =
      self.instanced_aabb_triangles.start as usize..
      self.instanced_aabb_triangles.end   as usize;
    self.instance_vertices.slice (range).unwrap().write (vertex_data);
  }

  #[inline]
  pub fn instance_vertices_billboard_write (&self,
    billboard_key : usize,
    vertex_data   : &[vertex::Vert3dOrientationScaleColor]
  ) {
    let range = {
      let range = self.instanced_billboards[billboard_key].instances_range.clone();
      range.start as usize..range.end as usize
    };
    self.instance_vertices.slice (range).unwrap().write (vertex_data);
  }

  #[inline]
  pub fn instance_vertices_mesh_write (&self,
    mesh_key    : usize,
    vertex_data : &[vertex::Vert3dOrientationScaleColor]
  ) {
    let range = {
      let range = self.instanced_meshes.meshes[mesh_key].instances_range.clone();
      range.start as usize..range.end as usize
    };
    self.instance_vertices.slice (range).unwrap().write (vertex_data);
  }

  /// Create a new instanced billboard by blitting a string of tiles to a new
  /// texture.
  ///
  /// Panics if billboard texture with key already exists.
  pub fn tile_billboard_create (&mut self,
    glium_display   : &glium::Display <glutin::surface::WindowSurface>,
    tileset_texture : &glium::Texture2d,
    billboard_key   : usize,
    instances_range : std::ops::Range <u32>,
    string          : &str
  ) {
    use glium::Surface;
    debug_assert_eq!(0, tileset_texture.width() %16);
    debug_assert_eq!(0, tileset_texture.height()%16);
    let tile_width  = tileset_texture.width()  / 16;
    let tile_height = tileset_texture.height() / 16;
    let texture = glium::Texture2d::empty_with_mipmaps (
      glium_display, glium::texture::MipmapsOption::NoMipmap,
      tile_width * string.len() as u32, tile_height
    ).unwrap();
    { // blit tiles from default tileset
      let source     = tileset_texture.as_surface();
      let mut target = texture.as_surface();
      target.clear_color (1.0, 0.0, 1.0, 1.0);
      for (i,ch) in string.chars().enumerate() {
        let tile = ch as u32;
        // NB: (0,0) is bottom-left in texture pixel space
        let source_rect = glium::Rect {
          left:   tile_width  * (tile % 16),
          bottom: tile_height * (15 - tile / 16),
          width:  tile_width,
          height: tile_height
        };
        #[expect(clippy::identity_op)]
        let target_rect = glium::BlitTarget {
          left:   0 + i as u32 * tile_width,
          bottom: 0,
          width:  tile_width  as i32,
          height: tile_height as i32
        };
        target.blit_from_simple_framebuffer (
          &source, &source_rect, &target_rect,
          glium::uniforms::MagnifySamplerFilter::Linear);
      }
    }
    let instanced_billboard = InstancedBillboard { texture, instances_range };
    assert!(self.instanced_billboards.insert (
      billboard_key, instanced_billboard
    ).is_none());
  }
}

impl InstancesInit <'_> {
  pub fn instance_count (&self) -> usize {
    let mut count = 0;
    count += self.aabb_lines.map_or(0, <[_]>::len);
    count += self.aabb_triangles.map_or(0, <[_]>::len);
    for (_, mesh_data) in self.meshes.iter() {
      count += mesh_data.len();
    }
    for (_, billboard_data) in self.billboards.iter() {
      count += billboard_data.len();
    }
    count
  }
}

impl InstancedMeshes {
  fn new (
    glium_display : &glium::Display <glutin::surface::WindowSurface>,
    user_meshes   : Vec <(MeshKey, Mesh, DrawPass)>
  ) -> Self {
    let InstancedMeshInit {
      instanced_vertex_data,
      instanced_line_index_data,
      line_indices_ranges,
      shader_program_ids,
      draw_passes,
      capsule_vertex_id_offset,
      hemisphere_vertex_count
    } = InstancedMeshInit::new (user_meshes);
    let vertices     = glium::VertexBuffer::dynamic (
      glium_display, instanced_vertex_data.as_slice()
    ).unwrap();
    let line_indices = glium::IndexBuffer::dynamic (
      glium_display, glium::index::PrimitiveType::LinesList,
      instanced_line_index_data.as_slice()
    ).unwrap();
    let meshes       = {
      let mut v = VecMap::new();
      for (mesh_key, line_indices_range) in line_indices_ranges.into_iter() {
        let instanced_mesh = InstancedMesh {
          line_indices_range,
          instances_range: 0..0,  // empty
          shader_program_id: shader_program_ids[mesh_key],
          draw_pass:         draw_passes[mesh_key]
        };
        assert!(v.insert (mesh_key, instanced_mesh).is_none());
      }
      v
    };
    InstancedMeshes {
      vertices, line_indices, meshes, capsule_vertex_id_offset,
      hemisphere_vertex_count
    }
  }
}

impl InstancedMeshInit {
  fn new (user_meshes : Vec <(MeshKey, Mesh, DrawPass)>) -> Self {
    const GRID_DIMS                 : u16 = MESH_GRID_DIMS;
    const HEMISPHERE_LATITUDE_DIVS  : u16 = 6;
    const SPHERE_LATITUDE_DIVS      : u16 = 2 * HEMISPHERE_LATITUDE_DIVS;
    const LONGITUDE_DIVS            : u16 = 24;
    const CYLINDER_DIVS             : u16 = LONGITUDE_DIVS;
    let mut instanced_vertex_data     = Vec::new();
    let mut instanced_line_index_data = Vec::new();
    // constant value to shift all indices during mesh creation
    let mut index_offset      = 0;
    // the beginning of the range where indices begin for the next mesh
    let mut index_range_start = 0;

    let mut line_indices_ranges = VecMap::with_capacity (MeshId::COUNT);
    let mut shader_program_ids  = VecMap::with_capacity (MeshId::COUNT);
    let mut draw_passes         = VecMap::with_capacity (MeshId::COUNT);

    // grid
    let mesh::Lines3d {
      vertices: mut grid_vertex_data, indices: mut grid_index_data
    } = mesh::Lines3d::grid (index_offset, GRID_DIMS);
    assert!(line_indices_ranges.insert (
      MeshId::Grid as usize,
      index_range_start..index_range_start + grid_index_data.len() as u32
    ).is_none());
    assert!(shader_program_ids.insert (
      MeshId::Grid as usize,
      shader::ProgramId::ModelSpace3dInstancedOrientationScaleColor
    ).is_none());
    assert!(draw_passes.insert (MeshId::Grid as usize, DrawPass::Depth).is_none());
    instanced_vertex_data.append (&mut grid_vertex_data);
    instanced_line_index_data.append  (&mut grid_index_data);
    index_offset      = instanced_vertex_data.len() as u32;
    index_range_start = instanced_line_index_data.len() as u32;

    // capsule: vertex and index data will be shared with sphere and hemisphere
    // meshes
    let capsule_vertex_id_offset = index_offset; // uniform used by capsule shader
    let mesh::Lines3d {
      vertices: mut capsule_vertex_data,
      indices:  mut capsule_index_data
    } = mesh::Lines3d::capsule (index_offset, HEMISPHERE_LATITUDE_DIVS, LONGITUDE_DIVS);
    let capsule_line_indices_range =
      index_range_start..index_range_start + capsule_index_data.len() as u32;
    assert!(line_indices_ranges.insert (
      MeshId::Capsule as usize, capsule_line_indices_range.clone()
    ).is_none());
    assert!(shader_program_ids.insert (
      MeshId::Capsule as usize,
      shader::ProgramId::ModelSpace3dInstancedCapsule
    ).is_none());
    assert!(draw_passes.insert (MeshId::Capsule as usize, DrawPass::Depth).is_none());
    instanced_vertex_data.append (&mut capsule_vertex_data);
    instanced_line_index_data.append  (&mut capsule_index_data);

    index_offset      = instanced_vertex_data.len() as u32;
    index_range_start = instanced_line_index_data.len() as u32;

    // hemisphere: this is defined to share the top half of the vertices and
    // indices of the capsule mesh
    let (hemisphere_vertex_count, hemisphere_index_count) =
      mesh::hemisphere::lines3d_vertex_index_counts (
        HEMISPHERE_LATITUDE_DIVS, LONGITUDE_DIVS);
    assert!(line_indices_ranges.insert (
      MeshId::Hemisphere as usize,
      capsule_line_indices_range.start..
      capsule_line_indices_range.start + hemisphere_index_count
    ).is_none());
    assert!(shader_program_ids.insert (
      MeshId::Hemisphere as usize,
      shader::ProgramId::ModelSpace3dInstancedScaleColor
    ).is_none());
    assert!(draw_passes.insert (MeshId::Hemisphere as usize, DrawPass::Depth)
      .is_none());

    // sphere: defined to use part of the capsule mesh indices except for the
    // extra equator lines and cylinder lines
    let (_, sphere_index_count) = mesh::sphere::lines3d_vertex_index_counts (
      SPHERE_LATITUDE_DIVS, LONGITUDE_DIVS);
    assert!(line_indices_ranges.insert (
      MeshId::Sphere as usize,
      capsule_line_indices_range.start..
      capsule_line_indices_range.start + sphere_index_count
    ).is_none());
    assert!(shader_program_ids.insert (
      MeshId::Sphere as usize,
      shader::ProgramId::ModelSpace3dInstancedScaleColor
    ).is_none());
    assert!(draw_passes.insert (MeshId::Sphere as usize, DrawPass::Depth)
      .is_none());

    // cylinder
    let mesh::Lines3d {
      vertices: mut cylinder_vertex_data, indices: mut cylinder_index_data
    } = mesh::Lines3d::cylinder (index_offset, CYLINDER_DIVS);
    assert!(line_indices_ranges.insert (
      MeshId::Cylinder as usize,
      index_range_start..index_range_start + cylinder_index_data.len() as u32
    ).is_none());
    assert!(shader_program_ids.insert (
      MeshId::Cylinder as usize,
      shader::ProgramId::ModelSpace3dInstancedScaleColor
    ).is_none());
    assert!(draw_passes.insert (MeshId::Cylinder as usize, DrawPass::Depth)
      .is_none());
    instanced_vertex_data.append (&mut cylinder_vertex_data);
    instanced_line_index_data.append  (&mut cylinder_index_data);

    index_offset      = instanced_vertex_data.len()     as u32;
    index_range_start = instanced_line_index_data.len() as u32;

    // cube
    let mesh::Lines3d {
      vertices: mut cube_vertex_data, indices: mut cube_index_data
    } = mesh::Lines3d::cube (index_offset);
    assert!(line_indices_ranges.insert (
      MeshId::Cube as usize,
      index_range_start..index_range_start + cube_index_data.len() as u32
    ).is_none());
    assert!(shader_program_ids.insert (
      MeshId::Cube as usize,
      shader::ProgramId::ModelSpace3dInstancedOrientationScaleColor
    ).is_none());
    assert!(draw_passes.insert (MeshId::Cube as usize, DrawPass::Depth).is_none());
    instanced_vertex_data.append (&mut cube_vertex_data);
    instanced_line_index_data.append  (&mut cube_index_data);

    // NB: the following is not required between meshes that share all vertices
    // comment this out between each new mesh when adding more meshes here:
    //index_offset      = instanced_vertex_data.len()     as u32;
    //index_range_start = instanced_line_index_data.len() as u32;

    // user meshes
    let num_user_meshes = user_meshes.len();
    for (mesh_key, mut mesh, draw_pass) in user_meshes {
      debug_assert!(mesh_key.index() >= MeshId::COUNT);
      index_offset      = instanced_vertex_data.len()     as u32;
      index_range_start = instanced_line_index_data.len() as u32;
      let mut insert_mesh = |vertices : &mut Vec <_>, indices : &mut Vec <u32>| {
        indices.iter_mut().for_each (|ix| *ix += index_offset);
        assert!(line_indices_ranges.insert (
          mesh_key.index(),
          index_range_start..index_range_start + indices.len() as u32
        ).is_none());
        assert!(shader_program_ids.insert (
          mesh_key.index(),
          shader::ProgramId::ModelSpace3dInstancedOrientationScaleColor
        ).is_none());
        assert!(draw_passes.insert (mesh_key.index(), draw_pass).is_none());
        instanced_vertex_data.append (vertices);
        instanced_line_index_data.append (indices);
      };
      match mesh {
        Mesh::Points3d (mesh::Points3d { ref mut vertices, ref mut indices }) |
        Mesh::Lines3d (mesh::Lines3d { ref mut vertices, ref mut indices }) |
        Mesh::Triangles3d (mesh::Triangles3d { ref mut vertices, ref mut indices }) =>
          insert_mesh (vertices, indices)
      }
    }

    debug_assert_eq!(line_indices_ranges.len(), MeshId::COUNT + num_user_meshes);
    debug_assert_eq!(shader_program_ids.len(),  MeshId::COUNT + num_user_meshes);

    InstancedMeshInit {
      instanced_vertex_data,
      instanced_line_index_data,
      line_indices_ranges,
      shader_program_ids,
      draw_passes,
      capsule_vertex_id_offset,
      hemisphere_vertex_count
    }
  }
}

impl MeshKey {
  pub const fn index (self) -> usize {
    self.0 as usize
  }
}

impl UserBufferKey {
  pub const fn index (self) -> usize {
    self.0 as usize
  }
}