moon_engine/
gl.rs

1//! A collection of functions and traits related to [`WebGl2RenderingContext`], as well as the [`GL`] alias.
2
3use wasm_bindgen::JsCast;
4use web_sys::WebGl2RenderingContext;
5
6use crate::Canvas;
7
8/// An alias for [`WebGl2RenderingContext`].
9///
10/// # Examples
11///
12/// ```no_run
13/// use moon_engine::*;
14/// let gl = gl::get_context();
15/// ```
16pub type GL = WebGl2RenderingContext;
17
18/// The [`Bind`] trait enables setting up WebGl state when bound, and optionally resetting to a neutral one when unbound.
19///
20/// These functons should be implented **without** mutating the implementing struct, i.e. just changing the state of the [`WebGl2RenderingContext`].
21pub trait Bind {
22    /// Binds a struct implementing the [`Bind`] trait. This is up to the implementation to decide.
23    fn bind(&self, gl: &GL);
24    /// Optionally unbinds a struct implementing the [`Bind`] trait. This effectively resets the WebGL state.
25    fn unbind(&self, _gl: &GL) {}
26}
27
28/// Check for, and print any WebGL errors if found.
29///
30/// Takes a reference to a [`WebGl2RenderingContext`] and returns a [`bool`], indicating whether any errors were found.
31///
32/// # Examples
33///
34/// ```no_run
35/// use moon_engine::*;
36/// # let gl = gl::get_context();
37///
38/// let has_errors = gl::check_gl_error(&gl);
39/// ```
40///
41pub fn check_gl_error(gl: &GL) -> bool {
42    let mut found_error = false;
43    let mut gl_error = gl.get_error();
44    while gl_error != GL::NO_ERROR {
45        println!("OpenGL Error {}", gl_error);
46        found_error = true;
47        gl_error = gl.get_error();
48    }
49    found_error
50}
51
52/// Get the `WebGl2RenderingContext` of a canvas with an *element ID* of **"canvas"**
53///
54/// This function will panic in case of an error
55///
56/// # Examples
57///
58/// ```no_run
59/// use moon_engine::gl::*;
60///
61/// let context: GL = get_context();
62/// ```
63pub fn get_context() -> GL {
64    let document: web_sys::Document = web_sys::window().unwrap().document().unwrap();
65    let canvas: Canvas = document
66        .get_element_by_id("canvas")
67        .unwrap()
68        .dyn_into::<Canvas>()
69        .unwrap();
70    let context: GL = canvas
71        .get_context("webgl2")
72        .unwrap()
73        .unwrap()
74        .dyn_into::<GL>()
75        .unwrap();
76    context
77}