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
//! Support types for Glium rendering.
//!
//! The `Render` struct holds all the context information and resources
//! required for making calls to OpenGL render commands (via `glium`).

use ::{std, glium, image, vec_map};

use ::{rs_utils};

pub mod params;
pub mod resource;
pub mod viewport;

pub use self::resource::Resource;
pub use self::resource::DefaultResource;
pub use self::viewport::Viewport;

/// Sets a limit to how many simultaneous screenshot worker threads may be
/// running simultaneously-- should be more than enough.
const MAX_SCREENSHOT_WORKER_COUNT      : u8    = 16;
/// Initialize viewport `VecMap` with this capacity
const INITIAL_VIEWPORT_VECMAP_CAPACITY : usize = 4;
/// Prevents renderers from dropping while screenshot workers are not yet
/// finished.
///
/// Note that this is a global variable so it is shared among all renderers
/// and it will not prevent other threads from terminating if not synchronized
/// with the render thread.
static SCREENSHOT_WORKER_COUNT    : std::sync::atomic::AtomicU8
  = std::sync::atomic::AtomicU8::new (0);

/// State for Glium-based rendering.
///
/// Holds all the context information and resources required for rendering. A
/// frame function may be specified by the `frame_fun` field which is a
/// function pointer that takes a mutable self reference for the purpose of
/// making Glium render commands.
///
/// OpenGL has four types of *render commands*:
///
/// 1. Framebuffer clearing commands
/// 2. Framebuffer blitting commands
/// 3. Drawing commands (*vertex rendering*)
/// 4. Compute dispatch commands (OpenGL 4.3+ only)
///
/// All resources (vertex and index buffers, textures and other uniforms)
/// should be in the user defined generic resource type `R : Resource`.

pub struct Render <R : Resource> {
  /// The `glium` context represented by a `glium::backend::Context` and a
  /// `glutin::GlWindow`
  pub glium_display   : glium::Display,
  /// A function for rendering a single frame
  pub resource        : R,
  pub frame_fun       : fn (&mut Render <R>),
  pub clear_color     : (f32, f32, f32, f32),
  pub viewports       : vec_map::VecMap <Viewport>
}

/// Default frame function clears all and calls resource `draw_3d` method
/// followed by `draw_2d` method.
pub fn frame_fun_default <R : Resource> (render : &mut Render <R>) {
  use glium::Surface;
  debug!("frame fun default...");
  let mut glium_frame = render.glium_display.draw();
  glium_frame.clear_all (render.clear_color, 1.0, 0);
  Resource::draw_3d (&render, &mut glium_frame);
  Resource::draw_2d (&render, &mut glium_frame);
  glium_frame.finish().unwrap();
  debug!("...frame fun default");
}

/// Default 2D frame function clears all and calls resource `draw_2d` method.
pub fn frame_fun_default_2d <R : Resource> (render : &mut Render <R>) {
  use glium::Surface;
  debug!("frame fun default...");
  let mut glium_frame = render.glium_display.draw();
  glium_frame.clear_all (render.clear_color, 1.0, 0);
  Resource::draw_2d (&render, &mut glium_frame);
  glium_frame.finish().unwrap();
  debug!("...frame fun default");
}

/// Default 3D frame function clears all and calls resource `draw_3d` method.
pub fn frame_fun_default_3d <R : Resource> (render : &mut Render <R>) {
  use glium::Surface;
  debug!("frame fun default...");
  let mut glium_frame = render.glium_display.draw();
  glium_frame.clear_all (render.clear_color, 1.0, 0);
  Resource::draw_3d (&render, &mut glium_frame);
  glium_frame.finish().unwrap();
  debug!("...frame fun default");
}

impl <R : Resource> Render <R> {
  /// Creates a new renderer with default viewport and resources.
  pub fn new (glium_display : glium::Display) -> Self {
    let frame_fun         = frame_fun_default::<R>;
    let clear_color       = (0.0, 0.0, 1.0, 1.0); // initial clear color: blue
    let (resolution_width, resolution_height) = glium_display.gl_window()
      .get_inner_size().unwrap();
    let viewports         = {
      let mut v
        = vec_map::VecMap::with_capacity (INITIAL_VIEWPORT_VECMAP_CAPACITY);
      assert!{
        v.insert (0, Viewport::new (glium::Rect {
          left: 0, bottom: 0, width: resolution_width, height: resolution_height
        })).is_none()
      }
      v
    };
    let resource          = R::new (&glium_display);

    let mut render = Render {
      glium_display,
      frame_fun,
      clear_color,
      viewports,
      resource
    };
    R::init (&mut render);
    render
  }

  /// Restore the renderer to the newly created state
  pub fn reset (&mut self) {
    let glium_display = self.glium_display.clone();
    *self = Self::new (glium_display);
  }

  /// Convenience method to call the current frame function on self
  #[inline]
  pub fn do_frame (&mut self) {
    (self.frame_fun) (self)
  }

  /// Read the content of the front buffer and save in a PNG file with unique
  /// file name `screenshot-N.png` in the current directory.
  pub fn screenshot (&self) {
    let raw : glium::texture::RawImage2d <u8>
      = self.glium_display.read_front_buffer();
    let worker_count = SCREENSHOT_WORKER_COUNT
      .fetch_add (1, std::sync::atomic::Ordering::SeqCst);
    if worker_count < MAX_SCREENSHOT_WORKER_COUNT {
      let _ = std::thread::spawn (|| {
        let mut image_buffer = image::ImageBuffer::from_raw (
          raw.width, raw.height, raw.data.into_owned()).unwrap();
        image_buffer = image::imageops::flip_vertical (&image_buffer);
        let image    = image::DynamicImage::ImageRgba8 (image_buffer);
        let filepath = {
          // create a file incrementally named 'screenshot-N.png'
          let mut filepath
            = rs_utils::file::file_path_incremental_with_extension (
                std::path::Path::new ("screenshot.png")).unwrap();
          filepath
        };
        println!("saving {:?}...", filepath);
        image.save (filepath).unwrap();
        SCREENSHOT_WORKER_COUNT
          .fetch_sub (1, std::sync::atomic::Ordering::SeqCst);
      });
    }
  }

  pub fn report_sizes() {
    use ::vertex;
    println!("Render report...");
    println!("  size of Render <R>:   {}", std::mem::size_of::<Self>());
    println!("  size of R: {}", std::mem::size_of::<R>());
    println!("  size of VertexBuffer <Vert2d>: {}",
      std::mem::size_of::<glium::VertexBuffer <vertex::Vert2d>>());
    println!("  size of IndexBuffer <u8>: {}",
      std::mem::size_of::<glium::IndexBuffer <u8>>());
    println!("...Render report");
  }
}

impl <R : Resource> Drop for Render <R> {
  fn drop (&mut self) {
    // wait for screenshot worker threads to finish
    while 0 < SCREENSHOT_WORKER_COUNT.load (std::sync::atomic::Ordering::SeqCst) {
      std::thread::sleep (std::time::Duration::from_millis (100));
    }
  }
}