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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
//! Meenle_Noonle is my software renderer demo, built to help me learn things I didn't previously know.
//! It is a small Rust library with no dependencies, targeting wasm. It exports functions to act on an
//! internal frame buffer ([render], [draw_line]), as well as a function to get a pointer to the frame buffer
//! itself ([get_buffer]).

#![cfg_attr(target_arch = "powerpc", no_std)]
#[cfg(target_arch = "powerpc")]
extern crate alloc;
#[cfg(target_arch = "powerpc")]
use {alloc::vec, alloc::vec::Vec, rs_ppc_support::MSLmaths};

use core::ops::Mul;
pub mod demo;
pub mod meshes;

// dimensions for the canvas
pub const WIDTH: usize = 500;
pub const HEIGHT: usize = 500;

/// Frame buffer.
static mut BUFFER: [[Pixel; WIDTH]; HEIGHT] = [[Pixel {
    r: 0,
    g: 0,
    b: 0,
    a: 0,
}; WIDTH]; HEIGHT];

/// Frame buffer with the pretty background pattern. Used to clear the scene.
static mut BG_BUFFER: [[Pixel; WIDTH]; HEIGHT] = unsafe { BUFFER };

#[derive(Clone, Copy)]
pub enum Axis {
    X,
    Y,
    Z,
}

#[repr(C)]
#[derive(Debug, Clone, Copy)]
pub struct Vec3 {
    pub x: f64,
    pub y: f64,
    pub z: f64,
}

pub type Vertex = Vec3;
/// Pixel for the frame buffer. RGBA color, to match HTML canvas' buffer format.
#[repr(C)]
#[allow(dead_code)]
#[derive(Clone, Copy)]
pub struct Pixel {
    pub r: u8,
    pub g: u8,
    pub b: u8,
    pub a: u8,
}

impl Pixel {
    const _BLACK: Pixel = Pixel {
        r: 0,
        g: 0,
        b: 0,
        a: 255,
    };
    const WHITE: Pixel = Pixel {
        r: 255,
        g: 255,
        b: 255,
        a: 255,
    };
}

impl Mul<Vec3> for f64 {
    type Output = Vec3;

    fn mul(self, rhs: Vec3) -> Self::Output {
        Vec3::from([self * rhs.x, self * rhs.y, self * rhs.z])
    }
}

impl From<[f64; 3]> for Vec3 {
    fn from(nums: [f64; 3]) -> Self {
        Vec3 {
            x: nums[0],
            y: nums[1],
            z: nums[2],
        }
    }
}

/// Simple 3x3 Matrix for graphics maths.
pub struct Mat3x3 {
    pub mat: [[f64; 3]; 3],
}

impl Mat3x3 {
    /// This poorly named function actually gives the 3x3 identity matrix scaled by the parameter `val`.
    pub const fn identity(val: f64) -> Mat3x3 {
        Mat3x3 {
            mat: [[val, 0.0, 0.0], [0.0, val, 0.0], [0.0, 0.0, val]],
        }
    }

    /// Gives a rotation matrix to rotate a vertex about the origin.
    pub fn rot(angle: f64, axis: Axis) -> Mat3x3 {
        match axis {
            Axis::X => Mat3x3 {
                mat: [
                    [1.0, 0.0, 0.0],
                    [0.0, angle.cos(), angle.sin()],
                    [0.0, -angle.sin(), angle.cos()],
                ],
            },
            Axis::Y => Mat3x3 {
                mat: [
                    [angle.cos(), 0.0, -angle.sin()],
                    [0.0, 1.0, 0.0],
                    [angle.sin(), 0.0, angle.cos()],
                ],
            },
            Axis::Z => Mat3x3 {
                mat: [
                    [angle.cos(), -angle.sin(), 0.0],
                    [angle.sin(), angle.cos(), 0.0],
                    [0.0, 0.0, 1.0],
                ],
            },
        }
    }
}

impl Mul<Vec3> for Mat3x3 {
    type Output = Vec3;

    fn mul(self, rhs: Vec3) -> Self::Output {
        Vec3::from([
            rhs.x * self.mat[0][0] + rhs.y * self.mat[0][1] + rhs.z * self.mat[0][2],
            rhs.x * self.mat[1][0] + rhs.y * self.mat[1][1] + rhs.z * self.mat[1][2],
            rhs.x * self.mat[2][0] + rhs.y * self.mat[2][1] + rhs.z * self.mat[2][2],
        ])
    }
}

///Triangle.
#[derive(Debug, Copy, Clone)]
#[repr(C)]
pub struct Tri {
    pub verts: [Vertex; 3],
}

impl Tri {
    /// Draws itself into the framebuffer.
    fn render(&self) {
        const DEPTH_RANGE: f64 = 0.0;
        const MODEL_Z_RANGE: f64 = 50.0;
        let stereoscopy_offset = |idx_vtx: usize| -> f64 {
            (-2.0 * DEPTH_RANGE) * (self.verts[idx_vtx].z + MODEL_Z_RANGE) / (2.0 * MODEL_Z_RANGE)
                - DEPTH_RANGE
        };
        draw_line(
            self.verts[0].x + stereoscopy_offset(0),
            self.verts[0].y,
            self.verts[1].x + stereoscopy_offset(1),
            self.verts[1].y,
        );
        draw_line(
            self.verts[1].x + stereoscopy_offset(1),
            self.verts[1].y,
            self.verts[2].x + stereoscopy_offset(2),
            self.verts[2].y,
        );
        draw_line(
            self.verts[2].x + stereoscopy_offset(2),
            self.verts[2].y,
            self.verts[0].x + stereoscopy_offset(0),
            self.verts[0].y,
        );
    }
}

/// Mesh of triangles.
#[derive(Debug, Clone)]
pub struct Mesh {
    pub tris: Vec<Tri>,
    pub loc: Vec3,
    pub rot: Vec3,
}

impl From<Vec<Tri>> for Mesh {
    fn from(value: Vec<Tri>) -> Self {
        Mesh {
            tris: value,
            loc: Vec3::from([0.0, 0.0, 0.0]),
            rot: Vec3::from([0.0, 0.0, 0.0]),
        }
    }
}

impl Mesh {
    /// Creates a cube given two opposing vertices.
    #[rustfmt::skip]
    pub fn cube(v1: Vertex, v2: Vertex) -> Mesh {
        // Adapted from [javidx9's](https://www.youtube.com/c/javidx9/) olc 3d render engine
        Mesh::from (vec![
                // South
                Tri { verts: [ Vec3::from([ v1.x, v1.y, v1.z,]), Vec3::from([ v1.x, v2.y, v1.z,]), Vec3::from([ v2.x, v2.y, v1.z,])]},
                Tri { verts: [ Vec3::from([ v1.x, v1.y, v1.z,]), Vec3::from([ v2.x, v2.y, v1.z,]), Vec3::from([ v2.x, v1.y, v1.z,])]},

                // East
                Tri { verts: [ Vec3::from([ v2.x, v1.y, v1.z,]), Vec3::from([ v2.x, v2.y, v1.z,]), Vec3::from([ v2.x, v2.y, v2.z,])]},
                Tri { verts: [ Vec3::from([ v2.x, v1.y, v1.z,]), Vec3::from([ v2.x, v2.y, v2.z,]), Vec3::from([ v2.x, v1.y, v2.z,])]},

                // North
                Tri { verts: [ Vec3::from([ v2.x, v1.y, v2.z,]), Vec3::from([ v2.x, v2.y, v2.z,]), Vec3::from([ v1.x, v2.y, v2.z,])]},
                Tri { verts: [ Vec3::from([ v2.x, v1.y, v2.z,]), Vec3::from([ v1.x, v2.y, v2.z,]), Vec3::from([ v1.x, v1.y, v2.z,])]},

                // West
                Tri { verts: [ Vec3::from([ v1.x, v1.y, v2.z,]), Vec3::from([ v1.x, v2.y, v2.z,]), Vec3::from([ v1.x, v2.y, v1.z,])]},
                Tri { verts: [ Vec3::from([ v1.x, v1.y, v2.z,]), Vec3::from([ v1.x, v2.y, v1.z,]), Vec3::from([ v1.x, v1.y, v1.z,])]},

                // Top
                Tri { verts: [ Vec3::from([ v1.x, v2.y, v1.z,]), Vec3::from([ v1.x, v2.y, v2.z,]), Vec3::from([ v2.x, v2.y, v2.z ])]},
                Tri { verts: [ Vec3::from([ v1.x, v2.y, v1.z,]), Vec3::from([ v2.x, v2.y, v2.z,]), Vec3::from([ v2.x, v2.y, v1.z ])]},

                // Bottom
                Tri { verts: [ Vec3::from([ v2.x, v1.y, v2.z,]), Vec3::from([ v1.x, v1.y, v2.z,]), Vec3::from([ v1.x, v1.y, v1.z ])]},
                Tri { verts: [ Vec3::from([ v2.x, v1.y, v2.z,]), Vec3::from([ v1.x, v1.y, v1.z,]), Vec3::from([ v2.x, v1.y, v1.z ])]},
            ])
    }

    /// Scales the mesh by the given scalar.
    pub fn scale(&mut self, scalar: f64) {
        for tri in &mut self.tris {
            for vert in &mut tri.verts {
                *vert = Mat3x3::identity(scalar) * *vert
            }
        }
    }

    /// Rotates the mesh.
    pub fn rot(&mut self, axis: Axis, angle: f64) {
        for tri in &mut self.tris {
            for vert in &mut tri.verts {
                *vert = Mat3x3::rot(angle, axis) * *vert;
            }
        }
    }

    /// Draws the mesh into the framebuffer.
    fn render(&self) {
        for tri in &self.tris {
            tri.render();
        }
    }
}

/// Plots a single pixel into the frame buffer.
fn plot_pixel(x: usize, y: usize, pixel: &Pixel) {
    unsafe {
        *BUFFER
            .get_mut(y)
            .unwrap_or(&mut BUFFER[0])
            .get_mut(x)
            .unwrap_or(&mut BUFFER[0][0]) = *pixel;
    }
}

/// Uses Bresenham's algorithm to draw a line.
#[no_mangle]
pub extern "C" fn draw_line(x0: f64, y0: f64, x1: f64, y1: f64) {
    let mut x0 = x0 as i32 + (WIDTH / 2) as i32;
    let mut y0 = y0 as i32 + (WIDTH / 2) as i32;
    let mut x1 = x1 as i32 + (WIDTH / 2) as i32;
    let mut y1 = y1 as i32 + (WIDTH / 2) as i32;

    let steep = (y1 - y0).abs() > (x1 - x0).abs();
    if steep {
        core::mem::swap(&mut x0, &mut y0);
        core::mem::swap(&mut x1, &mut y1);
    }
    if x0 > x1 {
        core::mem::swap(&mut x0, &mut x1);
        core::mem::swap(&mut y0, &mut y1);
    }

    let dx = x1 - x0;
    let dy = (y1 - y0).abs();
    let mut error = dx / 2;
    let ystep = if y0 < y1 { 1 } else { -1 };
    let mut y = y0;

    for x in x0..=x1 {
        if steep {
            plot_pixel(y as usize, x as usize, &Pixel::WHITE);
        } else {
            plot_pixel(x as usize, y as usize, &Pixel::WHITE);
        }
        error -= dy;
        if error < 0 {
            y += ystep;
            error += dx;
        }
    }
}

/// Generates the pretty background pattern.
#[no_mangle]
pub extern "C" fn generate_background() {
    unsafe {
        for (idx_row, row) in BG_BUFFER.iter_mut().enumerate() {
            for (idx_col, pxl) in row.iter_mut().enumerate() {
                *pxl = Pixel {
                    r: ((255.0 / HEIGHT as f64) * idx_row as f64) as u8,
                    g: ((255.0 / WIDTH as f64) * idx_col as f64) as u8,
                    b: ((-(255.0 / HEIGHT as f64) * idx_row as f64) + 255.0) as u8,
                    a: 255,
                };
            }
        }
    }
}

/// Fills the frame buffer with a pretty pattern.
#[no_mangle]
pub extern "C" fn fill_buffer() {
    unsafe {
        BUFFER = BG_BUFFER;
    }
}

/// Gets a pointer to the frame buffer.
#[no_mangle]
pub extern "C" fn get_buffer() -> &'static [[Pixel; WIDTH]; HEIGHT] {
    unsafe { &BUFFER }
}

/// Renders the demo into the frame buffer.
#[no_mangle]
pub extern "C" fn render(scalar: f64, x_angle: f64, y_angle: f64, z_angle: f64) {
    let mut demo_mesh = meshes::monkey();
    demo_mesh.scale(50.0);

    demo_mesh.scale(scalar);

    demo_mesh.rot(Axis::X, x_angle);
    demo_mesh.rot(Axis::Y, y_angle);
    demo_mesh.rot(Axis::Z, z_angle);

    fill_buffer();
    demo_mesh.render();
}