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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
//! Graphics renderer functions.

use crate::{core::state::Error as StateError, prelude::*};
use lazy_static::lazy_static;
use std::{borrow::Cow, error, ffi::NulError, fmt, io, path::PathBuf, result};

pub(crate) use crate::core::{
    texture::TextureRenderer, window::Error as WindowError, window::WindowRenderer,
};

#[cfg(not(target_arch = "wasm32"))]
pub(crate) mod sdl;
#[cfg(not(target_arch = "wasm32"))]
pub(crate) use sdl::{Renderer, RendererTexture};

#[cfg(target_arch = "wasm32")]
pub(crate) mod wasm;
#[cfg(target_arch = "wasm32")]
pub(crate) use wasm::{Renderer, RendererTexture};

lazy_static! {
    /// Default directory to extract static library assets into.
    pub static ref DEFAULT_ASSET_DIR: PathBuf = PathBuf::from("/tmp/pix-engine");
}

/// The result type for `Renderer` operations.
pub type Result<T> = result::Result<T, Error>;

/// Default audio sample rate.
const DEFAULT_SAMPLE_RATE: i32 = 44_100; // in Hz

/// Settings used to set up the renderer.
#[derive(Debug, Clone)]
pub(crate) struct RendererSettings {
    pub(crate) title: String,
    #[cfg(not(target_arch = "wasm32"))]
    pub(crate) font: PathBuf,
    #[cfg(target_arch = "wasm32")]
    pub(crate) font: String,
    pub(crate) font_size: u32,
    pub(crate) icon: Option<PathBuf>,
    pub(crate) asset_dir: PathBuf,
    pub(crate) x: Position,
    pub(crate) y: Position,
    pub(crate) width: u32,
    pub(crate) height: u32,
    pub(crate) scale_x: f32,
    pub(crate) scale_y: f32,
    pub(crate) audio_sample_rate: i32,
    pub(crate) fullscreen: bool,
    pub(crate) vsync: bool,
    pub(crate) resizable: bool,
    pub(crate) borderless: bool,
    pub(crate) allow_highdpi: bool,
    pub(crate) hidden: bool,
    pub(crate) show_frame_rate: bool,
    pub(crate) target_frame_rate: Option<Scalar>,
}

impl Default for RendererSettings {
    fn default() -> Self {
        Self {
            title: String::new(),
            #[cfg(not(target_arch = "wasm32"))]
            font: DEFAULT_ASSET_DIR.join("emulogic.ttf"),
            #[cfg(target_arch = "wasm32")]
            font: "Courier New".to_string(),
            font_size: 14,
            icon: None,
            asset_dir: DEFAULT_ASSET_DIR.clone(),
            x: Position::default(),
            y: Position::default(),
            width: 640,
            height: 480,
            scale_x: 1.0,
            scale_y: 1.0,
            audio_sample_rate: DEFAULT_SAMPLE_RATE,
            fullscreen: false,
            vsync: false,
            resizable: false,
            borderless: false,
            allow_highdpi: false,
            hidden: false,
            show_frame_rate: false,
            target_frame_rate: None,
        }
    }
}

/// Trait for operations on the underlying `Renderer`.
pub(crate) trait Rendering: Sized {
    /// Creates a new Renderer instance.
    fn new(settings: RendererSettings) -> Result<Self>;

    /// Clears the current canvas to the given clear color
    fn clear(&mut self) -> Result<()>;

    /// Sets the color used by the renderer to draw the current canvas.
    fn set_draw_color(&mut self, color: Color) -> Result<()>;

    /// Sets the clip rect used by the renderer to draw to the current canvas.
    fn clip(&mut self, rect: Option<Rect<i32>>) -> Result<()>;

    /// Sets the blend mode used by the renderer to drawing.
    fn blend_mode(&mut self, mode: BlendMode);

    /// Updates the canvas from the current back buffer.
    fn present(&mut self);

    /// Scale the current canvas.
    fn scale(&mut self, x: f32, y: f32) -> Result<()>;

    /// Set the font size for drawing to the current canvas.
    fn font_size(&mut self, size: u32) -> Result<()>;

    /// Set the font style for drawing to the current canvas.
    fn font_style(&mut self, style: FontStyle);

    /// Set the font family for drawing to the current canvas.
    fn font_family(&mut self, family: &str) -> Result<()>;

    /// Draw text to the current canvas. `angle` must be in degrees.
    fn text(
        &mut self,
        position: PointI2,
        text: &str,
        angle: Scalar,
        center: Option<PointI2>,
        flipped: Option<Flipped>,
        fill: Option<Color>,
    ) -> Result<()>;

    /// Returns the rendered dimensions of the given text using the current font
    /// as `(width, height)`.
    fn size_of(&self, text: &str) -> Result<(u32, u32)>;

    /// Draw a pixel to the current canvas.
    fn point(&mut self, p: PointI2, color: Color) -> Result<()>;

    /// Draw a line to the current canvas.
    fn line(&mut self, line: LineI2, color: Color) -> Result<()>;

    /// Draw a triangle to the current canvas.
    fn triangle(&mut self, tri: TriI2, fill: Option<Color>, stroke: Option<Color>) -> Result<()>;

    /// Draw a rectangle to the current canvas.
    fn rect(
        &mut self,
        rect: Rect<i32>,
        radius: Option<i32>,
        fill: Option<Color>,
        stroke: Option<Color>,
    ) -> Result<()>;

    /// Draw a quadrilateral to the current canvas.
    fn quad(&mut self, quad: QuadI2, fill: Option<Color>, stroke: Option<Color>) -> Result<()>;

    /// Draw a polygon to the current canvas.
    fn polygon(&mut self, ps: &[PointI2], fill: Option<Color>, stroke: Option<Color>)
        -> Result<()>;

    /// Draw a ellipse to the current canvas.
    fn ellipse(
        &mut self,
        ellipse: Ellipse<i32>,
        fill: Option<Color>,
        stroke: Option<Color>,
    ) -> Result<()>;

    /// Draw an arc to the current canvas.
    #[allow(clippy::too_many_arguments)]
    fn arc(
        &mut self,
        p: PointI2,
        radius: i32,
        start: i32,
        end: i32,
        mode: ArcMode,
        fill: Option<Color>,
        stroke: Option<Color>,
    ) -> Result<()>;

    /// Draw an image to the current canvas, optionally rotated about a `center`, flipped or
    /// tinted. `angle` must be in degrees.
    #[allow(clippy::too_many_arguments)]
    fn image(
        &mut self,
        img: &Image,
        src: Option<Rect<i32>>,
        dst: Option<Rect<i32>>,
        angle: Scalar,
        center: Option<PointI2>,
        flipped: Option<Flipped>,
        tint: Option<Color>,
    ) -> Result<()>;
}

/// The error type for `Renderer` operations.
#[non_exhaustive]
#[derive(Debug)]
pub enum Error {
    /// Renderer initialization errors.
    InitError,
    /// Renderer I/O errors.
    IoError(io::Error),
    /// Window errors.
    WindowError(WindowError),
    /// Invalid text.
    InvalidText(&'static str, NulError),
    /// Invalid font.
    #[cfg(not(target_arch = "wasm32"))]
    InvalidFont(PathBuf),
    /// Invalid Texture.
    InvalidTexture(TextureId),
    /// An error from invalid type conversions.
    Conversion(Cow<'static, str>),
    /// An overflow occurred.
    Overflow(Cow<'static, str>, u32),
    /// Any other unknown error as a string.
    Other(Cow<'static, str>),
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        use Error::*;
        match self {
            InitError => write!(f, "renderer initialization error"),
            InvalidText(msg, err) => write!(f, "invalid text: {}, {}", msg, err),
            InvalidTexture(id) => write!(f, "invalid texture_id: {}", id),
            Conversion(err) => write!(f, "conversion error: {}", err),
            Overflow(err, val) => write!(f, "overflow {}: {}", err, val),
            Other(err) => write!(f, "unknown renderer error: {}", err),
            _ => self.fmt(f),
        }
    }
}

impl error::Error for Error {
    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
        use Error::*;
        match self {
            IoError(err) => err.source(),
            WindowError(err) => err.source(),
            _ => None,
        }
    }
}

impl From<Error> for PixError {
    fn from(err: Error) -> Self {
        Self::RendererError(err)
    }
}

impl From<Error> for StateError {
    fn from(err: Error) -> Self {
        Self::RendererError(err)
    }
}

impl From<String> for Error {
    fn from(err: String) -> Self {
        Self::Other(err.into())
    }
}

impl From<std::num::TryFromIntError> for Error {
    fn from(err: std::num::TryFromIntError) -> Self {
        Self::Conversion(err.to_string().into())
    }
}

impl From<NulError> for Error {
    fn from(err: NulError) -> Self {
        Self::InvalidText("unknown nul error", err)
    }
}

impl From<PixError> for Error {
    fn from(err: PixError) -> Self {
        use PixError::*;
        match err {
            RendererError(err) => err,
            WindowError(err) => Error::WindowError(err),
            Conversion(err) => Error::Conversion(err),
            IoError(err) => Error::IoError(err),
            StateError(err) => Error::Other(err.to_string().into()),
            ImageError(err) => Error::Other(err.to_string().into()),
            Other(err) => Error::Other(err),
        }
    }
}