beamterm_renderer/gl/renderer.rs
1use web_sys::HtmlCanvasElement;
2
3use crate::{
4 error::Error,
5 gl::{context::GlState, GL},
6 js,
7};
8
9/// Rendering context that provides access to WebGL state.
10pub(super) struct RenderContext<'a> {
11 pub gl: &'a web_sys::WebGl2RenderingContext,
12 pub state: &'a mut GlState,
13}
14
15/// High-level WebGL2 renderer for terminal-style applications.
16///
17/// The `Renderer` manages the WebGL2 rendering context, canvas, and provides
18/// a simplified interface for rendering drawable objects. It handles frame
19/// management, viewport setup, and coordinate system transformations.
20#[derive(Debug)]
21pub struct Renderer {
22 gl: web_sys::WebGl2RenderingContext,
23 canvas: web_sys::HtmlCanvasElement,
24 state: GlState,
25}
26
27impl Renderer {
28 /// Creates a new renderer by querying for a canvas element with the given ID.
29 ///
30 /// This method searches the DOM for a canvas element with the specified ID,
31 /// initializes a WebGL2 context, and sets up the renderer with orthographic
32 /// projection matching the canvas dimensions.
33 ///
34 /// # Parameters
35 /// * `canvas_id` - CSS selector for the canvas element (e.g., "canvas" or "#my-canvas")
36 ///
37 /// # Returns
38 /// * `Ok(Renderer)` - Successfully created renderer
39 /// * `Err(Error)` - Failed to find canvas, create WebGL context, or initialize renderer
40 ///
41 /// # Errors
42 /// * `Error::UnableToRetrieveCanvas` - Canvas element not found
43 /// * `Error::FailedToRetrieveWebGl2RenderingContext` - WebGL2 not supported or failed to initialize
44 pub fn create(canvas_id: &str) -> Result<Self, Error> {
45 let canvas = js::get_canvas_by_id(canvas_id)?;
46 Self::create_with_canvas(canvas)
47 }
48
49 /// Creates a new renderer from an existing HTML canvas element.
50 ///
51 /// This method takes ownership of an existing canvas element and initializes
52 /// the WebGL2 context and renderer state. Useful when you already have a
53 /// reference to the canvas element.
54 ///
55 /// # Parameters
56 /// * `canvas` - HTML canvas element to use for rendering
57 ///
58 /// # Returns
59 /// * `Ok(Renderer)` - Successfully created renderer
60 /// * `Err(Error)` - Failed to create WebGL context or initialize renderer
61 pub fn create_with_canvas(canvas: HtmlCanvasElement) -> Result<Self, Error> {
62 let (width, height) = (canvas.width(), canvas.height());
63
64 // initialize WebGL context
65 let gl = js::get_webgl2_context(&canvas)?;
66 let state = GlState::new(&gl);
67
68 let mut renderer = Self { gl, canvas, state };
69 renderer.resize(width as _, height as _);
70 Ok(renderer)
71 }
72
73 /// Resizes the canvas and updates the viewport.
74 ///
75 /// This method changes the canvas resolution and adjusts the WebGL viewport
76 /// to match. The projection matrix is automatically updated to maintain
77 /// proper coordinate mapping.
78 ///
79 /// # Parameters
80 /// * `width` - New canvas width in pixels
81 /// * `height` - New canvas height in pixels
82 pub fn resize(&mut self, width: i32, height: i32) {
83 self.canvas.set_width(width as u32);
84 self.canvas.set_height(height as u32);
85 self.state.viewport(&self.gl, 0, 0, width, height);
86 }
87
88 /// Clears the framebuffer with the specified color.
89 ///
90 /// Sets the clear color and clears both the color and depth buffers.
91 /// Color components should be in the range [0.0, 1.0].
92 ///
93 /// # Parameters
94 /// * `r` - Red component (0.0 to 1.0)
95 /// * `g` - Green component (0.0 to 1.0)
96 /// * `b` - Blue component (0.0 to 1.0)
97 pub fn clear(&mut self, r: f32, g: f32, b: f32) {
98 self.state.clear_color(&self.gl, r, g, b, 1.0);
99 self.gl.clear(GL::COLOR_BUFFER_BIT | GL::DEPTH_BUFFER_BIT);
100 }
101
102 /// Begins a new rendering frame.
103 pub fn begin_frame(&mut self) {
104 self.clear(0.0, 0.0, 0.0);
105 }
106
107 /// Renders a drawable object.
108 ///
109 /// This method calls the drawable's prepare, draw, and cleanup methods
110 /// in sequence, providing it with a render context containing.
111 ///
112 /// # Parameters
113 /// * `drawable` - Object implementing the `Drawable` trait
114 #[allow(private_bounds)]
115 pub fn render(&mut self, drawable: &impl Drawable) {
116 let mut context = RenderContext { gl: &self.gl, state: &mut self.state };
117
118 drawable.prepare(&mut context);
119 drawable.draw(&mut context);
120 drawable.cleanup(&mut context);
121 }
122
123 /// Ends the current rendering frame.
124 ///
125 /// This method finalizes the frame rendering. In future versions, this
126 /// may handle buffer swapping or other post-rendering operations.
127 pub fn end_frame(&mut self) {
128 // swap buffers (todo)
129 }
130
131 /// Returns a reference to the WebGL2 rendering context.
132 pub fn gl(&self) -> &GL {
133 &self.gl
134 }
135
136 /// Returns a mutable reference to the WebGL2 rendering context.
137 pub fn canvas(&self) -> &HtmlCanvasElement {
138 &self.canvas
139 }
140
141 /// Returns the current canvas dimensions as a tuple.
142 ///
143 /// # Returns
144 /// Tuple containing (width, height) in pixels
145 pub fn canvas_size(&self) -> (i32, i32) {
146 (self.canvas.width() as i32, self.canvas.height() as i32)
147 }
148}
149
150/// Trait for objects that can be rendered by the renderer.
151pub(super) trait Drawable {
152 /// Prepares the object for rendering.
153 ///
154 /// This method should set up all necessary OpenGL state, bind shaders,
155 /// textures, and vertex data required for rendering.
156 ///
157 /// # Parameters
158 /// * `context` - Mutable reference to the render context
159 fn prepare(&self, context: &mut RenderContext);
160
161 /// Performs the actual rendering.
162 ///
163 /// This method should issue draw calls to render the object. All necessary
164 /// state should already be set up from the `prepare()` call.
165 ///
166 /// # Parameters
167 /// * `context` - Mutable reference to the render context
168 fn draw(&self, context: &mut RenderContext);
169
170 /// Cleans up after rendering.
171 ///
172 /// This method should restore OpenGL state and unbind any resources
173 /// that were bound during `prepare()`. This ensures proper cleanup
174 /// for subsequent rendering operations.
175 ///
176 /// # Parameters
177 /// * `context` - Mutable reference to the render context
178 fn cleanup(&self, context: &mut RenderContext);
179}