# misc/camera2d (vanilla-engine 0.4.0)

> https://vanillapunch.com/docs/vanilla-engine/0.4.0/api/misc/camera2d/

2D camera.
- A port of the original misc/camera2d.js. Gathers following, world bounds clamping, drag panning, cursor-anchored zoom, inertia, and movement tweens in one place.
- position is the world coordinate the camera looks at (screen center), zoom is the magnification, and rotation is the angle (degrees) around the screen center.
  The world rotates on screen by rotation. (same direction as the original deprecated/camera.js begin applying rotate after scale)
- Unlike the original, it is a plain value, not a component. The owner (a scene, etc.) calls tick and applies apply_transform before drawing the world.
- Usage:
  ```text
    camera.set_view_size(view_size);                    // every frame or on resize
    camera.follow(&[hero_position], 6.0, time_delta);  // follow (optional)
    camera.tick(time_delta);
    camera.begin(graphic); ...render world... camera.end(graphic);   // push_state + apply_transform / pop_state
  ```
- Differences from the original:
  Following the no-abbreviation naming rule, minZoom / maxZoom are written as minimum_zoom / maximum_zoom. (set_zoom_range means the same)
  The default tween_to duration of 0.4 seconds is passed as the DEFAULT_TWEEN_DURATION constant. (Rust has no default arguments)

Example: Draw the world while following the hero

```rust
use vanilla::{Camera2D, Colors, Graphic, Rect, Vector2};

fn draw_world(camera: &mut Camera2D, graphic: &mut Graphic, view_size: Vector2, hero_position: Vector2, time_delta: f64) {
	camera.set_view_size(view_size);
	camera.follow(&[hero_position], 6.0, time_delta);
	camera.tick(time_delta);
	camera.begin(graphic);
	graphic.set_fill_color(Colors::WHITE);
	graphic.draw_rect(Rect::create(hero_position.x - 16.0, hero_position.y - 16.0, 32.0, 32.0));
	camera.end(graphic);
}
```

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

2D camera.
- Converts between screen and world coordinates using position (the world coordinate seen at the screen center), zoom, rotation (degrees), and view size (pixels).

Example: Convert between screen and world coordinates

```rust
use vanilla::{Camera2D, Vector2};

let mut camera = Camera2D::new();
camera.set_view_size(Vector2::create(800.0, 600.0));
camera.set_position(Vector2::create(100.0, 50.0));
camera.set_zoom(2.0);
let screen_position = camera.world_to_screen(Vector2::create(110.0, 50.0));
assert_eq!(screen_position, Vector2::create(420.0, 300.0));
assert_eq!(camera.screen_to_world(screen_position), Vector2::create(110.0, 50.0));
```

Example: Keep the visible area inside the world bounds

```rust
use vanilla::{Camera2D, Rect, Vector2};

let mut camera = Camera2D::new();
camera.set_view_size(Vector2::create(400.0, 300.0));
camera.set_world_bounds(Some(Rect::create(0.0, 0.0, 1000.0, 1000.0)));
camera.set_position(Vector2::create(-500.0, 2000.0));
assert_eq!(camera.get_position(), Vector2::create(200.0, 850.0));
```

- `pub const DEFAULT_TWEEN_DURATION: f64 = 0.4` (static, since 0.3.2): Default duration of tween_to. (seconds, original duration = 0.4)
  - returns f64
- `pub fn new() -> Camera2D` (constructor, since 0.3.2): Constructor. (position 0, zoom 1, rotation 0, view 960x640, no bounds, inertia damping 6, zoom range 0.1 ~ 8)
  - returns Camera2D: A camera filled with default values.
- `pub fn tick(&mut self, time_delta: f64)` (method, since 0.3.2): Update. (in order: inertia movement, movement tween, bounds clamp)
  - The inertia velocity is multiplied by e^(-inertia damping * time_delta), and becomes 0 once both axes drop below 1.
  - The tween interpolates the position with a cubic ease out and the zoom geometrically. It ends on the frame that fills the duration.
  - `time_delta` f64: Time elapsed since the last frame. (seconds)
- `pub fn follow(&mut self, target_positions: &[Vector2], rate: f64, time_delta: f64)` (method, since 0.3.2): Follows targets. (follows the midpoint when there are several, frame-independent exponential decay, the larger rate is the faster it catches up)
  - Each call closes 1 - e^(-rate * time_delta) of the remaining distance. Does not clamp to bounds. (tick does)
  - `target_positions` &[Vector2]: List of world coordinates to follow. Does nothing if empty.
  - `rate` f64: Approach speed. (exponential decay rate per second, the original usage example uses 6)
  - `time_delta` f64: Time elapsed since the last frame. (seconds)

  Example: Stick to the midpoint of two targets

  ```rust
  use vanilla::{Camera2D, Vector2};
  
  let mut camera = Camera2D::new();
  let target_positions = [Vector2::create(100.0, 0.0), Vector2::create(300.0, 200.0)];
  for _ in 0..600 {
  	camera.follow(&target_positions, 6.0, 1.0 / 60.0);
  }
  let position = camera.get_position();
  assert!((position.x - 200.0).abs() < 0.01);
  assert!((position.y - 100.0).abs() < 0.01);
  ```

- `pub fn pan_by_screen(&mut self, screen_delta_x: f64, screen_delta_y: f64)` (method, since 0.3.2): Pans by screen pixels. (drag panning, converted to a world offset taking zoom and rotation into account)
  - The camera moves the opposite way so the world follows the drag. Clamps to bounds.
  - `screen_delta_x` f64: Horizontal distance dragged on screen. (pixels)
  - `screen_delta_y` f64: Vertical distance dragged on screen. (pixels)

  Example: Drag a 2x zoomed view 40 pixels to the right

  ```rust
  use vanilla::{Camera2D, Vector2};
  
  let mut camera = Camera2D::new();
  camera.set_zoom(2.0);
  camera.pan_by_screen(40.0, 0.0);
  assert_eq!(camera.get_position(), Vector2::create(-20.0, 0.0));
  ```

- `pub fn fling(&mut self, screen_velocity_x: f64, screen_velocity_y: f64)` (method, since 0.3.2): Flings with inertia. (pass the screen pixel velocity when the drag is released)
  - Converts it to a world velocity in the same direction as pan_by_screen, and tick moves by that velocity while slowing it down.
  - `screen_velocity_x` f64: Horizontal screen velocity. (pixels per second)
  - `screen_velocity_y` f64: Vertical screen velocity. (pixels per second)

  Example: Fling to the right and the camera slides to the left

  ```rust
  use vanilla::Camera2D;
  
  let mut camera = Camera2D::new();
  camera.fling(600.0, 0.0);
  camera.tick(0.1);
  assert!(camera.get_position().x < 0.0);
  ```

- `pub fn convert_screen_delta_to_world(&self, screen_delta_x: f64, screen_delta_y: f64) -> Vector2` (method, since 0.4.0): Screen pixel movement → world movement. (undoes rotation and divides by zoom)
  - `screen_delta_x` f64: Horizontal screen movement. (pixels)
  - `screen_delta_y` f64: Vertical screen movement. (pixels)
  - returns Vector2: The same movement measured in world coordinates. (not added to the position)
- `pub fn zoom_at(&mut self, anchor_screen: Vector2, zoom_factor: f64)` (method, since 0.3.2): Zooms with a fixed screen anchor. (wheel / pinch, the world point under anchor_screen does not move, 1.1 = 10% zoom in)
  - The new zoom is clamped to the zoom range. Does nothing if the clamped zoom is unchanged. Clamps to bounds after the change.
  - `anchor_screen` Vector2: Screen coordinate to keep fixed. (pixels, usually the cursor or the midpoint of two fingers)
  - `zoom_factor` f64: Value to multiply the current zoom by. (greater than 1 zooms in, less zooms out)

  Example: Zoom in 2x keeping the point under the cursor fixed

  ```rust
  use vanilla::{Camera2D, Vector2};
  
  let mut camera = Camera2D::new();
  camera.set_view_size(Vector2::create(800.0, 600.0));
  let anchor_screen = Vector2::create(600.0, 300.0);
  let anchor_world = camera.screen_to_world(anchor_screen);
  camera.zoom_at(anchor_screen, 2.0);
  assert_eq!(camera.get_zoom(), 2.0);
  assert_eq!(camera.screen_to_world(anchor_screen), anchor_world);
  ```

- `pub fn tween_to(&mut self, target_position: Vector2, target_zoom: f64, duration: f64)` (method, since 0.3.2): Starts a movement tween to a position / zoom. (stops inertia, default duration is DEFAULT_TWEEN_DURATION)
  - tick drives the progress. If already tweening, starts anew from the current spot.
  - `target_position` Vector2: Destination world coordinate.
  - `target_zoom` f64: Destination zoom. (clamped to the zoom range)
  - `duration` f64: Duration. (seconds, 0.0001 if less than 0.0001)

  Example: Move over 0.4 seconds while zooming in 2x

  ```rust
  use vanilla::{Camera2D, Vector2};
  
  let mut camera = Camera2D::new();
  camera.tween_to(Vector2::create(300.0, 0.0), 2.0, Camera2D::DEFAULT_TWEEN_DURATION);
  assert!(camera.is_tweening());
  for _ in 0..30 {
  	camera.tick(1.0 / 60.0);
  }
  assert!(!camera.is_tweening());
  assert!((camera.get_position().x - 300.0).abs() < 0.001);
  assert!((camera.get_zoom() - 2.0).abs() < 0.001);
  ```

- `pub fn apply_transform(&self, graphic: &mut Graphic)` (method, since 0.3.2): Applies the drawing transform. (the caller wraps it with push_state / pop_state)
  - Multiplies into the current transform in order: translate to the view center, zoom, rotation, then translate by the negated position.
  - `graphic` &mut Graphic: Graphic to apply the transform to.
- `pub fn begin(&self, graphic: &mut Graphic)` (method, since 0.4.0): Begins drawing. (pushes the state and applies the transform, the original deprecated/camera.js begin)
  - Call end as its pair after drawing the whole world.
  - `graphic` &mut Graphic: Graphic to draw with.
- `pub fn end(&self, graphic: &mut Graphic)` (method, since 0.4.0): Ends drawing. (restores the state pushed by begin, the original deprecated/camera.js end)
  - `graphic` &mut Graphic: The graphic passed to begin.
- `pub fn screen_to_world(&self, screen_position: Vector2) -> Vector2` (method, since 0.3.2): Screen coordinates → world coordinates.
  - `screen_position` Vector2: Screen coordinate. (pixels, relative to the top left of the view)
  - returns Vector2: The world coordinate seen at that screen point.
- `pub fn world_to_screen(&self, world_position: Vector2) -> Vector2` (method, since 0.3.2): World coordinates → screen coordinates.
  - `world_position` Vector2: World coordinates.
  - returns Vector2: The screen coordinate where that world point appears. (pixels, relative to the top left of the view, may be off screen)
- `pub fn get_visible_half_extent(&self) -> Vector2` (method, since 0.4.0): Half width and half height of the world area visible on screen. (axis-aligned box enclosing the rotated view)
  - returns Vector2: x is the half width, y is the half height. (world units)
- `pub fn clamp_to_bounds(&mut self)` (method, since 0.3.2): Clamps to the world bounds. (keeps the visible area inside the bounds, and centers an axis when the visible area is larger than the bounds (zoomed out))
  - When rotated, measures with the axis-aligned box that encloses the rotated view.
- `pub fn set_position(&mut self, position: Vector2)` (method, since 0.3.2): Sets the position. (clamps to bounds)
  - `position` Vector2: World coordinate to place at the screen center.
- `pub fn get_position(&self) -> Vector2` (method, since 0.3.2): Returns the position.
  - returns Vector2: The world coordinate seen at the screen center.
- `pub fn set_zoom(&mut self, zoom: f64)` (method, since 0.3.2): Sets the zoom. (clamped to the zoom range and to bounds)
  - `zoom` f64: Magnification. (1 is the original size)
- `pub fn get_zoom(&self) -> f64` (method, since 0.3.2): Returns the scale.
  - returns f64: Zoom factor.
- `pub fn set_rotation(&mut self, rotation: f64)` (method, since 0.4.0): Sets the rotation. (degrees, rotates around the screen center, clamps to bounds)
  - `rotation` f64: Rotation angle. (degrees, not clamped to a range)
- `pub fn get_rotation(&self) -> f64` (method, since 0.4.0): Returns the rotation. (degrees)
  - returns f64: Rotation angle. (degrees)
- `pub fn set_view_size(&mut self, view_size: Vector2)` (method, since 0.3.2): Sets the view size. (the size that defines the screen center)
  - The bounds clamp happens on the next tick or another setter.
  - `view_size` Vector2: View width and height. (pixels)
- `pub fn get_view_size(&self) -> Vector2` (method, since 0.3.2): Returns the view size.
  - returns Vector2: View width and height. (pixels)
- `pub fn set_world_bounds(&mut self, world_bounds: Option<Rect>)` (method, since 0.3.2): Sets the world bounds. (None means no bounds)
  - `world_bounds` Option<Rect>: World rectangle to keep the visible area in. None means no bounds. (clamps immediately)
- `pub fn get_world_bounds(&self) -> Option<Rect>` (method, since 0.3.2): Returns the world bounds.
  - returns Option<Rect>: World bounds. None if there are no bounds.
- `pub fn set_zoom_range(&mut self, minimum_zoom: f64, maximum_zoom: f64)` (method, since 0.3.2): Sets the zoom range. (the current zoom is clamped again to the new range)
  - `minimum_zoom` f64: Smallest zoom. (default 0.1)
  - `maximum_zoom` f64: Largest zoom. (default 8)
- `pub fn set_inertia_damping(&mut self, inertia_damping: f64)` (method, since 0.3.2): Sets the inertia damping. (the larger, the faster it stops)
  - `inertia_damping` f64: Exponential decay rate per second. (default 6, each tick multiplies the velocity by e^(-inertia_damping * time_delta))
- `pub fn is_tweening(&self) -> bool` (method, since 0.3.2): Whether a movement tween is running.
  - returns bool: true if the tween started by tween_to has not finished yet.
- `pub fn stop_inertia(&mut self)` (method, since 0.3.2): Stops inertia.
