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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
//! Matrix math types and functions.

use lambda_platform::rand::get_uniformly_random_floats_between;

use super::{
  turns_to_radians,
  vector::Vector,
};

// -------------------------------- MATRIX -------------------------------------

/// Matrix trait which defines the basic operations that can be performed on a
/// matrix. Lambda currently implements this trait for f32 arrays of arrays
/// for any size.
pub trait Matrix<V: Vector> {
  fn add(&self, other: &Self) -> Self;
  fn subtract(&self, other: &Self) -> Self;
  fn multiply(&self, other: &Self) -> Self;
  fn transpose(&self) -> Self;
  fn inverse(&self) -> Self;
  fn transform(&self, other: &V) -> V;
  fn determinant(&self) -> f32;
  fn size(&self) -> (usize, usize);
  fn row(&self, row: usize) -> &V;
  fn at(&self, row: usize, column: usize) -> V::Scalar;
  fn update(&mut self, row: usize, column: usize, value: V::Scalar);
}

// -------------------------------- FUNCTIONS ----------------------------------

/// Obtain the submatrix of the input matrix starting from the given row &
/// column.
pub fn submatrix<V: Vector<Scalar = f32>, MatrixLike: Matrix<V>>(
  matrix: MatrixLike,
  row: usize,
  column: usize,
) -> Vec<Vec<V::Scalar>> {
  let mut submatrix = Vec::new();
  let (rows, columns) = matrix.size();

  for k in 0..rows {
    if k != row {
      let mut row = Vec::new();
      for l in 0..columns {
        if l != column {
          row.push(matrix.at(k, l));
        }
      }
      submatrix.push(row);
    }
  }
  return submatrix;
}

/// Creates a translation matrix with the given translation vector. The output vector
pub fn translation_matrix<
  InputVector: Vector<Scalar = f32>,
  ResultingVector: Vector<Scalar = f32>,
  OutputMatrix: Matrix<ResultingVector> + Default,
>(
  vector: InputVector,
) -> OutputMatrix {
  let mut result = OutputMatrix::default();
  let (rows, columns) = result.size();
  assert_eq!(
    rows - 1,
    vector.size(),
    "Vector must contain one less element than the vectors of the input matrix"
  );

  for i in 0..rows {
    for j in 0..columns {
      if i == j {
        result.update(i, j, 1.0);
      } else if j == columns - 1 {
        result.update(i, j, vector.at(i));
      } else {
        result.update(i, j, 0.0);
      }
    }
  }

  return result;
}

/// Rotates the input matrix by the given number of turns around the given axis.
/// The axis must be a unit vector and the turns must be in the range [0, 1).
/// The rotation is counter-clockwise when looking down the axis.
pub fn rotate_matrix<
  InputVector: Vector<Scalar = f32>,
  ResultingVector: Vector<Scalar = f32>,
  OutputMatrix: Matrix<ResultingVector> + Default + Clone,
>(
  matrix_to_rotate: OutputMatrix,
  axis_to_rotate: InputVector,
  angle_in_turns: f32,
) -> OutputMatrix {
  let (rows, columns) = matrix_to_rotate.size();
  assert_eq!(rows, columns, "Matrix must be square");
  assert_eq!(rows, 4, "Matrix must be 4x4");
  assert_eq!(
    axis_to_rotate.size(),
    3,
    "Axis vector must have 3 elements (x, y, z)"
  );

  let angle_in_radians = turns_to_radians(angle_in_turns);
  let cosine_of_angle = angle_in_radians.cos();
  let sin_of_angle = angle_in_radians.sin();

  let t = 1.0 - cosine_of_angle;
  let x = axis_to_rotate.at(0);
  let y = axis_to_rotate.at(1);
  let z = axis_to_rotate.at(2);

  let mut rotation_matrix = OutputMatrix::default();

  let rotation = match (x as u8, y as u8, z as u8) {
    (0, 0, 0) => {
      // No rotation
      return matrix_to_rotate;
    }
    (0, 0, 1) => {
      // Rotate around z-axis
      [
        [cosine_of_angle, sin_of_angle, 0.0, 0.0],
        [-sin_of_angle, cosine_of_angle, 0.0, 0.0],
        [0.0, 0.0, 1.0, 0.0],
        [0.0, 0.0, 0.0, 1.0],
      ]
    }
    (0, 1, 0) => {
      // Rotate around y-axis
      [
        [cosine_of_angle, 0.0, -sin_of_angle, 0.0],
        [0.0, 1.0, 0.0, 0.0],
        [sin_of_angle, 0.0, cosine_of_angle, 0.0],
        [0.0, 0.0, 0.0, 1.0],
      ]
    }
    (1, 0, 0) => {
      // Rotate around x-axis
      [
        [1.0, 0.0, 0.0, 0.0],
        [0.0, cosine_of_angle, sin_of_angle, 0.0],
        [0.0, -sin_of_angle, cosine_of_angle, 0.0],
        [0.0, 0.0, 0.0, 1.0],
      ]
    }
    _ => {
      panic!("Axis must be a unit vector")
    }
  };

  for i in 0..rows {
    for j in 0..columns {
      rotation_matrix.update(i, j, rotation[i][j]);
    }
  }

  return matrix_to_rotate.multiply(&rotation_matrix);
}

/// Creates a 4x4 perspective matrix given the fov in turns (unit between
/// 0..2pi radians), aspect ratio, near clipping plane (also known as z_near),
/// and far clipping plane (also known as z_far). Enforces that the matrix being
/// created is square in both debug and release builds, but only enforces that
/// the output matrix is 4x4 in debug builds.
pub fn perspective_matrix<
  V: Vector<Scalar = f32>,
  MatrixLike: Matrix<V> + Default,
>(
  fov: V::Scalar,
  aspect_ratio: V::Scalar,
  near_clipping_plane: V::Scalar,
  far_clipping_plane: V::Scalar,
) -> MatrixLike {
  let mut result = MatrixLike::default();
  let (rows, columns) = result.size();
  assert_eq!(
    rows, columns,
    "Matrix must be square to be a perspective matrix"
  );
  debug_assert_eq!(rows, 4, "Matrix must be 4x4 to be a perspective matrix");
  let fov_in_radians = turns_to_radians(fov);
  let f = 1.0 / (fov_in_radians / 2.0).tan();
  let range = near_clipping_plane - far_clipping_plane;

  result.update(0, 0, f / aspect_ratio);
  result.update(1, 1, f);
  result.update(2, 2, (near_clipping_plane + far_clipping_plane) / range);
  result.update(2, 3, -1.0);
  result.update(
    3,
    2,
    (2.0 * near_clipping_plane * far_clipping_plane) / range,
  );

  return result;
}

/// Create a matrix of any size that is filled with zeros.
pub fn zeroed_matrix<
  V: Vector<Scalar = f32>,
  MatrixLike: Matrix<V> + Default,
>(
  rows: usize,
  columns: usize,
) -> MatrixLike {
  let mut result = MatrixLike::default();
  for i in 0..rows {
    for j in 0..columns {
      result.update(i, j, 0.0);
    }
  }
  return result;
}

/// Creates a new matrix with the given number of rows and columns, and fills it
/// with the given value.
pub fn filled_matrix<
  V: Vector<Scalar = f32>,
  MatrixLike: Matrix<V> + Default,
>(
  rows: usize,
  columns: usize,
  value: V::Scalar,
) -> MatrixLike {
  let mut result = MatrixLike::default();
  for i in 0..rows {
    for j in 0..columns {
      result.update(i, j, value);
    }
  }
  return result;
}

/// Creates an identity matrix of the given size.
pub fn identity_matrix<
  V: Vector<Scalar = f32>,
  MatrixLike: Matrix<V> + Default,
>(
  rows: usize,
  columns: usize,
) -> MatrixLike {
  assert_eq!(
    rows, columns,
    "Matrix must be square to be an identity matrix"
  );
  let mut result = MatrixLike::default();
  for i in 0..rows {
    for j in 0..columns {
      if i == j {
        result.update(i, j, 1.0);
      } else {
        result.update(i, j, 0.0);
      }
    }
  }
  return result;
}

// -------------------------- ARRAY IMPLEMENTATION -----------------------------

/// Matrix implementations for arrays of f32 arrays. Including the trait Matrix into
/// your code will allow you to use these function implementation for any array
/// of f32 arrays.
impl<Array, V> Matrix<V> for Array
where
  Array: AsMut<[V]> + AsRef<[V]> + Default,
  V: AsMut<[f32]> + AsRef<[f32]> + Vector<Scalar = f32> + Sized,
{
  fn add(&self, other: &Self) -> Self {
    let mut result = Self::default();
    for (i, (a, b)) in
      self.as_ref().iter().zip(other.as_ref().iter()).enumerate()
    {
      result.as_mut()[i] = a.add(b);
    }
    return result;
  }

  fn subtract(&self, other: &Self) -> Self {
    let mut result = Self::default();

    for (i, (a, b)) in
      self.as_ref().iter().zip(other.as_ref().iter()).enumerate()
    {
      result.as_mut()[i] = a.subtract(b);
    }
    return result;
  }

  fn multiply(&self, other: &Self) -> Self {
    let mut result = Self::default();

    // We transpose the other matrix to convert the columns into rows, allowing
    // us to compute the new values of each index using the dot product
    // function.
    let transposed = other.transpose();

    for (i, a) in self.as_ref().iter().enumerate() {
      for (j, b) in transposed.as_ref().iter().enumerate() {
        result.update(i, j, a.dot(b));
      }
    }
    return result;
  }

  /// Transposes the matrix, swapping the rows and columns.
  fn transpose(&self) -> Self {
    let mut result = Self::default();
    for (i, a) in self.as_ref().iter().enumerate() {
      for j in 0..a.as_ref().len() {
        result.update(i, j, self.at(j, i));
      }
    }
    return result;
  }

  fn inverse(&self) -> Self {
    todo!()
  }

  fn transform(&self, other: &V) -> V {
    todo!()
  }

  /// Computes the determinant of any square matrix using Laplace expansion.
  fn determinant(&self) -> f32 {
    let (width, height) =
      (self.as_ref()[0].as_ref().len(), self.as_ref().len());

    if width != height {
      panic!("Cannot compute determinant of non-square matrix");
    }

    return match height {
      1 => self.as_ref()[0].as_ref()[0],
      2 => {
        let a = self.at(0, 0);
        let b = self.at(0, 1);
        let c = self.at(1, 0);
        let d = self.at(1, 1);
        a * d - b * c
      }
      _ => {
        let mut result = 0.0;
        for i in 0..height {
          let mut submatrix: Vec<Vec<f32>> = Vec::with_capacity(height - 1);
          for j in 1..height {
            let mut row = Vec::new();
            for k in 0..height {
              if k != i {
                row.push(self.at(j, k));
              }
            }
            submatrix.push(row);
          }
          result += self.at(0, i)
            * submatrix.determinant()
            * (-1.0 as f32).powi(i as i32);
        }
        result
      }
    };
  }

  /// Return the size as a (rows, columns).
  fn size(&self) -> (usize, usize) {
    return (self.as_ref().len(), self.row(0).size());
  }

  /// Return a reference to the row.
  fn row(&self, row: usize) -> &V {
    return &self.as_ref()[row];
  }

  ///
  fn at(&self, row: usize, column: usize) -> <V as Vector>::Scalar {
    return self.as_ref()[row].as_ref()[column];
  }

  fn update(&mut self, row: usize, column: usize, new_value: V::Scalar) {
    self.as_mut()[row].as_mut()[column] = new_value;
  }
}

// ---------------------------------- TESTS ------------------------------------

#[cfg(test)]
mod tests {

  use super::{
    filled_matrix,
    perspective_matrix,
    rotate_matrix,
    submatrix,
    Matrix,
  };
  use crate::math::{
    matrix::translation_matrix,
    turns_to_radians,
  };

  #[test]
  fn square_matrix_add() {
    let a = [[1.0, 2.0], [3.0, 4.0]];
    let b = [[5.0, 6.0], [7.0, 8.0]];
    let c = a.add(&b);
    assert_eq!(c, [[6.0, 8.0], [10.0, 12.0]]);
  }

  #[test]
  fn square_matrix_subtract() {
    let a = [[1.0, 2.0], [3.0, 4.0]];
    let b = [[5.0, 6.0], [7.0, 8.0]];
    let c = a.subtract(&b);
    assert_eq!(c, [[-4.0, -4.0], [-4.0, -4.0]]);
  }

  #[test]
  // Test square matrix multiplication.
  fn square_matrix_multiply() {
    let m1 = [[1.0, 2.0], [3.0, 4.0]];
    let m2 = [[2.0, 0.0], [1.0, 2.0]];

    let mut result = m1.multiply(&m2);
    assert_eq!(result, [[4.0, 4.0], [10.0, 8.0]]);

    result = m2.multiply(&m1);
    assert_eq!(result, [[2.0, 4.0], [7.0, 10.0]])
  }

  #[test]
  fn transpose_square_matrix() {
    let m = [[1.0, 2.0], [5.0, 6.0]];
    let t = m.transpose();
    assert_eq!(t, [[1.0, 5.0], [2.0, 6.0]]);
  }

  #[test]
  fn square_matrix_determinant() {
    let m = [[3.0, 8.0], [4.0, 6.0]];
    assert_eq!(m.determinant(), -14.0);

    let m2 = [[6.0, 1.0, 1.0], [4.0, -2.0, 5.0], [2.0, 8.0, 7.0]];
    assert_eq!(m2.determinant(), -306.0);
  }

  #[test]
  fn non_square_matrix_determinant() {
    let m = [[3.0, 8.0], [4.0, 6.0], [0.0, 1.0]];
    let result = std::panic::catch_unwind(|| m.determinant());
    assert_eq!(false, result.is_ok());
  }

  #[test]
  fn submatrix_for_matrix_array() {
    let matrix = [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]];

    let expected_submatrix = vec![vec![2.0, 3.0], vec![8.0, 9.0]];
    let actual_submatrix = submatrix(matrix, 1, 0);

    assert_eq!(expected_submatrix, actual_submatrix);
  }

  #[test]
  fn translate_matrix() {
    let translation: [[f32; 3]; 3] = translation_matrix([56.0, 5.0]);
    assert_eq!(
      translation,
      [[1.0, 0.0, 56.0], [0.0, 1.0, 5.0], [0.0, 0.0, 1.0]]
    );

    let translation: [[f32; 4]; 4] = translation_matrix([10.0, 2.0, 3.0]);
    let expected = [
      [1.0, 0.0, 0.0, 10.0],
      [0.0, 1.0, 0.0, 2.0],
      [0.0, 0.0, 1.0, 3.0],
      [0.0, 0.0, 0.0, 1.0],
    ];
    assert_eq!(translation, expected);
  }

  #[test]
  fn perspective_matrix_test() {
    let perspective: [[f32; 4]; 4] =
      perspective_matrix(1.0 / 4.0, 1.0, 1.0, 0.0);

    // Compute the field of view values used by the perspective matrix by hand.
    let fov_radians = turns_to_radians(1.0 / 4.0);
    let f = 1.0 / (fov_radians / 2.0).tan();

    let expected: [[f32; 4]; 4] = [
      [f, 0.0, 0.0, 0.0],
      [0.0, f, 0.0, 0.0],
      [0.0, 0.0, 1.0, -1.0],
      [0.0, 0.0, 0.0, 0.0],
    ];

    assert_eq!(perspective, expected);
  }

  /// Test the rotation matrix for a 3D rotation.
  #[test]
  fn rotate_matrices() {
    // Test a zero turn rotation.
    let matrix: [[f32; 4]; 4] = filled_matrix(4, 4, 1.0);
    let rotated_matrix = rotate_matrix(matrix, [0.0, 0.0, 1.0], 0.0);
    assert_eq!(rotated_matrix, matrix);

    // Test a 90 degree rotation.
    let matrix = [
      [1.0, 2.0, 3.0, 4.0],
      [5.0, 6.0, 7.0, 8.0],
      [9.0, 10.0, 11.0, 12.0],
      [13.0, 14.0, 15.0, 16.0],
    ];
    let rotated = rotate_matrix(matrix, [0.0, 1.0, 0.0], 0.25);
    let expected = [
      [3.0, 1.9999999, -1.0000001, 4.0],
      [7.0, 5.9999995, -5.0000005, 8.0],
      [11.0, 9.999999, -9.000001, 12.0],
      [14.999999, 13.999999, -13.000001, 16.0],
    ];

    println!("rotated: {:?}", rotated);
    for i in 0..4 {
      for j in 0..4 {
        crate::assert_approximately_equal!(
          rotated.at(i, j),
          expected.at(i, j),
          0.1
        );
      }
    }
  }
}