# graphics3d/camera3d (vanilla.js 0.4.0)

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

3D camera. (holds a perspective or orthographic projection and the viewpoint, recomputes the view and projection matrices only when they change)

## Camera3D

3D camera. (holds a perspective or orthographic projection and the viewpoint, recomputes the view and projection matrices only when they change)
- Coordinates are right-handed with y up, same as the engine's Matrix4. The camera looks down -Z. (createLookAt, createPerspective)
- Perspective: setPerspective(field of view, near distance, far distance), orthographic: setOrthographic(visible height, near distance, far distance).
  The aspect ratio is given separately with setAspectRatio. (update it whenever the drawing rectangle changes, orthographic width is height x ratio)
- lookAt(eye, target, up) sets the viewpoint.
- getViewProjectionMatrix returns the cached matrix. It recomputes only on the first read after a function that changes values is called.
  Do not modify the returned matrix. (clone to modify)
- The renderer (ToonRenderer.beginFrameWithCamera) and the 2D display (projectToView) share the same camera, to put text or buttons over 3D points.
- projectToView(x, y, z, viewRect): a world point to a position in viewRect. viewRect is the rectangle the 3D is drawn in, given in the caller's coordinates (usually view coordinates).
- unprojectToPlane(viewPosition, planeHeight, viewRect): the point where the line of sight from a position in viewRect meets the horizontal plane at height planeHeight (y = planeHeight).
- Raw matrices: setMatrices(view, projection) uses the matrices the game computed as is. (oblique orthographic, a projection multiplied by a screen transform, and so on) All the functions above run on those matrices.
  The view matrix is given as a rigid world → camera transform (the camera looks down -Z). Eye, target (1 in front of the eye), up and isOrthographic are extracted from that matrix.
  Field of view, visible height, near distance, far distance and aspect ratio stay as last given. Calling setPerspective, setOrthographic or lookAt discards the raw matrices and returns to the computed path.
- View offset: setViewOffset(position, rotation) applies an offset in camera local axes last. (CameraShake shakes, head bob, recoil and the like, on both the computed path and raw matrices)
  The view matrix, the matrices after it, projectToView and unprojectToPlane run with the offset camera. getEyePosition, getTargetPosition and getUpDirection are the values before the offset.

Example: Map a world point to a screen position with a perspective camera

```js
import { Camera3D, Rect, Vector3 } from "./build/vanilla.js";

const camera = new Camera3D();
camera.setPerspective(Math.PI / 3, 0.1, 500);
camera.setAspectRatio(640 / 360);
const eyePosition = Vector3.create(0, 8, 12);
const targetPosition = Vector3.create(0, 0, 0);
camera.lookAt(eyePosition, targetPosition);
const viewRect = Rect.create(0, 0, 640, 360);
const screenPoint = camera.projectToView(0, 1, 0, viewRect);
console.log(screenPoint.x, screenPoint.y, screenPoint.isInFront);
const viewProjectionMatrix = camera.getViewProjectionMatrix();
const elements = viewProjectionMatrix.getElements();
console.log(elements.length);
```

- `constructor()` (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))
- `setPerspective(fieldOfViewRadian, nearDistance, farDistance)` (method, since 0.4.0): Sets a perspective projection.
  - `fieldOfViewRadian` number: Vertical field of view.
  - `nearDistance` number: Near distance. (world units)
  - `farDistance` number: Far distance. (world units)
- `setOrthographic(orthographicHeight, nearDistance, farDistance)` (method, since 0.4.0): Sets an orthographic projection. (visible height, width is height x aspect ratio)
  - `orthographicHeight` number: Visible height. (world units, width is height x aspect ratio)
  - `nearDistance` number: Near distance. (world units)
  - `farDistance` number: Far distance. (world units)
- `isOrthographic()` (method, since 0.4.0): Whether it is an orthographic projection.
  - returns boolean: True for orthographic projection.
- `setAspectRatio(aspectRatio)` (method, since 0.4.0): Sets the aspect ratio. (width / height, unchanged if the same)
  - `aspectRatio` number: Aspect ratio. (width / height, ignored when 0 or less or NaN)
- `getAspectRatio()` (method, since 0.4.0): Returns the aspect ratio.
  - returns number: Aspect ratio. (width / height)
- `getFieldOfView()` (method, since 0.4.0): Returns the vertical field of view of the perspective.
  - returns number: Vertical field of view of the perspective. (radians)
- `getOrthographicHeight()` (method, since 0.4.0): Returns the orthographic visible height.
  - returns number: Visible height of the orthographic projection. (world units)
- `getNearDistance()` (method, since 0.4.0): Returns the near distance.
  - returns number: Near distance. (world units)
- `getFarDistance()` (method, since 0.4.0): Returns the far distance.
  - returns number: Far distance. (world units)
- `lookAt(eyePosition, targetPosition, upDirection = Vector3.up())` (method, since 0.4.0): Sets the viewpoint. (copies the values)
  - `eyePosition` Vector3: World position of the eye.
  - `targetPosition` Vector3: World position being looked at.
  - `upDirection` Vector3: Default (0, 1, 0).
- `getEyePosition()` (method, since 0.4.0): Returns the eye position.
  - returns Vector3: World position of the eye. (the stored vector, do not modify)
- `getTargetPosition()` (method, since 0.4.0): Returns the target.
  - returns Vector3: World position being looked at. (the stored vector, do not modify)
- `getUpDirection()` (method, since 0.4.0): Returns the up direction.
  - returns Vector3: Up direction. (the stored vector, do not modify)
- `setMatrices(viewMatrix, projectionMatrix)` (method, since 0.4.0): Sets the raw matrices. (uses the view and projection the game computed as is, copies the values, header)
  - `viewMatrix` Matrix4: World → camera.
  - `projectionMatrix` Matrix4: Camera → clip.

  Example: Use an orthographic matrix computed by the game as is

  ```js
  import { Camera3D, Matrix4, Vector3 } from "./build/vanilla.js";
  
  const eyePosition = Vector3.create(10, 10, 10);
  const targetPosition = Vector3.create(0, 0, 0);
  const upDirection = Vector3.up();
  const viewMatrix = Matrix4.createLookAt(eyePosition, targetPosition, upDirection);
  const projectionMatrix = Matrix4.createOrthographic(-8, 8, -4.5, 4.5, 0.1, 100);
  const camera = new Camera3D();
  camera.setMatrices(viewMatrix, projectionMatrix);
  const recoveredEyePosition = camera.getEyePosition();
  const isOrthographic = camera.isOrthographic();
  console.log(isOrthographic, recoveredEyePosition.x, recoveredEyePosition.y, recoveredEyePosition.z);
  camera.setPerspective(0.8, 0.1, 100);
  const hasRawMatrices = camera.hasRawMatrices();
  console.log(hasRawMatrices);
  ```

- `hasRawMatrices()` (method, since 0.4.0): Whether raw matrices are used.
  - returns boolean: True when the raw matrices given to setMatrices are in use.
- `clearRawMatrices()` (method, since 0.4.0): Discards the raw matrices. (back to the computed path)
- `setViewOffset(position, rotation = Vector3.zero())` (method, since 0.4.0): Sets the view offset. (applies position and rotation in camera local axes last to the view matrix, copies the values, 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, zero vector by default)

  Example: Applying a camera shake and removing it again

  ```js
  import { Camera3D, CameraShake, Vector3 } from "./vanilla.js";
  const camera = new Camera3D();
  camera.lookAt(Vector3.create(0, 4, 10), Vector3.create(0, 0, 0));
  const cameraShake = new CameraShake();
  cameraShake.add({ amplitude: 0.1, rotationAmplitude: 0.02, duration: 0.3 });
  cameraShake.update(1 / 60);
  const shake = cameraShake.read();
  camera.setViewOffset(shake.position, shake.rotation);
  const shakenViewMatrix = camera.getViewMatrix().clone();
  camera.setViewOffset(Vector3.zero(), Vector3.zero());
  console.log(shakenViewMatrix.getElements()[12], camera.getViewMatrix().getElements()[12]);
  ```

- `getViewMatrix()` (method, since 0.4.0): Returns the view matrix. (world → camera)
  - returns Matrix4: View matrix. (the stored matrix, clone it to modify)
- `getProjectionMatrix()` (method, since 0.4.0): Returns the projection matrix. (camera → clip)
  - returns Matrix4: Projection matrix. (the stored matrix, clone it to modify)
- `getViewProjectionMatrix()` (method, since 0.4.0): Returns the view-projection matrix. (world → clip)
  - returns Matrix4: Projection x view matrix. (the stored matrix, clone it to modify)
- `getInverseViewProjectionMatrix()` (method, since 0.4.0): Returns the inverse view-projection matrix. (clip → world)
  - returns Matrix4: Inverse of the view and projection. (the stored matrix, clone it to modify)
- `readViewDepth(x, y, z)` (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` number: World X.
  - `y` number: World Y.
  - `z` number: World Z.
  - returns number: Depth measured along the camera's view direction. (world units, negative behind the eye plane)
- `projectToView(x, y, z, viewRect, result = { x: 0, y: 0, depth: 0, isInFront: false })` (method, since 0.4.0): A world point to a position in viewRect. (viewRect coordinates, origin at top-left, increasing downward)
  - isInFront is whether the point is in front of the eye plane. If behind, x and y are 0. Whether it is off-screen is decided by the caller from x, y.
  - If result is given, it is filled and returned. (so a new object is not created every frame)
  - `x` number: World X.
  - `y` number: World Y.
  - `z` number: World Z.
  - `viewRect` Rect: Rectangle where 3D is drawn. (in the caller's coordinates, usually view coordinates)
  - `result` object: { x, y, depth, isInFront }
  - returns object: { x, y, depth, isInFront }

  Example: Project several points while reusing the result object

  ```js
  import { Camera3D, Rect } from "./build/vanilla.js";
  
  const camera = new Camera3D();
  const viewRect = Rect.create(0, 0, 640, 360);
  const projected = { x: 0, y: 0, depth: 0, isInFront: false };
  const pointList = [[0, 0, 0], [2, 1, 0], [0, 0, 20]];
  for (const point of pointList) {
  	camera.projectToView(point[0], point[1], point[2], viewRect, projected);
  	console.log(projected.x, projected.y, projected.depth, projected.isInFront);
  }
  ```

- `unprojectToPlane(viewPosition, planeHeight, viewRect)` (method, since 0.4.0): The point where the line of sight from a position in viewRect meets the horizontal plane y = planeHeight. (null if parallel or meeting behind the eye)
  - `viewPosition` Vector2: Same coordinates as viewRect.
  - `planeHeight` number: Height of the horizontal plane. (world y)
  - `viewRect` Rect: Rectangle where 3D is drawn. (same coordinates as viewPosition)
  - returns Vector3 | null: World point where the ray meets the horizontal plane. (null when parallel, when it meets behind the eye, or when the viewRect size is 0 or less)

  Example: Find the ground position under the screen center

  ```js
  import { Camera3D, Rect, Vector2, Vector3 } from "./build/vanilla.js";
  
  const camera = new Camera3D();
  camera.setAspectRatio(640 / 360);
  const eyePosition = Vector3.create(0, 10, 10);
  const targetPosition = Vector3.create(0, 0, 0);
  camera.lookAt(eyePosition, targetPosition);
  const viewRect = Rect.create(0, 0, 640, 360);
  const viewPosition = Vector2.create(320, 180);
  const groundPoint = camera.unprojectToPlane(viewPosition, 0, viewRect);
  if (groundPoint !== null) {
  	console.log(groundPoint.x, groundPoint.y, groundPoint.z);
  }
  ```

