# base/matrix4 (vanilla-engine 0.4.0)

> https://vanillapunch.com/docs/vanilla-engine/0.4.0/api/base/matrix4/

4x4 transform matrix. (the original base/matrix4.js)
- Column-major as in the original. Element positions are elements[column * 4 + row], uploaded as is to glUniformMatrix4fv without transposing.
- Point transformation is transformed = matrix x (x, y, z, 1). (column vector multiplied on the right)
- multiply / translate / rotate_x ... / scale change the matrix itself as in the original. (this = this x other, right multiplication in local space)
  The create... static functions return a new matrix as in the original.
- The coordinate system is right-handed as in the original. create_perspective is OpenGL style (the camera looks down -Z, depth -1 ~ 1),
  create_look_at is a view matrix whose +Z (back axis) points away from the target as seen from the eye, rotations are in radians, and counterclockwise when looking down the axis is positive.
- The original getElements() hands out a Float32Array and the caller edits it directly. The Rust version makes elements a public field;
  get_elements() gives a read reference, and write_to_array / write_to_slice copy into uniform arrays.
- Like the original, elements are stored in f32 like a Float32Array, and math is done per element in f64 and then stored as f32. (the same bits as the original; read them as f64 with read_elements when computing)
- The original transformPoint's { x, y, z, w } is returned as TransformedPoint, and transform_direction's { x, y, z } as Vector3.
- The original clone is replaced by Copy. A transpose, which the original does not have, was not added.

## TransformedPoint (struct) (Clone, Copy, Debug, Default, PartialEq)

Homogeneous coordinate point. (the { x, y, z, w } the original transformPoint returns; the caller does the perspective divide)

Example: Compute depth after perspective projection

```rust
use vanilla::{math, Matrix4};

let projection = Matrix4::create_perspective(math::PI * 0.5, 2.0, 1.0, 3.0);
let clip_point = projection.transform_point(0.0, 0.0, -3.0);
assert_eq!(clip_point.w, 3.0);
assert_eq!(clip_point.z / clip_point.w, 1.0);
```

- `pub x: f64` (field, since 0.3.2): Transformed x. (before the perspective divide)
  - returns f64
- `pub y: f64` (field, since 0.3.2): Transformed y. (before the perspective divide)
  - returns f64
- `pub z: f64` (field, since 0.3.2): Transformed z. (before the perspective divide)
  - returns f64
- `pub w: f64` (field, since 0.3.2): Homogeneous coordinate w. (used for the perspective divide, 1 for affine transforms)
  - returns f64

## Matrix4 (struct) (Clone, Copy, Debug, PartialEq, Default)

4x4 transform matrix. (column-major, right-handed coordinate system, defaults to the identity matrix)
- Accumulating functions like translate, rotate_x and scale change the matrix itself, and create_... functions return a new matrix.

Example: Move a point with a model matrix and bring it back with the inverse

```rust
use vanilla::{Matrix4, Vector3};

let mut model = Matrix4::create_translation(1.0, 2.0, 3.0);
model.scale(2.0, 2.0, 2.0);
let point = model.transform_point(1.0, 1.0, 1.0);
assert_eq!((point.x, point.y, point.z, point.w), (3.0, 4.0, 5.0, 1.0));

let inverse = Matrix4::create_inverse(&model);
let back = inverse.transform_point(point.x, point.y, point.z);
assert_eq!((back.x, back.y, back.z), (1.0, 1.0, 1.0));

let view = Matrix4::create_look_at(Vector3::create(0.0, 0.0, 5.0), Vector3::zero(), Vector3::up());
assert_eq!(view, Matrix4::create_translation(0.0, 0.0, -5.0));
```

- `pub elements: [f32; 16]` (field, since 0.3.2): Column-major element array. (elements[column * 4 + row])
  - returns [f32; 16]
- `pub fn set_identity(&mut self)` (method, since 0.3.2): Resets to the identity matrix.
- `pub fn copy_from(&mut self, other: &Matrix4)` (method, since 0.3.2): Copies from another matrix.
  - `other` &Matrix4: Matrix to copy from.
- `pub fn multiply(&mut self, other: &Matrix4)` (method, since 0.3.2): Accumulates by multiplying another matrix on the right. (this = this x other)
  - `other` &Matrix4: Matrix to multiply on the right. (the other transform applies to points first)

  Example: For translate x scale, the scale applies first

  ```rust
  use vanilla::Matrix4;
  
  let mut matrix = Matrix4::create_translation(1.0, 2.0, 3.0);
  matrix.multiply(&Matrix4::create_scale(2.0, 2.0, 2.0));
  let point = matrix.transform_point(1.0, 0.0, 0.0);
  assert_eq!((point.x, point.y, point.z), (3.0, 2.0, 3.0));
  ```

- `pub fn translate(&mut self, x: f64, y: f64, z: f64)` (method, since 0.3.2): Accumulates a translation. (right multiplication in local space)
  - `x` f64: x translation.
  - `y` f64: y translation.
  - `z` f64: z translation.
- `pub fn rotate_x(&mut self, radian: f64)` (method, since 0.3.2): Accumulates an X axis rotation. (radians, right multiplication in local space)
  - `radian` f64: Rotation angle. (radians, positive turns +Y toward +Z)
- `pub fn rotate_y(&mut self, radian: f64)` (method, since 0.3.2): Accumulates a Y axis rotation. (radians, right multiplication in local space)
  - `radian` f64: Rotation angle. (radians, positive turns +Z toward +X)
- `pub fn rotate_z(&mut self, radian: f64)` (method, since 0.3.2): Accumulates a Z axis rotation. (radians, right multiplication in local space)
  - `radian` f64: Rotation angle. (radians, positive turns +X toward +Y)
- `pub fn scale(&mut self, x: f64, y: f64, z: f64)` (method, since 0.3.2): Accumulates a scale. (right multiplication in local space)
  - `x` f64: x scale. (1 leaves it unchanged)
  - `y` f64: y scale.
  - `z` f64: z scale.
- `pub fn transform_point(&self, x: f64, y: f64, z: f64) -> TransformedPoint` (method, since 0.3.2): Transforms a point. (returns up to the w component; the caller does the perspective divide)
  - `x` f64: x of the point.
  - `y` f64: y of the point.
  - `z` f64: z of the point.
  - returns TransformedPoint: Homogeneous coordinates of matrix x (x, y, z, 1). (not divided by w)
- `pub fn transform_direction(&self, x: f64, y: f64, z: f64) -> Vector3` (method, since 0.3.2): Transforms a direction. (applies only rotation and scale, without the translation part)
  - `x` f64: x of the direction.
  - `y` f64: y of the direction.
  - `z` f64: z of the direction.
  - returns Vector3: The transformed direction. (the length is not renormalized)

  Example: Translation does not apply to directions

  ```rust
  use vanilla::{Matrix4, Vector3};
  
  let mut matrix = Matrix4::create_translation(10.0, 0.0, 0.0);
  matrix.scale(2.0, 2.0, 2.0);
  assert_eq!(matrix.transform_direction(0.0, 1.0, 0.0), Vector3::create(0.0, 2.0, 0.0));
  ```

- `pub fn read_elements(&self) -> [f64; 16]` (method, since 0.4.0): Column-major elements read as numbers (f64). (the same as reading a Float32Array element in the original, which gives a JavaScript number; math uses this)
  - returns [f64; 16]: The 16 column-major elements widened to f64. (each keeps its f32 value)

  Example: Reading the translation elements of a translation matrix

  ```rust
  use vanilla::Matrix4;
  
  let matrix = Matrix4::create_translation(1.5, 2.0, 0.1);
  let elements = matrix.read_elements();
  assert_eq!(elements[12], 1.5);
  assert_eq!(elements[14], 0.1f32 as f64);
  ```

- `pub fn get_elements(&self) -> &[f32; 16]` (method, since 0.3.2): Returns the column-major element array. (to edit, use the elements field directly)
  - returns &[f32; 16]: Read reference to the 16 column-major elements.
- `pub fn write_to_array(&self, array: &mut [f32; 16])` (method, since 0.3.2): Writes to a shader mat4 (column-major) array.
  - `array` &mut [f32; 16]: Array to copy into. (16 column-major values)
- `pub fn write_to_slice(&self, array: &mut [f32], offset: usize)` (method, since 0.3.2): Writes 16 values starting at offset in a large array. (in place of the original jointMatrixArray.set(elements, joint_index * 16))
  - `array` &mut [f32]: Large array to copy into. (panics if shorter than offset + 16)
  - `offset` usize: Position to start writing. (element index, such as joint index x 16)

  Example: Write into the second slot of a joint matrix array

  ```rust
  use vanilla::Matrix4;
  
  let joint_matrix = Matrix4::create_translation(7.0, 8.0, 9.0);
  let mut joint_matrix_array = vec![0.0f32; 32];
  joint_matrix.write_to_slice(&mut joint_matrix_array, 16);
  assert_eq!(&joint_matrix_array[16..32], &joint_matrix.elements[..]);
  assert_eq!(joint_matrix_array[0], 0.0);
  ```

- `pub const fn create_identity() -> Matrix4` (static, since 0.3.2): Creates an identity matrix.
  - returns Matrix4: Identity matrix.
- `pub fn create_translation(x: f64, y: f64, z: f64) -> Matrix4` (static, since 0.3.2): Creates a translation matrix.
  - `x` f64: x translation.
  - `y` f64: y translation.
  - `z` f64: z translation.
  - returns Matrix4: Translation matrix. (x, y, z in elements 12, 13, 14)
- `pub fn create_rotation_x(radian: f64) -> Matrix4` (static, since 0.3.2): Creates an X axis rotation matrix. (radians)
  - `radian` f64: Rotation angle. (radians, positive turns +Y toward +Z)
  - returns Matrix4: X axis rotation matrix.
- `pub fn create_rotation_y(radian: f64) -> Matrix4` (static, since 0.3.2): Creates a Y axis rotation matrix. (radians)
  - `radian` f64: Rotation angle. (radians, positive turns +Z toward +X)
  - returns Matrix4: Y axis rotation matrix.
- `pub fn create_rotation_z(radian: f64) -> Matrix4` (static, since 0.3.2): Creates a Z axis rotation matrix. (radians)
  - `radian` f64: Rotation angle. (radians, positive turns +X toward +Y)
  - returns Matrix4: Z axis rotation matrix.

  Example: Rotating 90 degrees moves +X to +Y

  ```rust
  use vanilla::{math, Matrix4};
  
  let rotation = Matrix4::create_rotation_z(math::degree_to_radian(90.0));
  let rotated = rotation.transform_direction(1.0, 0.0, 0.0);
  assert!(rotated.x.abs() < 1e-6);
  assert!((rotated.y - 1.0).abs() < 1e-6);
  ```

- `pub fn create_rotation_from_quaternion(quaternion: Quaternion) -> Matrix4` (static, since 0.3.2): Creates a quaternion rotation matrix. (assumes a unit quaternion)
  - `quaternion` Quaternion: Rotation quaternion. (normalized to length 1)
  - returns Matrix4: Rotation matrix. (translation part is 0)

  Example: A Z axis Euler quaternion equals the Z axis rotation matrix

  ```rust
  use vanilla::{Matrix4, Quaternion};
  
  let quaternion = Quaternion::create_from_euler(0.0, 0.0, 0.5);
  let from_quaternion = Matrix4::create_rotation_from_quaternion(quaternion);
  let from_angle = Matrix4::create_rotation_z(0.5);
  for index in 0..16 {
  	assert!((from_quaternion.elements[index] - from_angle.elements[index]).abs() < 1e-5);
  }
  ```

- `pub fn create_scale(x: f64, y: f64, z: f64) -> Matrix4` (static, since 0.3.2): Creates a scale matrix.
  - `x` f64: x scale.
  - `y` f64: y scale.
  - `z` f64: z scale.
  - returns Matrix4: Scale matrix.
- `pub fn create_perspective(field_of_view_radian: f64, aspect_ratio: f64, near_distance: f64, far_distance: f64) -> Matrix4` (static, since 0.3.2): Creates a perspective projection matrix. (vertical field of view in radians, OpenGL style depth -1 ~ 1)
  - `field_of_view_radian` f64: Vertical field of view. (radians)
  - `aspect_ratio` f64: Width divided by height ratio.
  - `near_distance` f64: Distance from the camera to the near plane. (the camera looks down -Z)
  - `far_distance` f64: Distance from the camera to the far plane.
  - returns Matrix4: Perspective projection matrix. (the near plane goes to depth -1, the far plane to depth 1)

  Example: A point on the near plane has depth -1

  ```rust
  use vanilla::{math, Matrix4};
  
  let projection = Matrix4::create_perspective(math::degree_to_radian(90.0), 2.0, 1.0, 3.0);
  let near_point = projection.transform_point(0.0, 0.0, -1.0);
  assert_eq!(near_point.z / near_point.w, -1.0);
  ```

- `pub fn create_orthographic(left: f64, right: f64, bottom: f64, top: f64, near_distance: f64, far_distance: f64) -> Matrix4` (static, since 0.3.2): Creates an orthographic projection matrix. (the same formula as OpenGL glOrtho)
  - `left` f64: x of the left plane.
  - `right` f64: x of the right plane.
  - `bottom` f64: y of the bottom plane.
  - `top` f64: y of the top plane.
  - `near_distance` f64: Distance from the camera to the near plane. (the camera looks down -Z)
  - `far_distance` f64: Distance from the camera to the far plane.
  - returns Matrix4: Orthographic projection matrix. (maps the inside of the box to -1 ~ 1)

  Example: The box corner goes to (1, 1, 1)

  ```rust
  use vanilla::Matrix4;
  
  let projection = Matrix4::create_orthographic(0.0, 4.0, 0.0, 2.0, 1.0, 5.0);
  let corner = projection.transform_point(4.0, 2.0, -5.0);
  assert_eq!((corner.x, corner.y, corner.z, corner.w), (1.0, 1.0, 1.0, 1.0));
  ```

- `pub fn create_look_at(eye_position: Vector3, target_position: Vector3, up_direction: Vector3) -> Matrix4` (static, since 0.3.2): Creates a view matrix. (a view matrix looking from eye_position at target_position, back axis = eye - target)
  - `eye_position` Vector3: Eye (camera) position.
  - `target_position` Vector3: Point to look at. (the matrix becomes unusable if it equals eye_position)
  - `up_direction` Vector3: Up direction. (usually Vector3::up(); if parallel to the line of sight, the right axis becomes (0, 0, 0) and the matrix is unusable)
  - returns Matrix4: Matrix that converts world coordinates to view coordinates. (the target lies toward -Z)

  Example: Look at the origin from (0, 0, 5)

  ```rust
  use vanilla::{Matrix4, Vector3};
  
  let view = Matrix4::create_look_at(Vector3::create(0.0, 0.0, 5.0), Vector3::zero(), Vector3::up());
  let target_in_view = view.transform_point(0.0, 0.0, 0.0);
  assert_eq!((target_in_view.x, target_in_view.y, target_in_view.z), (0.0, 0.0, -5.0));
  ```

- `pub fn create_inverse(matrix: &Matrix4) -> Matrix4` (static, since 0.3.2): Creates an inverse matrix. (general 4x4 cofactor expansion, the identity matrix if the determinant is 0)
  - `matrix` &Matrix4: Matrix to invert.
  - returns Matrix4: The inverse matrix. The identity matrix if the determinant is 0.

  Example: Undoing, and a matrix that cannot be inverted

  ```rust
  use vanilla::Matrix4;
  
  let mut matrix = Matrix4::create_translation(1.0, 2.0, 3.0);
  matrix.scale(2.0, 4.0, 8.0);
  let inverse = Matrix4::create_inverse(&matrix);
  let point = inverse.transform_point(1.0, 2.0, 3.0);
  assert_eq!((point.x, point.y, point.z), (0.0, 0.0, 0.0));
  
  let singular = Matrix4 { elements: [0.0; 16] };
  assert_eq!(Matrix4::create_inverse(&singular), Matrix4::create_identity());
  ```

