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
//! A trait for resource types with arbitrary `draw` functionality and a
//! default implementation that supports switching to a "quad viewport" mode.

use std::iter::FromIterator;
use std::ops::Deref;
use std::sync::LazyLock;

use glium;
use image;
use strum::{EnumCount, EnumIter, FromRepr};
use vec_map::VecMap;
use winit;

use math_utils as math;

use crate::{color, shader, texture, vertex, Render};

pub mod draw2d;
pub mod draw3d;
#[cfg(feature="demo")]
#[cfg_attr(docsrs, doc(cfg(feature="demo")))]
pub mod demo;

pub use self::draw2d::Draw2d;
pub use self::draw3d::Draw3d;

////////////////////////////////////////////////////////////////////////////////
//  constants                                                                 //
////////////////////////////////////////////////////////////////////////////////

pub const MAIN_VIEWPORT        : usize = 0;
pub const LOWER_RIGHT_VIEWPORT : usize = MAIN_VIEWPORT;
pub const UPPER_LEFT_VIEWPORT  : usize = 1;
pub const UPPER_RIGHT_VIEWPORT : usize = 2;
pub const LOWER_LEFT_VIEWPORT  : usize = 3;
pub const OVERLAY_VIEWPORT     : usize = 4;

////////////////////////////////////////////////////////////////////////////////
//  statics                                                                   //
////////////////////////////////////////////////////////////////////////////////

static DEFAULT_TEXTURES_16X16_BYTES : LazyLock <VecMap <&'static [u8]>> =
  LazyLock::new (|| VecMap::from_iter ([
    ( DefaultTexture16Id::Crosshair         as usize,
      texture::CROSSHAIR_PNG_FILE_BYTES.as_slice()
    ), (
      DefaultTexture16Id::CrosshairInverse  as usize,
      texture::CROSSHAIR_INVERSE_PNG_FILE_BYTES.as_slice()
    )
  ]));

static DEFAULT_TEXTURES_POINTER_BYTES_OFFSETS :
  LazyLock <VecMap <(&'static [u8], [i16; 2])>> = LazyLock::new (|| VecMap::from_iter ([
    ( DefaultTexturePointerId::Hand as usize,
      ( texture::POINTER_HAND_PNG_FILE_BYTES_OFFSET.0.as_slice(),
        texture::POINTER_HAND_PNG_FILE_BYTES_OFFSET.1
      )
    )
  ]));

////////////////////////////////////////////////////////////////////////////////
//  typedefs                                                                  //
////////////////////////////////////////////////////////////////////////////////

pub type PointerTextureIndexRepr = u16;

////////////////////////////////////////////////////////////////////////////////
//  traits                                                                    //
////////////////////////////////////////////////////////////////////////////////

/// Represents a generic Glium resource type for a renderer to use as a source
/// of *drawing* (vertex rendering).
///
/// The resource should have all the shader programs, vertex buffers, textures,
/// etc. necessary to make a `draw` call on a given `glium::Frame`.
///
/// The default frame functions will call the `draw_2d` and `draw_3d` methods,
/// which do nothing by default.
pub trait Resource {
  fn new (glium_display : &glium::Display <glutin::surface::WindowSurface>)
    -> Self;
  fn init (_render : &mut Render <Self>) where Self : Sized
    { /* default: do nothing */ }
  /// Default replace self with `Self::new`. Can be overridden.
  fn reset (render : &mut Render <Self>)  where Self : Sized {
    render.resource = Self::new (&render.glium_display)
  }
  fn draw_2d (_render : &Render <Self>, _glium_frame : &mut glium::Frame) where
    Self : Sized { /* default: do nothing */ }
  fn draw_3d (_render : &Render <Self>, _glium_frame : &mut glium::Frame) where
    Self : Sized { /* default: do nothing */ }
}

////////////////////////////////////////////////////////////////////////////////
//  structs                                                                   //
////////////////////////////////////////////////////////////////////////////////

/// A default implementation of `Resource` containing the builtin shader programs and
/// some pre-defined vertex sources.
pub struct Default {
  pub draw2d : Draw2d,
  pub draw3d : Draw3d,
  /// Textures of heterogeneous dimensions
  pub textures_anysize        : VecMap <glium::texture::Texture2d>,
  /// Custom pointer textures with offsets for non-centered cursors
  pub textures_pointer : VecMap <(glium::texture::Texture2d, math::Vector2 <i16>)>,
  /// 128x128 pixel tileset texture with 8x8 tile dimensions
  pub tileset_128x128_texture : glium::texture::Texture2d,
  /// 256x256 pixel tileset texture with 16x16 tile dimensions
  pub tileset_256x256_texture : glium::texture::Texture2d,
  // TODO: more tilesets?
  shader_programs             : VecMap <glium::Program>,
  /// Default 16x16 textures indexed by `DefaultTexture16Id`
  default_textures_16x16      : glium::texture::Texture2dArray,
  /// Texture array of 16x16 pixel general purpose textures
  textures_16x16              : glium::texture::Texture2dArray,
  /// Texture array of 64x64 pixel general purpose textures
  textures_64x64              : glium::texture::Texture2dArray
}

////////////////////////////////////////////////////////////////////////////////
//  enums                                                                     //
////////////////////////////////////////////////////////////////////////////////

#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd, EnumCount, EnumIter,
  FromRepr)]
#[repr(u16)]
pub enum DefaultTexturePointerId {
  Hand
}

#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd, EnumCount, EnumIter,
  FromRepr)]
#[repr(u16)]
pub enum DefaultTexture16Id {
  // for use with `BLEND_FUNC_NORMAL`
  Crosshair,
  // for use with `BLEND_FUNC_INVERT_COLOR`
  CrosshairInverse
}

#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd, EnumCount, EnumIter,
  FromRepr)]
#[repr(u16)]
#[derive(Default)]
pub enum DefaultTilesetId {
  // for use with `BLEND_FUNC_NORMAL`
  #[default]
  EasciiAcorn128,
  EasciiAcorn256,
  // for use with `BLEND_FUNC_INVERT_COLOR`
  EasciiAcornInverse128,
  EasciiAcornInverse256
}

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

impl Default {
  /// Default debug grid vertices (3): [X plane (red), Y plane (green), Z plane
  /// (blue)]
  pub fn debug_grid_vertices() -> [vertex::Vert3dOrientationScaleColor; 3] {
    use std::f32::consts::FRAC_PI_2;
    const HALF_GRID_DIMS : f32 = 0.5 * draw3d::MESH_GRID_DIMS as f32;
    [
      // X plane
      vertex::Vert3dOrientationScaleColor {
        position:    [HALF_GRID_DIMS, 0.0, HALF_GRID_DIMS],
        orientation: (*math::Rotation3::from_angle_y (math::Rad (FRAC_PI_2)))
          .into_col_arrays(),
        scale:       [1.0, 1.0, 1.0],
        color:       color::rgba_u8_to_rgba_f32 ([255, 0, 0, 255])
      },
      // Y plane
      vertex::Vert3dOrientationScaleColor {
        position:    [0.0, HALF_GRID_DIMS, HALF_GRID_DIMS],
        orientation: (*math::Rotation3::from_angle_x (math::Rad (FRAC_PI_2)))
          .into_col_arrays(),
        scale:       [1.0, 1.0, 1.0],
        color:       color::rgba_u8_to_rgba_f32 ([0, 255, 0, 255])
      },
      // Z plane
      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 ([0, 0, 255, 255])
      }
    ]
  }
  /// Returns tile pixel [width, height] of the tileset.
  #[inline]
  pub fn tile_dimensions (&self, tileset_id : DefaultTilesetId) -> [u32; 2] {
    let (width, height) = match tileset_id {
      DefaultTilesetId::EasciiAcorn128 =>
        self.tileset_128x128_texture.dimensions(),
      DefaultTilesetId::EasciiAcorn256 =>
        self.tileset_256x256_texture.dimensions(),
      _ => unimplemented!()
    };
    debug_assert_eq!(width  % 16, 0);
    debug_assert_eq!(height % 16, 0);
    [width / 16, height / 16]
  }
  #[inline]
  pub const fn shader_programs (&self) -> &VecMap <glium::Program> {
    &self.shader_programs
  }
  #[inline]
  pub fn set_pointer_position (&mut self,
    display  : &glium::Display <glutin::surface::WindowSurface>,
    position : math::Point2 <f32>
  ) {
    let offset = self.draw2d.draw_pointer.map_or (
      math::Vector2::zero(),
      |texture_index| self.textures_pointer.get (texture_index as usize)
        .unwrap().1.numcast().unwrap()
    );
    self.draw2d.set_pointer_vertex (display, position + offset);
  }
  #[inline]
  pub fn set_textures_16x16 (&mut self,
    textures_16x16 : glium::texture::Texture2dArray
  ) {
    assert_eq!(textures_16x16.width(),  16);
    assert_eq!(textures_16x16.height(), 16);
    self.textures_16x16 = textures_16x16;
  }
  #[inline]
  pub fn set_textures_64x64 (&mut self,
    textures_64x64 : glium::texture::Texture2dArray
  ) {
    assert_eq!(textures_64x64.width(),  64);
    assert_eq!(textures_64x64.height(), 64);
    self.textures_64x64 = textures_64x64;
  }
}

impl Resource for Default {
  fn new (glium_display : &glium::Display <glutin::surface::WindowSurface>) -> Self {
    // shaders
    let shader_programs  = shader::build_programs (glium_display).unwrap();
    // shared resources
    let default_textures_16x16 =
      texture::texture2darray_with_mipmaps_from_bytes (
        glium_display,
        &DEFAULT_TEXTURES_16X16_BYTES.values().map (Deref::deref)
          .collect::<Vec <&[u8]>>(),
        image::ImageFormat::Png,
        glium::texture::MipmapsOption::NoMipmap
      ).unwrap();
    let textures_16x16   =
      glium::texture::Texture2dArray::empty (glium_display, 16, 16, 0).unwrap();
    let textures_64x64   =
      glium::texture::Texture2dArray::empty (glium_display, 64, 64, 0).unwrap();
    let textures_anysize = VecMap::new();
    let textures_pointer = DEFAULT_TEXTURES_POINTER_BYTES_OFFSETS.iter()
      .map (|(i, (bytes, offset))|{
        let texture = texture::texture2d_with_mipmaps_from_bytes (
          glium_display, bytes, image::ImageFormat::Png,
          glium::texture::MipmapsOption::NoMipmap
        ).unwrap();
        (i, (texture, math::Vector2::from (*offset)))
      }).collect();
    let tileset_128x128_texture = texture::texture2d_with_mipmaps_from_bytes (
      glium_display,
      // for use with normal blending
      texture::TILESET_EASCII_ACORN_8X8_PNG_FILE_BYTES,
      image::ImageFormat::Png,
      glium::texture::MipmapsOption::NoMipmap
    ).unwrap();
    let tileset_256x256_texture = texture::texture2d_with_mipmaps_from_bytes (
      glium_display,
      // for use with normal blending
      texture::TILESET_EASCII_ACORN_16X16_PNG_FILE_BYTES,
      image::ImageFormat::Png,
      glium::texture::MipmapsOption::NoMipmap
    ).unwrap();
    // TODO
    /*
    let tileset_128x128_inverse_texture =
      texture::texture2d_with_mipmaps_from_bytes (
        glium_display,
        // for use with inverse blending
        texture::TILESET_EASCII_ACORN_8X8_INVERSE_PNG_FILE_BYTES,
        image::PNG,
        glium::texture::MipmapsOption::NoMipmap
      ).unwrap();
    */

    let draw2d = Draw2d::new (glium_display);
    let draw3d = Draw3d::new (glium_display);

    Default {
      shader_programs,
      default_textures_16x16,
      textures_16x16,
      textures_64x64,
      textures_anysize,
      textures_pointer,
      tileset_128x128_texture,
      tileset_256x256_texture,
      draw2d,
      draw3d
    }
  }

  #[inline]
  fn init (render : &mut Render <Self>) {
    render.update_viewport_line_loops();
  }

  #[inline]
  fn draw_2d (render : &Render <Self>, glium_frame : &mut glium::Frame) {
    Draw2d::draw (render, glium_frame);
  }

  #[inline]
  fn draw_3d (render : &Render <Self>, glium_frame : &mut glium::Frame) {
    Draw3d::draw (render, glium_frame);
  } // end fn draw_3d

  #[inline]
  fn reset (render : &mut Render <Self>) {
    render.resource.draw2d = Draw2d::new (&render.glium_display);
    render.resource.draw3d = Draw3d::new (&render.glium_display);
  }
} // end impl Resource for DefaultResource

impl Render <Default> {

  #[inline]
  pub fn camera3d_position_set (&mut self, position : math::Point3 <f32>) {
    for (_, viewport) in self.viewports.iter_mut() {
      if viewport.camera3d().is_some() {
        viewport.camera3d_set_position (position);
      }
    }
  }

  #[inline]
  pub fn camera3d_orientation_set (&mut self,
    orientation : math::Rotation3 <f32>
  ) {
    for (_, viewport) in self.viewports.iter_mut() {
      if viewport.camera3d().is_some() {
        viewport.camera3d_set_orientation (orientation);
      }
    }
  }

  #[inline]
  pub fn camera3d_look_at (&mut self, target : math::Point3 <f32>) {
    for (_, viewport) in self.viewports.iter_mut() {
      if viewport.camera3d().is_some() {
        viewport.camera3d_look_at (target);
      }
    }
  }

  pub fn camera3d_move_local_xy (&mut self, dx : f32, dy : f32, dz : f32) {
    self.viewports[MAIN_VIEWPORT].camera3d_move_local_xy (dx, dy, dz);
    let position = self.viewports[MAIN_VIEWPORT].camera3d().unwrap().position();
    for (_, viewport) in self.viewports.iter_mut().skip (1) {
      if viewport.camera3d().is_some() {
        viewport.camera3d_set_position (position);
      }
    }
  }

  #[inline]
  pub fn camera3d_rotate (&mut self,
    dyaw : math::Rad <f32>, dpitch : math::Rad <f32>, droll : math::Rad <f32>
  ) {
    self.viewports[MAIN_VIEWPORT].camera3d_rotate (dyaw, dpitch, droll);
  }

  /// Scales 3D zoom of viewports 1-3.
  ///
  /// Does nothing in single viewport mode.
  ///
  /// # Panics
  ///
  /// Panics if scale is negative.
  pub fn camera3d_orthographic_zoom_scale (&mut self, scale : f32) {
    assert!(0.0 < scale);
    for (_, viewport) in self.viewports.iter_mut().skip(1) {
      if viewport.camera3d().is_some() {
        debug_assert!(viewport.camera3d().unwrap().projection()
          .is_orthographic());
        viewport.camera3d_scale_fovy_or_zoom (scale);
      }
    }
  }

  /// Scales 3D zoom of viewport 0 (the main viewport) only.
  ///
  /// # Panics
  ///
  /// Panics if scale is negative.
  pub fn camera3d_perspective_fovy_scale (&mut self, scale : f32) {
    assert!(0.0 < scale);
    debug_assert!(self.viewports[MAIN_VIEWPORT].camera3d().unwrap().projection()
      .is_perspective());
    self.viewports[MAIN_VIEWPORT].camera3d_scale_fovy_or_zoom (scale);
  }

  pub fn camera2d_zoom_set (&mut self, zoom : f32) {
    assert!(0.0 < zoom);
    for (_, viewport) in self.viewports.iter_mut() {
      if viewport.camera2d().is_some() {
        viewport.camera2d_set_zoom (zoom);
      }
    }
    self.update_viewport_line_loops();
  }

  /// Modifies the 2D zoom by the given amount for all viewports.
  pub fn camera2d_zoom_shift (&mut self, shift : f32) {
    let mut dirty = false;
    for (_, viewport) in self.viewports.iter_mut() {
      if viewport.camera2d().is_some() {
        let zoom = viewport.camera2d().unwrap().zoom() + shift;
        if 0.0 < zoom {
          viewport.camera2d_set_zoom (zoom);
          dirty = true;
        }
      }
    }
    if dirty {
      self.update_viewport_line_loops();
    }
  }

  pub fn camera2d_move_local (&mut self, dx : f32, dy : f32) {
    self.viewports[MAIN_VIEWPORT].camera2d_move_local (dx, dy);
    let position = self.viewports[MAIN_VIEWPORT].camera2d().unwrap().position();
    for (_, viewport) in self.viewports.iter_mut().skip (1) {
      if viewport.camera2d().is_some() {
        viewport.camera2d_set_position (position);
      }
    }
  }

  /// Moves origin for all viewports to lower left
  pub fn camera2d_move_origin_to_bottom_left (&mut self) {
    for (_, viewport) in self.viewports.iter_mut() {
      if viewport.camera2d().is_some() {
        viewport.camera2d_move_origin_to_bottom_left()
      }
    }
    self.update_viewport_line_loops();
  }

  /// Resize the viewport(s) based on the `LogicalSize` that was returned by a
  /// `WindowEvent::Resized` event
  // TODO: come up with a better scheme for quad viewports, overlay viewports
  pub fn window_resized (&mut self,
    physical_size : winit::dpi::PhysicalSize <u32>
  ) {
    let (width, height) = physical_size.into();
    if self.viewports.len() < 4 {
      self.viewports[MAIN_VIEWPORT].set_rect (
        glium::Rect { left: 0, bottom: 0, width, height }
      );
      self.viewports.get_mut (OVERLAY_VIEWPORT).map (|viewport|
        viewport.set_rect (glium::Rect { left: 0, bottom: 0, width, height }));
    } else {
      // quad viewports
      let left_width    = left_width   (width);
      let right_width   = right_width  (width);
      let upper_height  = upper_height (height);
      let lower_height  = lower_height (height);
      self.viewports[LOWER_RIGHT_VIEWPORT].set_rect (
        glium::Rect {
          width:  right_width,
          height: lower_height,
          left:   left_width,
          bottom: 0
        }
      );
      self.viewports[UPPER_LEFT_VIEWPORT].set_rect (
        glium::Rect {
          width:  left_width,
          height: upper_height,
          left:   0,
          bottom: lower_height
        }
      );
      self.viewports[UPPER_RIGHT_VIEWPORT].set_rect (
        glium::Rect {
          width:  right_width,
          height: upper_height,
          left:   left_width,
          bottom: lower_height
        }
      );
      self.viewports[LOWER_LEFT_VIEWPORT].set_rect (
        glium::Rect {
          width:  left_width,
          height: lower_height,
          left:   0,
          bottom: 0
        }
      );
      self.viewports.get_mut (OVERLAY_VIEWPORT).map (|viewport|
        viewport.set_rect (glium::Rect { left: 0, bottom: 0, width, height }));
    }
    self.update_viewport_line_loops();
  }

  /// Updates vertex and index buffers for viewport line loops.
  ///
  /// Should be called whenever viewport sizes or 2D camera zoom or position
  /// changes.
  fn update_viewport_line_loops (&mut self) {
    const VERTS_PER_VIEWPORT : usize = 4;
    let num_vertices = VERTS_PER_VIEWPORT * self.viewports.len();
    let vertices = {
      let mut vertices = Vec::<vertex::Vert2d>::with_capacity (num_vertices);
      for (_, viewport) in self.viewports.iter() {
        if let Some (camera2d) = viewport.camera2d() {
          // pixels are centered on 0.5 unit centers
          let pixel_radius = 0.5 / camera2d.zoom();
          let position     = camera2d.position();
          let ortho        = camera2d.ortho();
          let left         = position.0.x + ortho.left;
          let bottom       = position.0.y + ortho.bottom;
          let top          = position.0.y + ortho.top;
          let right        = position.0.x + ortho.right;
          vertices.append (&mut vec![
            vertex::Vert2d {
              position: [left  + pixel_radius, bottom + pixel_radius] },
            vertex::Vert2d {
              position: [left  + pixel_radius, top    - pixel_radius] },
            vertex::Vert2d {
              position: [right - pixel_radius, top    - pixel_radius] },
            vertex::Vert2d {
              position: [right - pixel_radius, bottom + pixel_radius] }
          ]);
        }
      }
      vertices
    };
    self.resource.draw2d
      .line_loop_vertices_set (&self.glium_display, &vertices[..]);
  }
}


////////////////////////////////////////////////////////////////////////////////
//  private functions                                                         //
////////////////////////////////////////////////////////////////////////////////

// some functions to compute viewport widths for odd window dimensions:
// right viewports will be 1 pixel wider on odd width windows and bottom
// viewports will be 1 pixel taller on odd height windows

#[inline]
const fn left_width (window_width : u32) -> u32 {
  window_width / 2
}
#[inline]
const fn right_width (window_width : u32) -> u32 {
  window_width / 2 + window_width % 2
}
#[inline]
const fn upper_height (window_height : u32) -> u32 {
  window_height / 2
}
#[inline]
const fn lower_height (window_height : u32) -> u32 {
  window_height / 2 + window_height % 2
}