fennel_engine/
graphics.rs

1//! SDL3-backed graphics helper
2//!
3//! Provides:
4//! - `Graphics`: owned SDL context + drawing canvas
5//! - `Graphics::new(...)`: initialize SDL, create a centered resizable window and return [`Graphics`]
6//!
7
8use std::path::PathBuf;
9use std::sync::Arc;
10
11use sdl3::Sdl;
12use sdl3::render::{Canvas, FRect};
13use sdl3::video::Window;
14
15use crate::resources::loadable::Image;
16use crate::resources::{self, LoadableResource, ResourceManager, loadable};
17
18/// Owned SDL variables used for rendering
19///
20/// - `canvas`: the drawing surface for the window
21/// - `sdl_context`: the SDL context
22pub struct Graphics {
23    /// The SDL3 canvas, required to draw
24    pub canvas: Canvas<Window>,
25    /// SDL3 contaxt
26    pub sdl_context: Sdl,
27    /// SDL3 texture creator
28    pub texture_creator: Arc<sdl3::render::TextureCreator<sdl3::video::WindowContext>>,
29}
30
31impl Graphics {
32    /// Initialize SDL3, create a centered, resizable window and return a [`Graphics`]
33    /// container with the canvas and SDL context.
34    ///
35    /// # Parameters
36    /// - `name`: Window title.
37    /// - `dimensions`: (width, height) in pixels (u32).
38    ///
39    /// # Returns
40    /// - `Ok(Graphics)` on success.
41    /// - `Err(Box<dyn std::error::Error>)` on failure (window/canvas build error).
42    ///
43    /// # Example
44    /// ```ignore
45    /// let graphics = graphics::new(String::from("my cool game"), (500, 500))?;
46    /// ```
47    pub fn new(
48        name: String,
49        dimensions: (u32, u32),
50    ) -> Result<Graphics, Box<dyn std::error::Error>> {
51        // TODO: allow the user to uh customize video_subsystem configuration 'cuz man this is ass why
52        // do we position_centered() and resizable() it by default
53
54        let sdl_context = sdl3::init().unwrap();
55        let video_subsystem = sdl_context.video().unwrap(); // TODO: get this fucking unwrap out of
56        // here and replace with something more
57        // cool
58
59        let window = video_subsystem
60            .window(&name, dimensions.0, dimensions.1)
61            .position_centered()
62            .resizable()
63            .build()
64            .map_err(|e| e.to_string())?;
65
66        let canvas = window.into_canvas();
67        let texture_creator = canvas.texture_creator();
68        Ok(Graphics {
69            canvas,
70            sdl_context,
71            texture_creator: Arc::new(texture_creator),
72        })
73    }
74
75    /// Cache an image if it isn't cached and draw it on the canvas
76    ///
77    /// # Parameters
78    /// - `path`: Path to the image
79    /// - `position`: Where to draw the image in the window (x,y) in pixels (f32).
80    ///
81    /// # Returns
82    /// - `Ok(())` on success.
83    /// - `Err(Box<dyn std::error::Error>)` on failure
84    ///
85    /// # Example
86    /// ```ignore
87    /// graphics.draw_image(String::from("examples/example.png"), (0.0, 0.0)).await;
88    /// ```
89    pub fn draw_image(
90        &mut self,
91        path: String,
92        position: (f32, f32),
93        manager: &mut ResourceManager,
94    ) -> anyhow::Result<()> {
95        if !manager.is_cached(path.clone()) {
96            // rust programmers when they have to .clone()
97            let texture = loadable::Image::load(PathBuf::from(path.clone()), &self.texture_creator);
98            manager.cache_asset(texture?)?; // those question marks are funny hehehe
99        }
100
101        let image: &Image = resources::as_concrete(manager.get_asset(path).unwrap());
102
103        let dst_rect = FRect::new(
104            position.0,
105            position.1,
106            image.width as f32,
107            image.height as f32,
108        );
109
110        self.canvas
111            .copy_ex(
112                &image.texture,
113                None,
114                Some(dst_rect),
115                0.0,
116                None,
117                false,
118                false,
119            )
120            .unwrap();
121
122        Ok(())
123    }
124}