Skip to main content

beamterm_renderer/gl/
renderer.rs

1use beamterm_core::gl::{Drawable, GlState, RenderContext};
2use glow::HasContext;
3use web_sys::HtmlCanvasElement;
4
5use crate::{error::Error, js};
6
7/// High-level WebGL2 renderer for terminal-style applications.
8///
9/// The `Renderer` manages the WebGL2 rendering context, canvas, and provides
10/// a simplified interface for rendering drawable objects. It handles frame
11/// management, viewport setup, and coordinate system transformations.
12pub struct Renderer {
13    gl: glow::Context,
14    raw_gl: web_sys::WebGl2RenderingContext, // for is_context_lost() only
15    canvas: web_sys::HtmlCanvasElement,
16    state: GlState,
17    canvas_padding_color: (f32, f32, f32),
18    logical_size_px: (i32, i32),
19    pixel_ratio: f32,
20    auto_resize_canvas_css: bool,
21}
22
23impl std::fmt::Debug for Renderer {
24    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
25        f.debug_struct("Renderer")
26            .field("canvas_padding_color", &self.canvas_padding_color)
27            .field("logical_size_px", &self.logical_size_px)
28            .field("pixel_ratio", &self.pixel_ratio)
29            .field("auto_resize_canvas_css", &self.auto_resize_canvas_css)
30            .finish_non_exhaustive()
31    }
32}
33
34impl Renderer {
35    /// Creates a new renderer by querying for a canvas element with the given ID.
36    pub fn create(canvas_id: &str, auto_resize_canvas_css: bool) -> Result<Self, Error> {
37        let canvas = js::get_canvas_by_id(canvas_id)?;
38        Self::create_with_canvas(canvas, auto_resize_canvas_css)
39    }
40
41    /// Sets the background color for the canvas area outside the terminal grid.
42    pub fn canvas_padding_color(mut self, color: u32) -> Self {
43        let r = ((color >> 16) & 0xFF) as f32 / 255.0;
44        let g = ((color >> 8) & 0xFF) as f32 / 255.0;
45        let b = (color & 0xFF) as f32 / 255.0;
46        self.canvas_padding_color = (r, g, b);
47        self
48    }
49
50    /// Creates a new renderer from an existing HTML canvas element.
51    pub fn create_with_canvas(
52        canvas: HtmlCanvasElement,
53        auto_resize_canvas_css: bool,
54    ) -> Result<Self, Error> {
55        let (width, height) = (canvas.width() as i32, canvas.height() as i32);
56
57        // initialize WebGL context
58        let (gl, raw_gl) = js::create_glow_context(&canvas)?;
59        let state = GlState::new(&gl);
60
61        let mut renderer = Self {
62            gl,
63            raw_gl,
64            canvas,
65            state,
66            canvas_padding_color: (0.0, 0.0, 0.0),
67            logical_size_px: (width, height),
68            pixel_ratio: 1.0,
69            auto_resize_canvas_css,
70        };
71        renderer.resize(width as _, height as _);
72        Ok(renderer)
73    }
74
75    /// Resizes the canvas and updates the viewport.
76    pub fn resize(&mut self, width: i32, height: i32) {
77        self.logical_size_px = (width, height);
78        let (w, h) = self.physical_size();
79
80        self.canvas.set_width(w as u32);
81        self.canvas.set_height(h as u32);
82
83        if self.auto_resize_canvas_css {
84            let _ = self
85                .canvas
86                .style()
87                .set_property("width", &format!("{width}px"));
88            let _ = self
89                .canvas
90                .style()
91                .set_property("height", &format!("{height}px"));
92        }
93
94        self.state.viewport(&self.gl, 0, 0, w, h);
95    }
96
97    /// Clears the framebuffer with the specified color.
98    pub fn clear(&mut self, r: f32, g: f32, b: f32) {
99        self.state.clear_color(&self.gl, r, g, b, 1.0);
100        unsafe {
101            self.gl
102                .clear(glow::COLOR_BUFFER_BIT | glow::DEPTH_BUFFER_BIT)
103        };
104    }
105
106    /// Begins a new rendering frame.
107    pub fn begin_frame(&mut self) {
108        let (r, g, b) = self.canvas_padding_color;
109        self.clear(r, g, b);
110    }
111
112    /// Renders a drawable object.
113    pub fn render(&mut self, drawable: &impl Drawable) -> Result<(), crate::Error> {
114        let mut context = RenderContext { gl: &self.gl, state: &mut self.state };
115
116        drawable.prepare(&mut context)?;
117        drawable.draw(&mut context);
118        drawable.cleanup(&mut context);
119        Ok(())
120    }
121
122    /// Ends the current rendering frame.
123    pub fn end_frame(&mut self) {
124        // swap buffers (todo)
125    }
126
127    /// Returns a reference to the glow rendering context.
128    pub fn gl(&self) -> &glow::Context {
129        &self.gl
130    }
131
132    /// Returns a reference to the HTML canvas element.
133    pub fn canvas(&self) -> &HtmlCanvasElement {
134        &self.canvas
135    }
136
137    /// Returns the current canvas dimensions as a tuple.
138    pub fn canvas_size(&self) -> (i32, i32) {
139        self.logical_size()
140    }
141
142    /// Returns the logical size of the canvas in pixels.
143    pub fn logical_size(&self) -> (i32, i32) {
144        self.logical_size_px
145    }
146
147    /// Returns the physical size of the canvas in pixels, taking into account the device
148    /// pixel ratio.
149    pub fn physical_size(&self) -> (i32, i32) {
150        let (w, h) = self.logical_size_px;
151        (
152            (w as f32 * self.pixel_ratio).round() as i32,
153            (h as f32 * self.pixel_ratio).round() as i32,
154        )
155    }
156
157    /// Checks if the WebGL context has been lost.
158    pub fn is_context_lost(&self) -> bool {
159        self.raw_gl.is_context_lost()
160    }
161
162    /// Restores the WebGL context after a context loss event.
163    pub fn restore_context(&mut self) -> Result<(), Error> {
164        let (gl, raw_gl) = js::create_glow_context(&self.canvas)?;
165        self.state = GlState::new(&gl);
166        self.gl = gl;
167        self.raw_gl = raw_gl;
168
169        // Restore viewport using physical (device) pixels
170        let (width, height) = self.physical_size();
171        self.state.viewport(&self.gl, 0, 0, width, height);
172
173        Ok(())
174    }
175
176    /// Sets the pixel ratio.
177    pub(crate) fn set_pixel_ratio(&mut self, pixel_ratio: f32) {
178        self.pixel_ratio = pixel_ratio;
179    }
180}