tmatrix4.nim 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. import math
  2. type
  3. TMatrix*[T; R, C: static[int]] = array[R, array[C, T]] ## Row major matrix type.
  4. TMat4* = TMatrix[float32, 4, 4]
  5. TVector*[T; C: static[int]] = array[C, T]
  6. TVec4* = TVector[float32, 4]
  7. template row*[T; R, C: static[int]](m: TMatrix[T, R, C], rowidx: range[0..R-1]): TVector[T, R] =
  8. m[rowidx]
  9. proc col*[T; R, C: static[int]](m: TMatrix[T, R, C], colidx: range[0..C-1]): TVector[T, C] {.noSideEffect.} =
  10. for i in low(m)..high(m):
  11. result[i] = m[i][colidx]
  12. proc dot(lhs, rhs: TVector): float32 =
  13. for i in low(rhs)..high(rhs):
  14. result += lhs[i] * rhs[i]
  15. proc `*`*[T; R, N, C: static[int]](a: TMatrix[T, R, N], b: TMatrix[T, N, C]): TMatrix[T, R, C] {.noSideEffect.} =
  16. for i in low(a)..high(a):
  17. for j in low(a[i])..high(a[i]):
  18. result[i][j] = dot(a.row(i), b.col(j))
  19. proc translate*(v: TVec4): TMat4 {.noSideEffect.} =
  20. result = [[1f32, 0f32, 0f32, 0f32],
  21. [0f32, 1f32, 0f32, 0f32],
  22. [0f32, 0f32, 1f32, 0f32],
  23. [v[0], v[1], v[2], 1f32]]
  24. proc rotatex*(angle: float): TMat4 =
  25. result = [[1f32, 0f32, 0f32, 0f32],
  26. [0f32, cos(angle).float32, sin(angle).float32, 0f32],
  27. [0f32, -sin(angle).float32, cos(angle).float32, 0f32],
  28. [0f32, 0f32, 0f32, 1f32]]
  29. proc orbitxAround(point: TVec4, angle: float): TMat4 =
  30. result = translate(point)*rotatex(angle)*translate(point)