# graphics3d/camerashake (vanilla-engine 0.4.0)

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

3D camera shake. (CameraShake and createOffsetViewMatrix of vanilla.js graphics3d/camerashake.js)
- An engine shake in the shape of Unity Cinemachine Impulse and Unreal Camera Shake. Each shake holds its own signal, strength, frequency, duration, attack and decay for 3 position axes and 3 rotation axes (pitch, yaw, roll).
- Signal: two sine waves with slightly different frequencies are layered per axis. Phases and frequency ratios are drawn from the shake's seed. (same seed and same age give the same values)
- Envelope: 0 while the age is negative (starts that much later), rises from 0 to 1 over attack seconds, and decays as (1 - age / duration) to the power decay_exponent, reaching 0 at the duration.
- Overlap: all live shakes are summed. (unlike the 2D Shaker, which follows the stronger one)
- Age: age in CameraShakeOptions is the seconds already passed. The signal is also computed from the age, so an event seen late added with that age continues with the same values as if added from the start.
- Where to apply: pass it to Camera3D::set_view_offset(position, rotation), or apply it with create_offset_view_matrix to a view matrix the game computed.
- The same seed as the original gives the same values. A shake without a seed uses the floor of the base SeededRandom's next value x 2^32 as its seed,
  and draws 12 wave values (two waves per each of six axes, frequency ratio then phase per wave) from that seed's SeededRandom in the same order as the original.
  The sine is the engine sine with the same bits as Chrome Math.sin (the correctly rounded sin in base).
- Differences from the original: the original constructor's { seed } is CameraShake::new(seed), and the options object of add is CameraShakeOptions (Default is the original defaults).
  The original read's { position, rotation } is CameraShakeOffset. The seed is u32 like the original SeededRandom.

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

Fields of one shake. (passed to CameraShake::add, the options of the original add, Default is the original defaults)

Example: A shake that moves less up and down and starts a little later

```rust
use vanilla::{CameraShake, CameraShakeOptions};

let mut camera_shake = CameraShake::new(1);
camera_shake.add(CameraShakeOptions { amplitude: 0.05, position_axes: [1.0, 0.3, 1.0], duration: 0.4, age: -0.1, ..Default::default() });
assert!(camera_shake.is_shaking());
assert_eq!(camera_shake.read().position.x, 0.0);
```

- `pub amplitude: f64` (field, since 0.4.0): Maximum length of the position shake. (scene length, default 0.1)
  - returns f64
- `pub rotation_amplitude: f64` (field, since 0.4.0): Maximum angle of the rotation shake. (radians, default 0)
  - returns f64
- `pub position_axes: [f64; 3]` (field, since 0.4.0): Share per position axis. ([x, y, z] camera local axes right, up, back, default [1, 1, 1])
  - returns [f64; 3]
- `pub rotation_axes: [f64; 3]` (field, since 0.4.0): Share per rotation axis. ([pitch, yaw, roll], default [1, 1, 1])
  - returns [f64; 3]
- `pub frequency: f64` (field, since 0.4.0): Frequency. (times per second, default 10)
  - returns f64
- `pub duration: f64` (field, since 0.4.0): Duration. (seconds, default 0.25)
  - returns f64
- `pub attack: f64` (field, since 0.4.0): Seconds to rise from 0 to full strength. (default 0)
  - returns f64
- `pub decay_exponent: f64` (field, since 0.4.0): Decay exponent. ((1 - age / duration) to this power, 1 is linear, 0 stays the same until the end, default 2)
  - returns f64
- `pub age: f64` (field, since 0.4.0): Seconds already passed. (default 0, negative starts that much later)
  - returns f64
- `pub seed: Option<u32>` (field, since 0.4.0): Seed of this shake. (None draws one in turn from the base seed)
  - returns Option<u32>

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

Current shake offset. (CameraShake::read, camera local axes, both zero vectors when there is no shake)

Example: Zero vectors when there is no shake

```rust
use vanilla::{CameraShake, CameraShakeOffset, Vector3};

let camera_shake = CameraShake::new(1);
let offset: CameraShakeOffset = camera_shake.read();
assert_eq!(offset.position, Vector3::zero());
assert_eq!(offset.rotation, Vector3::zero());
```

- `pub position: Vector3` (field, since 0.4.0): Position. (scene length, x right, y up, z back)
  - returns Vector3
- `pub rotation: Vector3` (field, since 0.4.0): Rotation. (radians, x pitch, y yaw, z roll)
  - returns Vector3

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

3D camera shake. (original CameraShake, adds shakes, ages them and reads the current offset in camera local axes)
- add adds one shake, update(seconds) ages them and removes finished shakes. read() gives the current offset.
- The default (Default) is base seed 1. (the original constructor default)

Example: Apply an explosion shake to Camera3D

```rust
use vanilla::{Camera3D, CameraShake, CameraShakeOptions, Vector3};

let mut camera = Camera3D::new();
camera.set_perspective(std::f64::consts::PI / 3.0, 0.1, 500.0);
camera.look_at(Vector3::create(0.0, 4.0, 10.0), Vector3::zero(), Vector3::up());
let mut camera_shake = CameraShake::new(7);
camera_shake.add(CameraShakeOptions { amplitude: 0.09, rotation_amplitude: 0.01, duration: 0.25, position_axes: [1.0, 0.5, 1.0], ..Default::default() });
camera_shake.add(CameraShakeOptions { amplitude: 0.04, duration: 0.6, age: 0.1, ..Default::default() });
camera_shake.update(1.0 / 60.0);
let shake = camera_shake.read();
camera.set_view_offset(shake.position, shake.rotation);
let view_projection_matrix = camera.get_view_projection_matrix();
assert!(camera_shake.is_shaking());
assert_eq!(view_projection_matrix.get_elements().len(), 16);
```

- `pub fn new(seed: u32) -> CameraShake` (constructor, since 0.4.0): Constructor.
  - `seed` u32: Base seed for drawing the seeds of shakes given without one. (original { seed } default 1, 0 becomes 1 like SeededRandom)
  - returns CameraShake: A new shake base with no shakes.

  Example: The same base seed gives the same values

  ```rust
  use vanilla::{CameraShake, CameraShakeOptions};
  
  let mut first = CameraShake::new(42);
  let mut second = CameraShake::new(42);
  first.add(CameraShakeOptions::default());
  second.add(CameraShakeOptions::default());
  first.update(0.05);
  second.update(0.05);
  assert_eq!(first.read(), second.read());
  ```

- `pub fn add(&mut self, options: CameraShakeOptions)` (method, since 0.4.0): Add a shake. (summed on top of the live shakes)
  - `options` CameraShakeOptions: Shake fields. (strength, rotation strength, axis shares, frequency, duration, attack, decay exponent, age, seed)

  Example: A shake that only rotates

  ```rust
  use vanilla::{CameraShake, CameraShakeOptions};
  
  let mut camera_shake = CameraShake::new(3);
  camera_shake.add(CameraShakeOptions { amplitude: 0.0, rotation_amplitude: 0.05, rotation_axes: [1.0, 1.0, 0.0], seed: Some(9), ..Default::default() });
  camera_shake.update(0.02);
  let offset = camera_shake.read();
  assert_eq!(offset.position.x, 0.0);
  assert_eq!(offset.rotation.z, 0.0);
  assert!(offset.rotation.x != 0.0);
  ```

- `pub fn update(&mut self, seconds: f64)` (method, since 0.4.0): Age the shakes. (removes finished shakes)
  - `seconds` f64: Time since the last frame. (Seconds)

  Example: The shake ends after its duration

  ```rust
  use vanilla::{CameraShake, CameraShakeOptions};
  
  let mut camera_shake = CameraShake::new(1);
  camera_shake.add(CameraShakeOptions { duration: 0.2, ..Default::default() });
  camera_shake.update(0.1);
  assert!(camera_shake.is_shaking());
  camera_shake.update(0.1);
  assert!(!camera_shake.is_shaking());
  ```

- `pub fn read(&self) -> CameraShakeOffset` (method, since 0.4.0): Current offset. (sum of all live shakes, camera local axes)
  - returns CameraShakeOffset: Position (scene length, x right, y up, z back) and rotation (radians, x pitch, y yaw, z roll). (both zero vectors when there is no shake)

  Example: The position offset stays within strength x axis share

  ```rust
  use vanilla::{CameraShake, CameraShakeOptions};
  
  let mut camera_shake = CameraShake::new(5);
  camera_shake.add(CameraShakeOptions { amplitude: 0.2, duration: 1.0, ..Default::default() });
  camera_shake.update(0.1);
  let offset = camera_shake.read();
  assert!(offset.position.x.abs() <= 0.2 && offset.position.y.abs() <= 0.2 && offset.position.z.abs() <= 0.2);
  ```

- `pub fn is_shaking(&self) -> bool` (method, since 0.4.0): Whether any shake remains. (shakes that start later count too)
  - returns bool: true if there is at least one live shake.

  Example: A shake that starts later counts as remaining

  ```rust
  use vanilla::{CameraShake, CameraShakeOptions};
  
  let mut camera_shake = CameraShake::new(1);
  assert!(!camera_shake.is_shaking());
  camera_shake.add(CameraShakeOptions { age: -0.5, ..Default::default() });
  assert!(camera_shake.is_shaking());
  ```

- `pub fn clear(&mut self)` (method, since 0.4.0): Stop all shakes at once.

  Example: Clear shakes when changing scenes

  ```rust
  use vanilla::{CameraShake, CameraShakeOptions};
  
  let mut camera_shake = CameraShake::new(1);
  camera_shake.add(CameraShakeOptions::default());
  camera_shake.clear();
  assert!(!camera_shake.is_shaking());
  ```

## Functions and constants

- `pub fn create_offset_view_matrix(view_matrix: &Matrix4, position: Vector3, rotation: Vector3) -> Matrix4` (method, since 0.4.0): Apply an offset in camera local axes to a view matrix. (the view of the camera moved by position and rotated by rotation from where it is, a new matrix)
  - position is in camera local axes. (x right, y up, z back, the camera looks down -Z)
  - rotation is angles (radians) in camera local axes. (x is pitch, y is yaw, z is roll, applied roll then pitch then yaw)
  - The offset camera is (camera) x translation x yaw x pitch x roll, and the view matrix is its inverse, so the inverse of (translation x yaw x pitch x roll) is multiplied in front.
  - `view_matrix` &Matrix4: View matrix before the offset. (world → camera, not modified)
  - `position` Vector3: Position offset in camera local axes. (scene length)
  - `rotation` Vector3: Rotation offset in camera local axes. (radians, x pitch, y yaw, z roll)
  - returns Matrix4: Offset view matrix. (a new matrix)

  Example: Offset a view matrix 0.1 to the right and tilt it up 0.02 radians

  ```rust
  use vanilla::{create_offset_view_matrix, Matrix4, Vector3};
  
  let view_matrix = Matrix4::create_look_at(Vector3::create(0.0, 2.0, 6.0), Vector3::create(0.0, 1.0, 0.0), Vector3::create(0.0, 1.0, 0.0));
  let shaken_view_matrix = create_offset_view_matrix(&view_matrix, Vector3::create(0.1, 0.0, 0.0), Vector3::create(0.02, 0.0, 0.0));
  assert_eq!(shaken_view_matrix.get_elements().len(), 16);
  assert_eq!(create_offset_view_matrix(&view_matrix, Vector3::zero(), Vector3::zero()).get_elements(), view_matrix.get_elements());
  ```

