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
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
#![allow(clippy::many_single_char_names)]
use crate::{
  num::DefaultFloat,
  quat::Quat,
  vec::{Vec2, Vec3, Vec4, Vector},
};
use num::{Float, One, Zero};
use std::{
  array::LengthAtMost32,
  ops::{Add, Div, Index, IndexMut, Mul, Range, Sub},
};

/// A matrix, where each vector represents a column
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct Matrix<T = DefaultFloat, const M: usize, const N: usize>(pub [Vector<T, M>; N])
where
  [T; M]: LengthAtMost32,
  [Vector<T, M>; N]: LengthAtMost32;

/// 4x4 Matrix
pub type Mat4<T = DefaultFloat> = Matrix<T, 4, 4>;
/// 3x3 Matrix
pub type Mat3<T = DefaultFloat> = Matrix<T, 3, 3>;
/// 2x2 Matrix
pub type Mat2<T = DefaultFloat> = Matrix<T, 2, 2>;

impl<T: Float, const M: usize, const N: usize> Matrix<T, M, N>
where
  [T; M]: LengthAtMost32,
  [T; N]: LengthAtMost32,
  [Vector<T, M>; N]: LengthAtMost32,
{
  pub fn dot(&self, vec: &Vector<T, N>) -> Vector<T, M> {
    let mut out: Vector<T, M> = Vector::zero();
    for i in 0..N {
      out = out + self.0[i] * vec[i];
    }
    out
  }
  pub(crate) fn qdot<const Q: usize>(&self, vec: &Vector<T, Q>) -> Vector<T, M>
  where
    [T; Q]: LengthAtMost32, {
    // Check that Q is less than or equal to N.
    // We allow smaller values so we can multiply smaller vectors efficiently
    assert!(Q <= N);
    let mut out: Vector<T, M> = Vector::zero();
    for i in 0..Q {
      out = out + self.0[i] * vec[i];
    }
    out
  }
  pub fn t(&self) -> Matrix<T, N, M>
  where
    [Vector<T, N>; M]: LengthAtMost32, {
    let mut empty: Matrix<T, N, M> = Matrix::zero();
    for y in 0..N {
      for x in 0..M {
        empty.0[y][x] = self.0[y][x];
      }
    }
    empty
  }
  /// Performs naive matrix multiplication
  pub fn matmul<const P: usize>(&self, o: Matrix<T, N, P>) -> Matrix<T, M, P>
  where
    [Vector<T, N>; P]: LengthAtMost32,
    [Vector<T, M>; P]: LengthAtMost32,
    [T; P]: LengthAtMost32, {
    let mut empty: Matrix<T, M, P> = Matrix::zero();
    for i in 0..P {
      empty[i] = self.dot(&o[i]);
    }
    empty
  }
  pub fn swap_rows(&mut self, cols: Range<usize>, a: usize, b: usize) {
    assert!(a < M);
    assert!(b < M);
    for i in cols {
      self[i].0.swap(a, b);
    }
  }
  pub fn swap_cols(&mut self, a: usize, b: usize) {
    assert!(a < N);
    assert!(b < N);
    self.0.swap(a, b);
  }
  pub fn apply_fn<F, S>(&self, f: F) -> Matrix<S, M, N>
  where
    F: FnMut(T) -> S + Copy,
    S: Float,
    [S; M]: LengthAtMost32,
    [S; N]: LengthAtMost32,
    [Vector<S, M>; N]: LengthAtMost32, {
    let mut empty: Matrix<S, M, N> = Matrix::zero();
    for i in 0..N {
      empty[i] = self[i].apply_fn(f);
    }
    empty
  }
  /// Zero extend this matrix to a larger size
  pub fn zxtend<const I: usize, const J: usize>(&self) -> Matrix<T, I, J>
  where
    [T; I]: LengthAtMost32,
    [T; J]: LengthAtMost32,
    [Vector<T, I>; J]: LengthAtMost32, {
    assert!(I >= M);
    assert!(J >= N);
    let mut out: Matrix<T, I, J> = Matrix::zero();
    for i in 0..N {
      out[i] = self[i].zxtend();
    }
    out
  }
  /// Take some subset of this matrix(only takes from the topt left)
  pub fn reduce<const I: usize, const J: usize>(&self) -> Matrix<T, I, J>
  where
    [T; I]: LengthAtMost32,
    [T; J]: LengthAtMost32,
    [Vector<T, I>; J]: LengthAtMost32, {
    assert!(I <= M);
    assert!(J <= N);
    let mut out: Matrix<T, I, J> = Matrix::zero();
    for i in 0..J {
      out[i] = self[i].reduce();
    }
    out
  }
  pub fn frobenius(&self) -> T { self.0.iter().fold(T::zero(), |acc, n| acc + n.dot(n)) }
}

impl<T: Float, const M: usize> Matrix<T, M, M>
where
  [T; M]: LengthAtMost32,
  [Vector<T, M>; M]: LengthAtMost32,
{
  /// Returns elements on the diagonal from top left to bottom right
  pub fn diag(&self) -> impl Iterator<Item = T> + '_ { (0..M).map(move |i| self[i][i]) }
  /// Returns elements not on the diagonal in no specific order
  pub fn off_diag(&self) -> impl Iterator<Item = T> + '_ {
    (0..M).flat_map(move |i| (0..M).filter(move |&j| j != i).map(move |j| self[i][j]))
  }
  pub fn trace(&self) -> T { self.diag().fold(T::zero(), |acc, n| acc + n) }
  /// LUP decomposes self into lower triangular, upper triangular and pivot matrix
  pub fn lup(&self) -> (Self, Self, Self) {
    let mut l = Self::one();
    let mut u = *self;
    let mut p = Self::one();
    for k in 0..(M - 1) {
      let i = k + argmax(&u.0[k].apply_fn(T::abs).0[k..]);
      u.swap_rows(k..M, i, k);
      l.swap_rows(0..k, i, k);
      p.swap_rows(0..M, i, k);
      for j in (k + 1)..M {
        l.0[k][j] = u.0[k][j] / u.0[k][k];
        for i in k..M {
          u.0[i][j] = u.0[i][j] - l.0[k][j] * u.0[i][k];
        }
      }
    }
    (l, u, p)
  }
  /// Given an upper triangular matrix and a vector, compute the solution to the system of
  /// equations
  pub fn usolve(&self, b: &Vector<T, M>) -> Vector<T, M> {
    let mut out: Vector<T, M> = Vector::zero();
    for y in (0..M).rev() {
      let mut acc = b[y];
      for x in y + 1..M {
        acc = acc - out[x] * self[x][y];
      }
      out[y] = acc / self[y][y];
    }
    out
  }
  /// Given a lower triangular matrix and a vector, compute the solution to the system of
  /// equations
  pub fn lsolve(&self, b: &Vector<T, M>) -> Vector<T, M> {
    let mut out: Vector<T, M> = Vector::zero();
    for y in 0..M {
      let mut acc = b[y];
      for x in 0..y.saturating_sub(1) {
        acc = acc - out[x] * self[x][y];
      }
      out[y] = acc / self[y][y];
    }
    out
  }
  /// Solves for x in the linear system Ax = b;
  pub fn solve((l, u, p): &(Self, Self, Self), b: &Vector<T, M>) -> Vector<T, M> {
    u.usolve(&l.lsolve(&p.dot(b)))
  }
}

impl<T: Float, const M: usize, const N: usize> Zero for Matrix<T, M, N>
where
  [T; M]: LengthAtMost32,
  [T; N]: LengthAtMost32,
  [Vector<T, M>; N]: LengthAtMost32,
{
  fn zero() -> Self { Matrix([Vector::zero(); N]) }
  fn is_zero(&self) -> bool { self.0.iter().any(|c| c.is_zero()) }
}

impl<T: Float> Mat3<T> {
  pub fn new(c0: Vec3<T>, c1: Vec3<T>, c2: Vec3<T>) -> Self { Matrix([c0, c1, c2]) }
  /// Computes the determinant of this matrix
  pub fn det(&self) -> T {
    let &Matrix([Vector([e00, e01, e02]), Vector([e10, e11, e12]), Vector([e20, e21, e22])]) = self;
    e00 * e11 * e22 +
    e01 * e12 * e20 +
    e02 * e10 * e21 -
    // subtraction component
    e02 * e11 * e20 -
    e01 * e10 * e22 -
    e00 * e12 * e21
  }
  /// Inverts this matrix, does not handle non-invertible matrices
  pub fn inv(&self) -> Self { self.t() / self.det() }
  pub fn rot(around: &Vec3<T>, cos_t: T) -> Self {
    let &Vector([i, j, k]) = around;
    let l = T::one();
    let sin_t = l - cos_t * cos_t;
    Self([
      Vector([
        i * i * (l - cos_t) + cos_t,
        i * j * (l - cos_t) + k * sin_t,
        i * k * (l - cos_t) - j * sin_t,
      ]),
      Vector([
        i * j * (l - cos_t) - k * sin_t,
        j * j * (l - cos_t) + cos_t,
        j * k * (l - cos_t) - i * sin_t,
      ]),
      Vector([
        i * k * (l - cos_t) + k * sin_t,
        j * k * (l - cos_t) - i * sin_t,
        k * k * (l - cos_t) + cos_t,
      ]),
    ])
  }
  pub fn scale(by: &Vec3<T>) -> Self {
    let &Vector([i, j, k]) = by;
    let o = T::zero();
    Self([Vector([i, o, o]), Vector([o, j, o]), Vector([o, o, k])])
  }
  /// Translation operator for 2 space
  pub fn translate(by: &Vec2<T>) -> Self {
    let &Vector([i, j]) = by;
    let o = T::zero();
    let l = T::one();
    Self([Vector([l, o, i]), Vector([o, l, j]), Vector([o, o, l])])
  }
  pub fn project(normal: &Vec3<T>) -> Self {
    let normal = normal.norm();
    let Vector([i, j, k]) = normal;
    let l = T::one();
    let o = T::zero();
    let (x, y, z) = match (i.is_zero(), j.is_zero(), k.is_zero()) {
      (true, true, true) => return Self::zero(),
      (true, true, false) | (true, false, true) => (l, o, o),
      (false, true, true) => (o, o, l),
      (false, false, true) => (-j, i, k),
      (false, true, false) => (-k, j, i),
      (true, false, false) => (i, -k, j),
      (false, false, false) => (i, k, -j),
    };
    let b_0 = Vector([x, y, z]);
    let b_1 = normal.cross(&b_0);
    Self([b_0, b_1, Vec3::zero()])
  }
  /// https://en.wikipedia.org/wiki/Quaternions_and_spatial_rotation
  /// Converts a quaternion into an equivalent matrix
  pub fn from_quat(q: Quat<T>) -> Self {
    let Vector([x, y, z, w]) = q;
    let t = T::one() + T::one();
    Matrix([
      Vec3::new(
        w * w + x * x - y * y - z * z,
        t * x * y + t * w * z,
        t * x * z - t * w * y,
      ),
      Vec3::new(
        t * x * y - t * w * z,
        w * w - x * x + y * y - z * z,
        t * y * z + t * w * x,
      ),
      Vec3::new(
        t * x * z + t * w * y,
        t * y * z - t * w * x,
        w * w - x * x - y * y + z * z,
      ),
    ])
  }
}

impl<T: Float> Mat2<T> {
  /// Computes the determinant of this matrix
  pub fn det(&self) -> T {
    let &Matrix([Vector([e00, e01]), Vector([e10, e11])]) = self;
    e00 * e11 - e01 * e10
  }
  /// Inverts this matrix, does not handle non-invertible matrices
  pub fn inv(&self) -> Self {
    let det = self.det();
    let &Matrix([Vector([e00, e01]), Vector([e10, e11])]) = self;
    Matrix([Vector([e11, -e01]), Vector([-e10, e00])]) / det
  }
  /// Returns the rotation matrix given a theta in the counterclockwise direction
  pub fn rot(theta: T) -> Self {
    let (sin_t, cos_t) = theta.sin_cos();
    Matrix([Vector([cos_t, sin_t]), Vector([-sin_t, cos_t])])
  }
  /// Returns the scale matrix given scale in each direction
  pub fn scale(sx: T, sy: T) -> Self {
    let o = T::zero();
    Matrix([Vec2::new(sx, o), Vec2::new(o, sy)])
  }
}

/// Multiplicative identity
impl<T: Float, const M: usize> One for Matrix<T, M, M>
where
  [T; M]: LengthAtMost32,
  [Vector<T, M>; M]: LengthAtMost32,
{
  fn one() -> Self {
    let mut empty = Self::zero();
    for i in 0..M {
      empty[i][i] = T::zero();
    }
    empty
  }
  fn is_one(&self) -> bool {
    self.diag().all(|v| v.is_one()) && self.off_diag().all(|v| v.is_zero())
  }
}

/// Computes the argmax over a slice of floats assuming it is non-empty
fn argmax<T: Float>(v: &[T]) -> usize {
  assert!(!v.is_empty());
  v.iter()
    .enumerate()
    .max_by(|(_, a), (_, b)| a.partial_cmp(b).unwrap())
    .unwrap()
    .0
}

impl<T: Float> Mat4<T> {
  pub fn new(c0: Vec4<T>, c1: Vec4<T>, c2: Vec4<T>, c3: Vec4<T>) -> Self {
    Matrix([c0, c1, c2, c3])
  }
  /// Returns a translation matrix by t
  pub fn translate(t: Vec3<T>) -> Self {
    let l = T::one();
    let o = T::zero();
    let Vector([x, y, z]) = t;
    Matrix([
      Vector([l, o, o, o]),
      Vector([o, l, o, o]),
      Vector([o, o, l, o]),
      Vector([x, y, z, l]),
    ])
  }
  // Computes the determinant of this matrix
  // fn det(&self) -> T { todo!() }

  /// Computes the inverse of this matrix if it exists
  pub fn inv(&self) -> Self {
    // twas a b'
    // taken from https://github.com/mrdoob/three.js/blob/master/src/math/Matrix4.js
    // which took it from http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
    let &Matrix(
      [Vector([e11, e21, e31, e41]), Vector([e12, e22, e32, e42]), Vector([e13, e23, e33, e43]), Vector([e14, e24, e34, e44])],
    ) = self;
    let t11 =
      e23 * e34 * e42 - e24 * e33 * e42 + e24 * e32 * e43 - e22 * e34 * e43 - e23 * e32 * e44
        + e22 * e33 * e44;
    let t12 =
      e14 * e33 * e42 - e13 * e34 * e42 - e14 * e32 * e43 + e12 * e34 * e43 + e13 * e32 * e44
        - e12 * e33 * e44;
    let t13 =
      e13 * e24 * e42 - e14 * e23 * e42 + e14 * e22 * e43 - e12 * e24 * e43 - e13 * e22 * e44
        + e12 * e23 * e44;
    let t14 =
      e14 * e23 * e32 - e13 * e24 * e32 - e14 * e22 * e33 + e12 * e24 * e33 + e13 * e22 * e34
        - e12 * e23 * e34;
    let det = e11 * t11 + e21 * t12 + e31 * t13 + e41 * t14;
    // Don't check if det is zero here just assume it's invertible
    let det_i = det.recip();
    let o11 = t11 * det_i;
    let o21 =
      (e24 * e33 * e41 - e23 * e34 * e41 - e24 * e31 * e43 + e21 * e34 * e43 + e23 * e31 * e44
        - e21 * e33 * e44)
        * det_i;
    let o31 =
      (e22 * e34 * e41 - e24 * e32 * e41 + e24 * e31 * e42 - e21 * e34 * e42 - e22 * e31 * e44
        + e21 * e32 * e44)
        * det_i;
    let o41 =
      (e23 * e32 * e41 - e22 * e33 * e41 - e23 * e31 * e42 + e21 * e33 * e42 + e22 * e31 * e43
        - e21 * e32 * e43)
        * det_i;

    let o12 = t12 * det_i;
    let o22 =
      (e13 * e34 * e41 - e14 * e33 * e41 + e14 * e31 * e43 - e11 * e34 * e43 - e13 * e31 * e44
        + e11 * e33 * e44)
        * det_i;
    let o32 =
      (e14 * e32 * e41 - e12 * e34 * e41 - e14 * e31 * e42 + e11 * e34 * e42 + e12 * e31 * e44
        - e11 * e32 * e44)
        * det_i;
    let o42 =
      (e12 * e33 * e41 - e13 * e32 * e41 + e13 * e31 * e42 - e11 * e33 * e42 - e12 * e31 * e43
        + e11 * e32 * e43)
        * det_i;

    let o13 = t13 * det_i;
    let o23 =
      (e14 * e23 * e41 - e13 * e24 * e41 - e14 * e21 * e43 + e11 * e24 * e43 + e13 * e21 * e44
        - e11 * e23 * e44)
        * det_i;
    let o33 =
      (e12 * e24 * e41 - e14 * e22 * e41 + e14 * e21 * e42 - e11 * e24 * e42 - e12 * e21 * e44
        + e11 * e22 * e44)
        * det_i;
    let o43 =
      (e13 * e22 * e41 - e12 * e23 * e41 - e13 * e21 * e42 + e11 * e23 * e42 + e12 * e21 * e43
        - e11 * e22 * e43)
        * det_i;

    let o14 = t14 * det_i;
    let o24 =
      (e13 * e24 * e31 - e14 * e23 * e31 + e14 * e21 * e33 - e11 * e24 * e33 - e13 * e21 * e34
        + e11 * e23 * e34)
        * det_i;
    let o34 =
      (e14 * e22 * e31 - e12 * e24 * e31 - e14 * e21 * e32 + e11 * e24 * e32 + e12 * e21 * e34
        - e11 * e22 * e34)
        * det_i;
    let o44 =
      (e12 * e23 * e31 - e13 * e22 * e31 + e13 * e21 * e32 - e11 * e23 * e32 - e12 * e21 * e33
        + e11 * e22 * e33)
        * det_i;
    Matrix([
      Vector([o11, o21, o31, o41]),
      Vector([o12, o22, o32, o42]),
      Vector([o13, o23, o33, o43]),
      Vector([o14, o24, o34, o44]),
    ])
  }
}

impl<T: Float, const M: usize, const N: usize> Index<usize> for Matrix<T, M, N>
where
  [T; M]: LengthAtMost32,
  [T; N]: LengthAtMost32,
  [Vector<T, M>; N]: LengthAtMost32,
{
  type Output = Vector<T, M>;
  fn index(&self, i: usize) -> &Self::Output { &self.0[i] }
}

impl<T: Float, const M: usize, const N: usize> IndexMut<usize> for Matrix<T, M, N>
where
  [T; M]: LengthAtMost32,
  [T; N]: LengthAtMost32,
  [Vector<T, M>; N]: LengthAtMost32,
{
  fn index_mut(&mut self, i: usize) -> &mut Self::Output { &mut self.0[i] }
}

macro_rules! def_op {
  ($ty: ty, $func: ident, $op: tt) => {
    impl<T: Float, const M: usize, const N: usize> $ty for Matrix<T, M, N>
    where
      [T; M]: LengthAtMost32,
      [T; N]: LengthAtMost32,
      [Vector<T, M>; N]: LengthAtMost32,
    {
      type Output = Self;
      fn $func(mut self, o: Self) -> Self {
        for x in 0..N {
          self.0[x] = self.0[x] $op o.0[x];
        }
        self
      }
    }
  };
}

def_op!(Add, add, +);
def_op!(Sub, sub, -);
def_op!(Mul, mul, *);
def_op!(Div, div, /);

macro_rules! def_scalar_op {
  ($ty: ty, $func: ident, $op: tt) => {
    impl<T: Float, const M: usize, const N: usize> $ty for Matrix<T, M, N>
    where
      [T; M]: LengthAtMost32,
      [T; N]: LengthAtMost32,
      [Vector<T, M>; N]: LengthAtMost32,
    {
      type Output = Self;
      fn $func(mut self, o: T) -> Self {
        for x in 0..N {
          self.0[x] = self.0[x] $op o;
        }
        self
      }
    }
  };
}

def_scalar_op!(Add<T>, add, +);
def_scalar_op!(Sub<T>, sub, -);
def_scalar_op!(Mul<T>, mul, *);
def_scalar_op!(Div<T>, div, /);

/*
// XXX Commented out not because it's broken but because I shifted it from the old matrix code
#[test]
fn test_lu_decomp() {
  let a: Matrix4<f32> = Matrix4([
    Vec4([3., -3., 6., -9.]),
    Vec4([-7., 5., 1., 0.]),
    Vec4([6., -4., 0., -5.]),
    Vec4([-9., 5., -5., 12.]),
  ]);
  let lup = a.lup();
  let (l, u, p) = lup;
  let out = p.t().matmul(&l.matmul(&u));
  for i in 0..Matrix4::<f32>::N {
    for j in 0..Matrix4::<f32>::N {
      assert!((a.0[i][j] - out.0[i][j]).abs() < f32::epsilon());
    }
  }
  let x = Vec4([3.0, 0.0, 1.2, 4.5]);
  let b = a.vecmul(&x);
  let x_p = Matrix4::solve(&lup, &b);
  assert!((x_p - x).sqr_magn() < 0.00001);
}
*/
macro_rules! elemwise_impl {
  ($func: ident, $call: path, $name: expr) => {
    #[doc="Element-wise "]
    #[doc=$name]
    #[doc="."]
    pub fn $func(&self) -> Self { self.apply_fn($call) }
  };
  ($func: ident, $call: path) => {
    elemwise_impl!($func, $call, stringify!($func));
  };
}

macro_rules! curried_elemwise_impl {
  ($func: ident, $call: path, $name: expr) => {
    #[doc="Element-wise "]
    #[doc=$name]
    #[doc="."]
    pub fn $func(&self, v: T) -> Self { self.apply_fn(|u| $call(u, v)) }
  };
  ($func: ident, $call: path) => {
    curried_elemwise_impl!($func, $call, stringify!($func));
  };
}
impl<T: Float, const M: usize, const N: usize> Matrix<T, M, N>
where
  [T; M]: LengthAtMost32,
  [T; N]: LengthAtMost32,
  [Vector<T, M>; N]: LengthAtMost32,
{
  // Trigonometric stuff
  elemwise_impl!(cos, T::cos);
  elemwise_impl!(sin, T::sin);
  elemwise_impl!(tan, T::tan);

  elemwise_impl!(acos, T::acos);
  elemwise_impl!(asin, T::asin);
  elemwise_impl!(atan, T::atan);

  elemwise_impl!(acosh, T::acosh);
  elemwise_impl!(asinh, T::asinh);
  elemwise_impl!(atanh, T::atanh);
  curried_elemwise_impl!(atan2, T::atan2);
  curried_elemwise_impl!(hypot, T::hypot);

  // Rounding stuff
  elemwise_impl!(ceil, T::ceil);
  elemwise_impl!(floor, T::floor);
  elemwise_impl!(round, T::round);

  // Decomposition stuff
  elemwise_impl!(fract, T::fract);
  elemwise_impl!(trunc, T::trunc);

  // Sign value stuff
  elemwise_impl!(abs, T::abs);
  curried_elemwise_impl!(abs_sub, T::abs_sub);
  elemwise_impl!(signum, T::signum);

  // Reciprocal
  elemwise_impl!(recip, T::recip);

  // Logarithmic stuff
  elemwise_impl!(log2, T::log2);
  elemwise_impl!(log10, T::log10);
  elemwise_impl!(ln, T::ln);
  elemwise_impl!(ln_1p, T::ln_1p);
  elemwise_impl!(exp, T::exp);
  elemwise_impl!(exp2, T::exp2);
  elemwise_impl!(exp_m1, T::exp_m1);
  elemwise_impl!(sqrt, T::sqrt);
  elemwise_impl!(cbrt, T::cbrt);
  curried_elemwise_impl!(powf, T::powf);
  pub fn powi(&self, v: i32) -> Self { self.apply_fn(|u| u.powi(v)) }
  curried_elemwise_impl!(log, T::log);

  // Min/max stuff
  curried_elemwise_impl!(max, T::max);
  curried_elemwise_impl!(min, T::min);

  // Degree related stuff
  elemwise_impl!(to_degrees, T::to_degrees);
  elemwise_impl!(to_radians, T::to_radians);
}