nsys-gl-utils 0.11.2

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

use crate::{camera2d, color, graphics, math, render, shader, vertex, Camera2d,
  Render};
use super::{DefaultTexture16Id, DefaultTilesetId, PointerTextureIndexRepr};

/// 2D drawing resources
pub struct Draw2d {
  // rectangles
  /// 2D rectangle vertices with sub-ranges mapped to viewports by
  /// `viewport_resources[i].draw_indices[j].rectangle`.
  pub rectangle_2d_vertices     : glium::VertexBuffer <vertex::Vert2dRectColor>,
  // line loops
  /// Vertices to be rendered as line loops
  pub line_loop_vertices        : glium::VertexBuffer <vertex::Vert2d>,
  // sprites
  /// Position and texture index of 2d sprites indexing the 16x16 texture array
  pub sprite_16x16_vertices     : glium::VertexBuffer <vertex::Vert2dLayer>,
  /// Position and texture index of 2d sprites indexing the 64x64 texture array
  pub sprite_64x64_vertices     : glium::VertexBuffer <vertex::Vert2dLayer>,
  /// Position and texture index of 2d textured rectangles indexing the 16x16
  /// texture array
  pub rectangle_16x16_vertices  :
    glium::VertexBuffer <vertex::Vert2dRectUvLayer>,
  /// Position and texture index of 2d textured rectangles indexing the 64x64
  /// texture array
  pub rectangle_64x64_vertices  :
    glium::VertexBuffer <vertex::Vert2dRectUvLayer>,
  pub rectangle_anysize_vertices :
    VecMap <glium::VertexBuffer <vertex::Vert2dRectUv>>,
  /// Position of optional pointer sprite
  pointer_vertex                : Option <glium::VertexBuffer <vertex::Vert2d>>,
  /// Draw the pointer vertex *if* the vertex has been set
  pub draw_pointer              : Option <PointerTextureIndexRepr>,
  /// Position and texture index of 2d sprites indexing the 16x16 texture array.
  /// This buffer contains built-in default vertices such as the crosshair
  /// vertex.
  default_sprite_16x16_vertices : glium::VertexBuffer <vertex::Vert2dLayer>,
  // tiles
  /// 2D tile vertices with sub-ranges mapped to viewports by
  /// `viewport_resources[i].draw_tiles[j].vertex_range`.
  pub tile_2d_vertices          : glium::VertexBuffer <vertex::Vert2dTile>,
  /// 2D tile vertices with sub-ranges mapped to viewports by
  /// `viewport_resources[i].draw_color_tiles[j].vertex_range`.
  pub tile_color_2d_vertices    : glium::VertexBuffer <vertex::Vert2dTileColor>,
  // viewport data
  /// Data used when drawing each viewport's 2D rectangles and tiles
  viewport_resources            : VecMap <ViewportResources>,
}

#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd, EnumCount, EnumIter,
  FromRepr)]
#[repr(u16)]
pub enum DefaultSprite16Id {
  // Index into `default_sprites_16x16_vertices` for the crosshair.
  //
  // In `draw_2d` this vertex is drawn as a separate draw call.
  Crosshair
}

/// Defines indices for drawing rectangles, tiles, and whether or not to draw
/// crosshair and line loop
#[derive(Clone, Debug)]
pub struct ViewportResources {
  pub draw_indices   : Vec <DrawIndices>,
  pub draw_crosshair : bool,
  pub draw_lineloop  : bool
}

/// Defines a set of rectangle and tile calls
#[derive(Clone, Debug, Default)]
pub struct DrawIndices {
  /// Index into the `rectangle_2d_vertices` buffer
  pub rectangle        : Option <u32>,
  /// Tile draw call
  pub draw_tiles       : Option <Tiles>,
  /// TileColor draw call
  pub draw_color_tiles : Option <Tiles>
}

/// Defines a draw call with the `tile_2d_vertices` buffer as a vertex source
#[derive(Clone, Debug)]
pub struct Tiles {
  /// Each range defines the tiles in the `tile_2d_vertices` or
  /// `tile_color_2d_vertices` to be drawn with the defined offset.
  pub vertex_range : std::ops::Range <u32>,
  /// Origin is either in world space or relative to upper-left corner of
  /// viewport
  pub origin       : TilesOrigin,
  pub tileset_id   : DefaultTilesetId
}

/// Selects the origin for a tile-based draw call
#[derive(Clone, Debug, From, TryInto)]
pub enum TilesOrigin {
  /// Origin is at the upper-left corner of the viewport.
  ///
  /// Offset can be used to shift the origin relative to the upper-left corner
  /// of the viewport.
  Viewport {
    /// A positive offset will shift the tile grid relative to the left of the
    /// viewport by this many pixels
    offset_px_left : i16,
    /// A positive offset will shift the tile grid downward from the top of the
    /// viewport by this many pixels
    offset_px_top  : i16
  },
  /// Origin is at the world origin
  World
}

impl Draw2d {
  pub fn new (glium_display : &glium::Display <glutin::surface::WindowSurface>)
    -> Self
  {
    let rectangle_2d_vertices =
      glium::VertexBuffer::dynamic (glium_display, &[ ]).unwrap();
    let pointer_vertex = None;
    let draw_pointer   = None;
    let default_sprite_16x16_vertices = glium::VertexBuffer::immutable (
      glium_display,
      // crosshair
      &[vertex::Vert2dLayer {
        position: [0.0, 0.0],
        layer:    DefaultTexture16Id::CrosshairInverse as u16
      }]
    ).unwrap();
    let sprite_16x16_vertices =
      glium::VertexBuffer::empty_immutable (glium_display, 0).unwrap();
    let sprite_64x64_vertices =
      glium::VertexBuffer::empty_immutable (glium_display, 0).unwrap();
    let rectangle_16x16_vertices =
      glium::VertexBuffer::empty_immutable (glium_display, 0).unwrap();
    let rectangle_64x64_vertices =
      glium::VertexBuffer::empty_immutable (glium_display, 0).unwrap();
    let rectangle_anysize_vertices = VecMap::new();
    let tile_2d_vertices = glium::VertexBuffer::dynamic (glium_display, &[ ])
      .unwrap();
    let tile_color_2d_vertices = glium::VertexBuffer::dynamic (glium_display, &[ ])
      .unwrap();
    let viewport_resources =
      VecMap::with_capacity (render::INITIAL_VIEWPORT_VECMAP_CAPACITY);
    let line_loop_vertices =
      glium::VertexBuffer::dynamic (glium_display, &[ ]).unwrap();
    Draw2d {
      rectangle_2d_vertices,
      pointer_vertex,
      draw_pointer,
      default_sprite_16x16_vertices,
      sprite_16x16_vertices,
      sprite_64x64_vertices,
      rectangle_16x16_vertices,
      rectangle_64x64_vertices,
      rectangle_anysize_vertices,
      tile_2d_vertices,
      tile_color_2d_vertices,
      viewport_resources,
      line_loop_vertices
    }
  }

  pub fn draw (
    render      : &Render <render::resource::Default>,
    glium_frame : &mut glium::Frame
  ) {
    use glium::Surface;
    let draw2d = &render.resource.draw2d;
    // primitives
    const POINTS : glium::index::IndicesSource =
      glium::index::IndicesSource::NoIndices {
        primitives: glium::index::PrimitiveType::Points
      };
    const LINE_LOOP : glium::index::IndicesSource =
      glium::index::IndicesSource::NoIndices {
        primitives: glium::index::PrimitiveType::LineLoop
      };
    // draw each viewport 2d
    for (i, viewport) in render.viewports.iter() {
      if let Some (camera2d) = viewport.camera2d() {
        // draw parameters
        let draw_parameters_viewport     = viewport.draw_parameters();
        let draw_parameters_blend_normal = glium::DrawParameters {
          blend: render::params::BLEND_FUNC_NORMAL,
          .. draw_parameters_viewport.clone()
        };
        let draw_parameters_blend_invert = glium::DrawParameters {
          // NOTE: inverse blending does not really have an effect when
          // rendering with 'Nearest' magnify filter below
          blend: render::params::BLEND_FUNC_INVERT_COLOR,
          .. draw_parameters_viewport.clone()
        };
        // samplers
        let tileset_sampler_128 = render.resource.tileset_128x128_texture
          .sampled()
          .magnify_filter (glium::uniforms::MagnifySamplerFilter::Nearest);
        let tileset_sampler_256 = render.resource.tileset_256x256_texture
          .sampled()
          .magnify_filter (glium::uniforms::MagnifySamplerFilter::Nearest);
        let tileset_sampler = |tileset_id| match tileset_id {
          DefaultTilesetId::EasciiAcorn128 => tileset_sampler_128.clone(),
          DefaultTilesetId::EasciiAcorn256 => tileset_sampler_256.clone(),
          _ => unimplemented!()
        };
        let default_textures_16x16_sampler =
          render.resource.default_textures_16x16.sampled()
            .magnify_filter (glium::uniforms::MagnifySamplerFilter::Nearest);
        let textures_16x16_sampler = render.resource.textures_16x16.sampled()
          .magnify_filter (glium::uniforms::MagnifySamplerFilter::Nearest);
        let textures_64x64_sampler = render.resource.textures_64x64.sampled()
          .magnify_filter (glium::uniforms::MagnifySamplerFilter::Nearest);
        // matrices
        let (transform_mat_world_to_view, projection_mat_ortho) =
          camera2d.view_ortho_mats();
        // uniforms
        let uniforms = uniform!{
          uni_transform_mat_view:   transform_mat_world_to_view,
          uni_projection_mat_ortho: projection_mat_ortho,
          uni_color: color::rgba_u8_to_rgba_f32 (color::DEBUG_GREY)
        };
        // draw per-viewport resources
        if let Some (resources) = draw2d.viewport_resources.get (i) {
          for draw_indices in resources.draw_indices.iter() {
            if let Some (r) = draw_indices.rectangle.map (|r| r as usize) {
              //////////////////////////////////////////////////////////////////
              //  draw rectangle
              //////////////////////////////////////////////////////////////////
              glium_frame.draw (
                draw2d.rectangle_2d_vertices.slice (r..r+1).unwrap(),
                POINTS.clone(),
                &render.resource.shader_programs [
                  shader::ProgramId::WorldSpace2dRect as usize],
                &uniforms,
                &draw_parameters_blend_normal
              ).unwrap();
              // end draw rectangle
            }
            if let Some (draw_tiles) = draw_indices.draw_tiles.as_ref() {
              //////////////////////////////////////////////////////////////////
              //  draw tiles (inverse)
              //////////////////////////////////////////////////////////////////
              let tile_origin = draw_tiles.origin.to_world (camera2d).0
                .into_array();
              let uniforms = uniform!{
                uni_transform_mat_view:   transform_mat_world_to_view,
                uni_projection_mat_ortho: projection_mat_ortho,
                // upper left corner
                uni_tile_space_origin:    tile_origin,
                uni_sampler2d_tileset:    tileset_sampler (draw_tiles.tileset_id)
              };
              glium_frame.draw (
                draw2d.tile_2d_vertices.slice (
                  draw_tiles.vertex_range.start as usize..
                  draw_tiles.vertex_range.end   as usize
                ).unwrap(),
                POINTS.clone(),
                &render.resource
                  .shader_programs [shader::ProgramId::TileSpace2dTile as usize],
                &uniforms,
                &draw_parameters_blend_invert
              ).unwrap();
              // end draw tiles (inverse)
            }
            // draw color tiles
            if let Some (draw_tiles) = draw_indices.draw_color_tiles.as_ref() {
              //////////////////////////////////////////////////////////////////
              //  draw color tiles
              //////////////////////////////////////////////////////////////////
              let tile_origin = draw_tiles.origin.to_world (camera2d).0
                .into_array();
              let uniforms = uniform!{
                uni_transform_mat_view:   transform_mat_world_to_view,
                uni_projection_mat_ortho: projection_mat_ortho,
                // upper left corner
                uni_tile_space_origin:    tile_origin,
                uni_sampler2d_tileset:    tileset_sampler (draw_tiles.tileset_id)
              };
              glium_frame.draw (
                draw2d.tile_color_2d_vertices.slice (
                  draw_tiles.vertex_range.start as usize..
                  draw_tiles.vertex_range.end   as usize
                ).unwrap(),
                POINTS.clone(),
                &render.resource.shader_programs [
                  shader::ProgramId::TileSpace2dTileColor as usize],
                &uniforms,
                &draw_parameters_blend_normal
              ).unwrap();
              // end draw color tiles
            }
          }
          if resources.draw_crosshair {
            ////////////////////////////////////////////////////////////////////
            //  draw crosshair
            ////////////////////////////////////////////////////////////////////
            let transform_mat_world_to_view =
              camera2d::transform_mat_world_to_view (
                [0.0, 0.0].into(),
                math::Rotation2::identity()
              ).into_col_arrays();
            let uniforms = uniform!{
              uni_transform_mat_view:     transform_mat_world_to_view,
              uni_projection_mat_ortho:   projection_mat_ortho,
              uni_sampler2darray:         default_textures_16x16_sampler.clone()
            };
            glium_frame.draw (
              draw2d.default_sprite_16x16_vertices.slice (
                (DefaultSprite16Id::Crosshair as usize)..
                (DefaultSprite16Id::Crosshair as usize + 1)
              ).unwrap(),
              POINTS.clone(),
              &render.resource.shader_programs [
                shader::ProgramId::WorldSpace2dSpriteLayer as usize],
              &uniforms,
              &draw_parameters_blend_invert
            ).unwrap();
            // end draw crosshair
          }
          if resources.draw_lineloop {
            ////////////////////////////////////////////////////////////////////
            //  draw viewport line loop
            ////////////////////////////////////////////////////////////////////
            let base_index = i * 4;
            glium_frame.draw (
              draw2d.line_loop_vertices.slice (base_index..(base_index + 4))
                .unwrap(),
              LINE_LOOP.clone(),
              &render.resource.shader_programs [
                shader::ProgramId::WorldSpace2dUniColor as usize],
              &uniforms,
              &draw_parameters_blend_normal
            ).unwrap();
            // end draw viewport line loop
          }
        } // end draw per-viewport resources
        ////////////////////////////////////////////////////////////////////////
        //  draw sprites 16x16
        ////////////////////////////////////////////////////////////////////////
        let uniforms = uniform!{
          uni_transform_mat_view:   transform_mat_world_to_view,
          uni_projection_mat_ortho: projection_mat_ortho,
          uni_sampler2darray:       textures_16x16_sampler.clone()
        };
        glium_frame.draw (
          draw2d.sprite_16x16_vertices.slice (..).unwrap(),
          POINTS.clone(),
          &render.resource.shader_programs [
            shader::ProgramId::WorldSpace2dSpriteLayer as usize],
          &uniforms,
          &draw_parameters_blend_normal
        ).unwrap();
        ////////////////////////////////////////////////////////////////////////
        //  draw rectangles 16x16
        ////////////////////////////////////////////////////////////////////////
        glium_frame.draw (
          draw2d.rectangle_16x16_vertices.slice (..).unwrap(),
          POINTS.clone(),
          &render.resource.shader_programs [
            shader::ProgramId::WorldSpace2dRectUvLayer as usize],
          &uniforms,
          &draw_parameters_blend_normal
        ).unwrap();
        ////////////////////////////////////////////////////////////////////////
        //  draw sprites 64x64
        ////////////////////////////////////////////////////////////////////////
        let uniforms = uniform!{
          uni_transform_mat_view:   transform_mat_world_to_view,
          uni_projection_mat_ortho: projection_mat_ortho,
          uni_sampler2darray:       textures_64x64_sampler.clone()
        };
        glium_frame.draw (
          draw2d.sprite_64x64_vertices.slice (..).unwrap(),
          POINTS.clone(),
          &render.resource.shader_programs [
            shader::ProgramId::WorldSpace2dSpriteLayer as usize],
          &uniforms,
          &draw_parameters_blend_normal
        ).unwrap();
        ////////////////////////////////////////////////////////////////////////
        //  draw rectangles 64x64
        ////////////////////////////////////////////////////////////////////////
        glium_frame.draw (
          draw2d.rectangle_64x64_vertices.slice (..).unwrap(),
          POINTS.clone(),
          &render.resource.shader_programs [
            shader::ProgramId::WorldSpace2dRectUvLayer as usize],
          &uniforms,
          &draw_parameters_blend_normal
        ).unwrap();
        ////////////////////////////////////////////////////////////////////////
        //  draw rectangles anysize
        ////////////////////////////////////////////////////////////////////////
        for (i, buffer) in draw2d.rectangle_anysize_vertices.iter() {
          let uniforms = uniform!{
            uni_transform_mat_view:   transform_mat_world_to_view,
            uni_projection_mat_ortho: projection_mat_ortho,
            uni_sampler2d:            render.resource
              .textures_anysize.get (i).unwrap().sampled()
          };
          glium_frame.draw (
            buffer,
            POINTS.clone(),
            &render.resource.shader_programs [
              shader::ProgramId::WorldSpace2dRectUv as usize],
            &uniforms,
            &draw_parameters_blend_normal
          ).unwrap();
        }
      } // end loop over viewports
    }
    if let Some (buffer) = draw2d.pointer_vertex.as_ref() {
      if let Some (texture_index) = draw2d.draw_pointer {
        ////////////////////////////////////////////////////////////////////////
        //  draw pointer
        ////////////////////////////////////////////////////////////////////////
        let pointer_texture_sampler =
          render.resource.textures_pointer.get (texture_index as usize).unwrap()
            .0.sampled()
            .magnify_filter (glium::uniforms::MagnifySamplerFilter::Nearest);
        let (width, height) = render.glium_display.get_framebuffer_dimensions();
        let transform_mat_world_to_view = camera2d::transform_mat_world_to_view (
          [width as f32 / 2.0, height as f32 / 2.0].into(),
          math::Rotation2::identity()
        ).into_col_arrays();
        let projection_mat_ortho = graphics::projection_mat_orthographic (
          &Camera2d::ortho_from_viewport_zoom (width as u16, height as u16, 1.0)
        ).into_col_arrays();
        let draw_parameters = glium::DrawParameters {
          blend:    render::params::BLEND_FUNC_NORMAL,
          viewport: Some (glium::Rect {
            left:   0,
            bottom: 0,
            width, height
          }),
          .. Default::default()
        };
        let uniforms = uniform!{
          uni_transform_mat_view:   transform_mat_world_to_view,
          uni_projection_mat_ortho: projection_mat_ortho,
          uni_sampler2d:            pointer_texture_sampler
        };
        glium_frame.draw (
          buffer,
          POINTS.clone(),
          &render.resource.shader_programs [
            shader::ProgramId::WorldSpace2dSprite as usize],
          &uniforms,
          &draw_parameters
        ).unwrap();
      }
    }
  }

  #[inline]
  pub fn viewport_resources_get (&self, key : usize)
    -> Option <&ViewportResources>
  {
    self.viewport_resources.get (key)
  }
  /// Set the viewport tile data for the specified viewport.
  ///
  /// Panics if the tile data range is outside of the current tile vertices
  /// length.
  #[inline]
  pub fn viewport_resources_set (&mut self,
    key       : usize,
    resources : ViewportResources
  ) {
    // verify that vertex ranges are valid
    for draw_indices in resources.draw_indices.iter() {
      draw_indices.rectangle
        .map (|i| assert!(i as usize <= self.rectangle_2d_vertices.get_size()));
      if let Some (draw_tiles) = draw_indices.draw_tiles.as_ref() {
        assert!(draw_tiles.vertex_range.end as usize
          <= self.tile_2d_vertices.get_size());
      }
      if let Some (draw_tiles) = draw_indices.draw_color_tiles.as_ref() {
        assert!(draw_tiles.vertex_range.end as usize
          <= self.tile_color_2d_vertices.get_size());
      }
    }
    let _ = self.viewport_resources.insert (key, resources);
  }
  #[inline]
  pub fn line_loop_vertices_set (&mut self,
    glium_display : &glium::Display <glutin::surface::WindowSurface>,
    vertices      : &[vertex::Vert2d]
  ) {
    self.line_loop_vertices =
      glium::VertexBuffer::persistent (glium_display, vertices).unwrap();
  }

  pub (crate) fn set_pointer_vertex (&mut self,
    display  : &glium::Display <glutin::surface::WindowSurface>,
    position : math::Point2 <f32>
  ) {
    let vertex = vertex::Vert2d { position: position.0.into_array() };
    if let Some (buffer) = self.pointer_vertex.as_mut() {
      buffer.write (&[vertex]);
    } else {
      let buffer = glium::VertexBuffer::persistent (display, &[vertex]).unwrap();
      self.pointer_vertex = Some (buffer);
    }
  }
}

impl Default for ViewportResources {
  fn default() -> Self {
    ViewportResources {
      draw_indices:   vec![],
      draw_crosshair: true,
      draw_lineloop:  true
    }
  }
}

impl TilesOrigin {
  pub fn to_world (&self, camera : &Camera2d) -> math::Point2 <f32> {
    match self {
      TilesOrigin::World => [0.0, 0.0],
      TilesOrigin::Viewport { offset_px_left, offset_px_top } => {
        let pixel_size_2d = 1.0 / camera.zoom();
        [ camera.ortho().left + camera.position().0.x +
            pixel_size_2d * *offset_px_left as f32,
          camera.ortho().top  + camera.position().0.y -
            pixel_size_2d * *offset_px_top  as f32
        ]
      }
    }.into()
  }
}