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
//! Framebuffer support for WebGL2.

use crate::webgl2::{state::WebGL2State, WebGL2};
use js_sys::Uint32Array;
use luminance::{
  backend::{
    color_slot::ColorSlot,
    depth_stencil_slot::DepthStencilSlot,
    framebuffer::{Framebuffer as FramebufferBackend, FramebufferBackBuffer},
  },
  framebuffer::{FramebufferError, IncompleteReason},
  texture::{Dim2, Dimensionable, Sampler},
};
use std::{cell::RefCell, rc::Rc};
use web_sys::{WebGl2RenderingContext, WebGlFramebuffer, WebGlRenderbuffer};

pub struct Framebuffer<D>
where
  D: Dimensionable,
{
  // None is the default framebuffer…
  pub(crate) handle: Option<WebGlFramebuffer>,
  renderbuffer: Option<WebGlRenderbuffer>,
  pub(crate) size: D::Size,
  state: Rc<RefCell<WebGL2State>>,
}

impl<D> Drop for Framebuffer<D>
where
  D: Dimensionable,
{
  fn drop(&mut self) {
    let state = self.state.borrow();

    state.ctx.delete_renderbuffer(self.renderbuffer.as_ref());
    state.ctx.delete_framebuffer(self.handle.as_ref());
  }
}

unsafe impl<D> FramebufferBackend<D> for WebGL2
where
  D: Dimensionable,
{
  type FramebufferRepr = Framebuffer<D>;

  unsafe fn new_framebuffer<CS, DS>(
    &mut self,
    size: D::Size,
    _: usize,
    _: &Sampler,
  ) -> Result<Self::FramebufferRepr, FramebufferError>
  where
    CS: ColorSlot<Self, D>,
    DS: DepthStencilSlot<Self, D>,
  {
    let color_formats = CS::color_formats();
    let depth_format = DS::depth_format();
    let mut depth_renderbuffer = None;

    let mut state = self.state.borrow_mut();

    let handle = state
      .create_framebuffer()
      .ok_or_else(|| FramebufferError::cannot_create())?;
    state.bind_draw_framebuffer(Some(&handle));

    // reserve textures to speed up slots creation
    let textures_needed = color_formats.len() + depth_format.map_or(0, |_| 1);
    state.reserve_textures(textures_needed);

    // color textures
    if color_formats.is_empty() {
      state.ctx.draw_buffers(&WebGl2RenderingContext::NONE.into());
    } else {
      // Specify the list of color buffers to draw to; to do so, we need to generate a temporary
      // list (Vec) of 32-bit integers and turn it into a Uint32Array to pass it across WASM
      // boundary.
      let color_buf_nb = color_formats.len() as u32;
      let color_buffers: Vec<_> = (WebGl2RenderingContext::COLOR_ATTACHMENT0
        ..WebGl2RenderingContext::COLOR_ATTACHMENT0 + color_buf_nb)
        .collect();

      let buffers = Uint32Array::view(&color_buffers);

      state.ctx.draw_buffers(buffers.as_ref());
    }

    // depth texture
    if depth_format.is_none() {
      let renderbuffer = state
        .ctx
        .create_renderbuffer()
        .ok_or_else(|| FramebufferError::cannot_create())?;

      state
        .ctx
        .bind_renderbuffer(WebGl2RenderingContext::RENDERBUFFER, Some(&renderbuffer));

      state.ctx.renderbuffer_storage(
        WebGl2RenderingContext::RENDERBUFFER,
        WebGl2RenderingContext::DEPTH_COMPONENT32F,
        D::width(size) as i32,
        D::height(size) as i32,
      );
      state.ctx.framebuffer_renderbuffer(
        WebGl2RenderingContext::FRAMEBUFFER,
        WebGl2RenderingContext::DEPTH_ATTACHMENT,
        WebGl2RenderingContext::RENDERBUFFER,
        Some(&renderbuffer),
      );

      depth_renderbuffer = Some(renderbuffer);
    }

    let framebuffer = Framebuffer {
      handle: Some(handle),
      renderbuffer: depth_renderbuffer,
      size,
      state: self.state.clone(),
    };

    Ok(framebuffer)
  }

  unsafe fn attach_color_texture(
    framebuffer: &mut Self::FramebufferRepr,
    texture: &Self::TextureRepr,
    attachment_index: usize,
  ) -> Result<(), FramebufferError> {
    match texture.target {
      WebGl2RenderingContext::TEXTURE_2D => {
        let state = framebuffer.state.borrow();
        state.ctx.framebuffer_texture_2d(
          WebGl2RenderingContext::FRAMEBUFFER,
          WebGl2RenderingContext::COLOR_ATTACHMENT0 + attachment_index as u32,
          texture.target,
          Some(&texture.handle),
          0,
        );

        Ok(())
      }

      _ => Err(FramebufferError::unsupported_attachment()),
    }
  }

  unsafe fn attach_depth_texture(
    framebuffer: &mut Self::FramebufferRepr,
    texture: &Self::TextureRepr,
  ) -> Result<(), FramebufferError> {
    match texture.target {
      WebGl2RenderingContext::TEXTURE_2D => {
        let state = framebuffer.state.borrow();
        state.ctx.framebuffer_texture_2d(
          WebGl2RenderingContext::FRAMEBUFFER,
          WebGl2RenderingContext::DEPTH_ATTACHMENT,
          texture.target,
          Some(&texture.handle),
          0,
        );

        Ok(())
      }

      _ => Err(FramebufferError::unsupported_attachment()),
    }
  }

  unsafe fn validate_framebuffer(
    framebuffer: Self::FramebufferRepr,
  ) -> Result<Self::FramebufferRepr, FramebufferError> {
    get_framebuffer_status(&mut framebuffer.state.borrow_mut())?;
    Ok(framebuffer)
  }

  unsafe fn framebuffer_size(framebuffer: &Self::FramebufferRepr) -> D::Size {
    framebuffer.size
  }
}

fn get_framebuffer_status(state: &mut WebGL2State) -> Result<(), IncompleteReason> {
  let status = state
    .ctx
    .check_framebuffer_status(WebGl2RenderingContext::FRAMEBUFFER);

  match status {
    WebGl2RenderingContext::FRAMEBUFFER_COMPLETE => Ok(()),
    WebGl2RenderingContext::FRAMEBUFFER_INCOMPLETE_ATTACHMENT => {
      Err(IncompleteReason::IncompleteAttachment)
    }
    WebGl2RenderingContext::FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT => {
      Err(IncompleteReason::MissingAttachment)
    }
    WebGl2RenderingContext::FRAMEBUFFER_UNSUPPORTED => Err(IncompleteReason::Unsupported),
    WebGl2RenderingContext::FRAMEBUFFER_INCOMPLETE_MULTISAMPLE => {
      Err(IncompleteReason::IncompleteMultisample)
    }
    _ => panic!(
      "unknown WebGL2 framebuffer incomplete status! status={}",
      status
    ),
  }
}

unsafe impl FramebufferBackBuffer for WebGL2 {
  unsafe fn back_buffer(
    &mut self,
    size: <Dim2 as Dimensionable>::Size,
  ) -> Result<Self::FramebufferRepr, FramebufferError> {
    Ok(Framebuffer {
      handle: None, // None is the default framebuffer in WebGL
      renderbuffer: None,
      size,
      state: self.state.clone(),
    })
  }
}