# graphics3d/camera3d (vanilla-engine 0.4.0)

> https://vanillapunch.com/docs/vanilla-engine/0.4.0/api/graphics3d/camera3d/

3D camera. (Camera3D of vanilla.js graphics3d/camera3d.js)
- Holds a perspective or orthographic projection and the view position, and recomputes the view and projection matrices only when they change.
- Coordinates are right-handed with y up, the same as the engine Matrix4. The camera looks toward -Z. (create_look_at, create_perspective)
- Perspective: set_perspective(field of view, near distance, far distance), orthographic: set_orthographic(visible height, near distance, far distance).
  The aspect ratio is given separately with set_aspect_ratio. (update it whenever the drawing rectangle changes, the orthographic width is height x ratio)
- Matrices are kept in Cell and recomputed when read through &self if a value changed. (the original getters check #isMatrixDirty and compute)
- The renderer (ToonRenderer::begin_frame_with_camera) and 2D display (project_to_view) share the same camera to place text or buttons over 3D points.
- project_to_view(x, y, z, view_rect): a world point to a position inside view_rect. view_rect is the rectangle where 3D is drawn, given in the caller's coordinates (usually view coordinates).
  The original { x, y, depth, isInFront } is returned as ProjectedPoint.
- unproject_to_plane(view_position, plane_height, view_rect): the point where the line of sight from a position inside view_rect meets the horizontal plane (y = plane_height). None if there is none.
- Raw matrices: set_matrices(view, projection) uses matrices computed by the game as is. (such as a tilted orthographic, or a projection multiplied by a screen transform) All the functions above then work with those matrices.
  The view matrix is given as a rigid transform from world to camera (the camera looks toward -Z). The eye, target (1 in front of the eye), up and is_orthographic are extracted from that matrix.
  The field of view, visible height, near distance, far distance and aspect ratio stay as last given. Calling set_perspective, set_orthographic or look_at drops the raw matrices and returns to the computed path.
- View offset: set_view_offset(position, rotation) applies an offset in camera local axes last. (such as CameraShake shakes, walk bobbing and recoil, on both the computed path and raw matrices)
  The view matrix and the matrices after it, project_to_view and unproject_to_plane run with the offset camera. get_eye_position, get_target_position and get_up_direction are the values before the offset.

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

Projected point. (view_rect coordinates, depth in front of the camera, whether it is in front of the eye plane, x and y are 0 when not in front)

Example: A point behind the eye has is_in_front false and position 0

```rust
use vanilla::{Camera3D, ProjectedPoint, Rect};

let camera = Camera3D::new();
let view_rect = Rect::create(0.0, 0.0, 640.0, 480.0);
let behind_point: ProjectedPoint = camera.project_to_view(0.0, 0.0, 20.0, view_rect);
assert!(!behind_point.is_in_front);
assert_eq!((behind_point.x, behind_point.y), (0.0, 0.0));
assert!((behind_point.depth + 10.0).abs() < 0.001);
```

- `pub x: f64` (field, since 0.4.0): Horizontal position in view_rect coordinates. (0 when not in front)
  - returns f64
- `pub y: f64` (field, since 0.4.0): Vertical position in view_rect coordinates. (0 at the top, increasing downward, 0 when not in front)
  - returns f64
- `pub depth: f64` (field, since 0.4.0): Depth in front of the camera. (distance measured along the view direction, negative if behind the eye plane, same as read_view_depth)
  - returns f64
- `pub is_in_front: bool` (field, since 0.4.0): Whether it is in front of the eye plane. (true if the depth is 0.0001 or more and clip w is not 0)
  - returns bool

## Camera3D (struct) (Clone, Debug, Default)

3D camera. (perspective or orthographic projection and view position, the view and projection matrices are recomputed on the first read after a change)
- The default is a perspective field of view of 0.8 radians, aspect ratio 1, distance 0.1 ~ 1000, looking at the origin from eye (0, 0, 10).

Example: Project the origin into the view rectangle with a perspective camera, and bring that position back to the floor

```rust
use vanilla::{Camera3D, Rect, Vector2, Vector3};

let mut camera = Camera3D::new();
camera.set_perspective(0.8, 0.1, 100.0);
camera.set_aspect_ratio(2.0);
camera.look_at(Vector3::create(0.0, 5.0, 10.0), Vector3::zero(), Vector3::up());

let view_rect = Rect::create(0.0, 0.0, 400.0, 200.0);
let projected_point = camera.project_to_view(0.0, 0.0, 0.0, view_rect);
assert!(projected_point.is_in_front);
assert!((projected_point.x - 200.0).abs() < 0.01);
assert!((projected_point.y - 100.0).abs() < 0.01);

let ground_point = camera.unproject_to_plane(Vector2::create(projected_point.x, projected_point.y), 0.0, view_rect).unwrap();
assert!(ground_point.x.abs() < 0.01);
assert!(ground_point.z.abs() < 0.01);
```

- `pub fn new() -> Camera3D` (constructor, since 0.4.0): Constructor. (perspective field of view 0.8 radians, ratio 1, distance 0.1 ~ 1000, looking at the origin from eye (0, 0, 10))
  - returns Camera3D: A new camera with a perspective field of view of 0.8 radians, aspect ratio 1, distance 0.1 ~ 1000, looking at the origin from eye (0, 0, 10) (up (0, 1, 0)).
- `pub fn set_perspective(&mut self, field_of_view_radian: f64, near_distance: f64, far_distance: f64)` (method, since 0.4.0): Sets a perspective projection. (vertical field of view)
  - If there are raw matrices given with set_matrices, they are dropped and it returns to the computed path.
  - `field_of_view_radian` f64: Vertical field of view. (radians)
  - `near_distance` f64: Near distance. (in front of the camera, world units)
  - `far_distance` f64: Far distance. (world units)
- `pub fn set_orthographic(&mut self, orthographic_height: f64, near_distance: f64, far_distance: f64)` (method, since 0.4.0): Sets an orthographic projection. (visible height, the width is height x aspect ratio)
  - If there are raw matrices given with set_matrices, they are dropped and it returns to the computed path.
  - `orthographic_height` f64: Visible height. (world units, half above and half below the center)
  - `near_distance` f64: Near distance. (in front of the camera, world units)
  - `far_distance` f64: Far distance. (world units)

  Example: With height 10 and ratio 2, a width of 20 is visible and (10, 5) goes to the top-right corner

  ```rust
  use vanilla::{Camera3D, Rect, Vector3};
  
  let mut camera = Camera3D::new();
  camera.set_orthographic(10.0, 0.1, 100.0);
  camera.set_aspect_ratio(2.0);
  camera.look_at(Vector3::create(0.0, 0.0, 10.0), Vector3::zero(), Vector3::up());
  assert!(camera.is_orthographic());
  
  let projected_point = camera.project_to_view(10.0, 5.0, 0.0, Rect::create(0.0, 0.0, 200.0, 100.0));
  assert!((projected_point.x - 200.0).abs() < 0.01);
  assert!(projected_point.y.abs() < 0.01);
  ```

- `pub fn is_orthographic(&self) -> bool` (method, since 0.4.0): Whether it is an orthographic projection.
  - returns bool: true for an orthographic projection. (with raw matrices, the value detected from the projection matrix)
- `pub fn set_aspect_ratio(&mut self, aspect_ratio: f64)` (method, since 0.4.0): Sets the aspect ratio. (width / height, unchanged if 0 or less or the same)
  - `aspect_ratio` f64: Aspect ratio. (width / height, NaN or 0 or less is ignored)
- `pub fn get_aspect_ratio(&self) -> f64` (method, since 0.4.0): Returns the aspect ratio.
  - returns f64: Aspect ratio. (width / height, default 1)
- `pub fn get_field_of_view(&self) -> f64` (method, since 0.4.0): Returns the vertical field of view of the perspective.
  - returns f64: Vertical field of view. (radians, default 0.8, the last given value even when raw matrices are used)
- `pub fn get_orthographic_height(&self) -> f64` (method, since 0.4.0): Returns the orthographic visible height.
  - returns f64: Visible height. (world units, default 10)
- `pub fn get_near_distance(&self) -> f64` (method, since 0.4.0): Returns the near distance.
  - returns f64: Near distance. (world units, default 0.1)
- `pub fn get_far_distance(&self) -> f64` (method, since 0.4.0): Returns the far distance.
  - returns f64: Far distance. (world units, default 1000)
- `pub fn look_at(&mut self, eye_position: Vector3, target_position: Vector3, up_direction: Vector3)` (method, since 0.4.0): Sets the view position.
  - If there are raw matrices given with set_matrices, they are dropped and it returns to the computed path.
  - `eye_position` Vector3: Eye position. (world)
  - `target_position` Vector3: Target. (world)
  - `up_direction` Vector3: Up direction. (usually Vector3::up())
- `pub fn get_eye_position(&self) -> Vector3` (method, since 0.4.0): Returns the eye position.
  - returns Vector3: Eye position. (world, with raw matrices the position extracted from the view matrix)
- `pub fn get_target_position(&self) -> Vector3` (method, since 0.4.0): Returns the target.
  - returns Vector3: Target. (world, with raw matrices the position 1 in front of the eye)
- `pub fn get_up_direction(&self) -> Vector3` (method, since 0.4.0): Returns the up direction.
  - returns Vector3: Up direction. (with raw matrices the up axis of the view matrix)
- `pub fn set_matrices(&mut self, view_matrix: &Matrix4, projection_matrix: &Matrix4)` (method, since 0.4.0): Sets the raw matrices. (uses the view and projection the game computed as is, see the header comment)
  - `view_matrix` &Matrix4: View matrix. (rigid transform from world to camera, the camera looks toward -Z)
  - `projection_matrix` &Matrix4: Projection matrix. (camera → clip, treated as orthographic when the absolute value of `elements[11]` is below 0.5)

  Example: Use a tilted orthographic projection as is, then return to the computed path with set_perspective

  ```rust
  use vanilla::{Camera3D, Matrix4, Vector3};
  
  let view_matrix = Matrix4::create_look_at(Vector3::create(0.0, 5.0, 10.0), Vector3::zero(), Vector3::up());
  let mut projection_matrix = Matrix4::create_orthographic(-4.0, 4.0, -2.0, 2.0, 0.1, 50.0);
  projection_matrix.elements[8] = 0.3;
  
  let mut camera = Camera3D::new();
  camera.set_matrices(&view_matrix, &projection_matrix);
  assert!(camera.has_raw_matrices());
  assert!(camera.is_orthographic());
  assert!((camera.get_eye_position().y - 5.0).abs() < 0.001);
  assert_eq!(camera.get_projection_matrix(), projection_matrix);
  
  camera.set_perspective(0.8, 0.1, 100.0);
  assert!(!camera.has_raw_matrices());
  assert!(!camera.is_orthographic());
  ```

- `pub fn has_raw_matrices(&self) -> bool` (method, since 0.4.0): Whether raw matrices are used.
  - returns bool: true if the raw matrices given with set_matrices are in use.
- `pub fn clear_raw_matrices(&mut self)` (method, since 0.4.0): Discards the raw matrices. (back to the computed path)
- `pub fn set_view_offset(&mut self, position: Vector3, rotation: Vector3)` (method, since 0.4.0): Set the view offset. (applies position and rotation in camera local axes last to the view matrix, no offset when both are zero vectors)
  - `position` Vector3: Position offset in camera local axes. (scene length, x right, y up, z back)
  - `rotation` Vector3: Rotation offset in camera local axes. (radians, x pitch, y yaw, z roll, pass Vector3::zero() for the original default zero vector)

  Example: Apply a camera shake and remove it again

  ```rust
  use vanilla::{Camera3D, CameraShake, CameraShakeOptions, Vector3};
  
  let mut camera = Camera3D::new();
  camera.look_at(Vector3::create(0.0, 4.0, 10.0), Vector3::zero(), Vector3::up());
  let plain_view_matrix = camera.get_view_matrix();
  let mut camera_shake = CameraShake::default();
  camera_shake.add(CameraShakeOptions { amplitude: 0.1, rotation_amplitude: 0.02, duration: 0.3, ..Default::default() });
  camera_shake.update(1.0 / 60.0);
  let shake = camera_shake.read();
  camera.set_view_offset(shake.position, shake.rotation);
  let shaken_view_matrix = camera.get_view_matrix();
  camera.set_view_offset(Vector3::zero(), Vector3::zero());
  assert_ne!(shaken_view_matrix.get_elements()[12], plain_view_matrix.get_elements()[12]);
  assert_eq!(camera.get_view_matrix().get_elements(), plain_view_matrix.get_elements());
  ```

- `pub fn get_view_matrix(&self) -> Matrix4` (method, since 0.4.0): Returns the view matrix. (world → camera)
  - returns Matrix4: View matrix. (with raw matrices that matrix, otherwise computed from the eye, target and up)
- `pub fn get_projection_matrix(&self) -> Matrix4` (method, since 0.4.0): Returns the projection matrix. (camera → clip)
  - returns Matrix4: Projection matrix. (with raw matrices that matrix, otherwise computed as perspective or orthographic)
- `pub fn get_view_projection_matrix(&self) -> Matrix4` (method, since 0.4.0): Returns the view-projection matrix. (world → clip)
  - returns Matrix4: Projection x view matrix. (world points to clip coordinates)
- `pub fn get_inverse_view_projection_matrix(&self) -> Matrix4` (method, since 0.4.0): Returns the inverse view-projection matrix. (clip → world)
  - returns Matrix4: Inverse of the view and projection matrix. (clip coordinates to world)
- `pub fn read_view_depth(&self, x: f64, y: f64, z: f64) -> f64` (method, since 0.4.0): Depth of a world point in front of the camera. (distance measured along the view direction, negative if behind the eye plane, for drawing transparent things far to near)
  - `x` f64: x of the world point.
  - `y` f64: y of the world point.
  - `z` f64: z of the world point.
  - returns f64: Depth in front of the camera. (distance measured along the view direction, negative if behind the eye plane)

  Example: Sort transparent things by depth so the far ones are drawn first

  ```rust
  use vanilla::{Camera3D, Vector3};
  
  let camera = Camera3D::new();
  let mut position_list = vec![Vector3::create(0.0, 0.0, 5.0), Vector3::create(0.0, 0.0, -5.0), Vector3::zero()];
  position_list.sort_by(|left, right| camera.read_view_depth(right.x, right.y, right.z).total_cmp(&camera.read_view_depth(left.x, left.y, left.z)));
  assert_eq!(position_list[0], Vector3::create(0.0, 0.0, -5.0));
  assert!((camera.read_view_depth(0.0, 0.0, 0.0) - 10.0).abs() < 0.001);
  ```

- `pub fn project_to_view(&self, x: f64, y: f64, z: f64, view_rect: Rect) -> ProjectedPoint` (method, since 0.4.0): A world point to a position inside view_rect. (view_rect coordinates, origin at the top left and increasing downward, whether it is off-screen is up to the caller)
  - `x` f64: x of the world point.
  - `y` f64: y of the world point.
  - `z` f64: z of the world point.
  - `view_rect` Rect: Rectangle where 3D is drawn. (in the caller's coordinates, usually view coordinates)
  - returns ProjectedPoint: Position and depth inside view_rect. If the depth is below 0.0001 (behind the eye plane) or clip w is 0, is_in_front is false and x, y are 0.

  Example: Position for placing a name tag over the origin of 3D drawn in the right half of the screen

  ```rust
  use vanilla::{Camera3D, Rect};
  
  let camera = Camera3D::new();
  let view_rect = Rect::create(640.0, 0.0, 640.0, 720.0);
  let projected_point = camera.project_to_view(0.0, 0.0, 0.0, view_rect);
  if projected_point.is_in_front {
  	let label_x = projected_point.x;
  	let label_y = projected_point.y - 24.0;
  	assert!((label_x - 960.0).abs() < 0.01);
  	assert!((label_y - 336.0).abs() < 0.01);
  }
  ```

- `pub fn unproject_to_plane(&self, view_position: Vector2, plane_height: f64, view_rect: Rect) -> Option<Vector3>` (method, since 0.4.0): The point where the line of sight from a position inside view_rect meets the horizontal plane y = plane_height. (None if parallel or meeting behind the eye)
  - `view_position` Vector2: Position the line of sight starts from. (same coordinates as view_rect, such as a pressed position)
  - `plane_height` f64: Height of the horizontal plane. (world y)
  - `view_rect` Rect: Rectangle where 3D is drawn. (in the caller's coordinates, usually view coordinates)
  - returns Option<Vector3>: World point where the line of sight meets the horizontal plane. (y is plane_height) None if view_rect is empty, the w of the unprojection is 0, the line of sight is parallel to the plane, or they meet behind the eye.

  Example: With a camera looking forward, the bottom edge hits the floor and the top edge is sky, so None

  ```rust
  use vanilla::{Camera3D, Rect, Vector2, Vector3};
  
  let mut camera = Camera3D::new();
  camera.look_at(Vector3::create(0.0, 1.0, 0.0), Vector3::create(0.0, 1.0, -10.0), Vector3::up());
  let view_rect = Rect::create(0.0, 0.0, 400.0, 400.0);
  
  let ground_point = camera.unproject_to_plane(Vector2::create(200.0, 400.0), 0.0, view_rect).unwrap();
  assert_eq!(ground_point.y, 0.0);
  assert!(ground_point.z < 0.0);
  assert_eq!(camera.unproject_to_plane(Vector2::create(200.0, 0.0), 0.0, view_rect), None);
  ```

