# base/math (vanilla-engine 0.4.0)

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

Math helper functions. (the original base/math.js)
- Numbers are f64 like the original JavaScript numbers. Only random_int is i32.
- The original floor, ceil, sqrt, abs, sin, cos, tan, asin, acos and pow are kept as functions of the same names. (so using code matches the original)
  sin, cos and tan compute what Chrome's Math.sin, cos and tan compute, as in the original (correctly rounded f64, base/trigonometry.rs). (the system libm has different last digits on each platform)
  round rounds halves toward +infinity (-2.5 → -2), which differs from f64::round (-2.5 → -3), so the original formula was ported as is.
- Randomness uses the engine's random (xorshift64*). (in place of the original Math.random)
- The default randomFunction argument of the original shuffle is split into shuffle (engine random) and shuffle_with_random_function (a passed function).

Example: Range clamping, interpolation, rounding, angle conversion, random numbers

```rust
use vanilla::math;

assert_eq!(math::clamp(15.0, 0.0, 10.0), 10.0);
assert_eq!(math::lerp(0.0, 10.0, 0.25), 2.5);
assert_eq!(math::round(-2.5), -2.0);
assert!((math::degree_to_radian(180.0) - math::PI).abs() < 1e-6);

let value = math::random_range(5.0, 10.0);
assert!(value >= 5.0 && value <= 10.0);
```

## Functions and constants

- `pub const PI: f64 = std::f64::consts::PI` (field, since 0.3.2): Pi. (std::f64::consts::PI)
  - returns f64
- `pub const POSITIVE_INFINITY: f64 = f64::INFINITY` (field, since 0.4.0): Positive infinity. (the original PositiveInfinity)
  - returns f64
- `pub const NEGATIVE_INFINITY: f64 = f64::NEG_INFINITY` (field, since 0.4.0): Negative infinity. (the original NegativeInfinity)
  - returns f64
- `pub fn min(left: f64, right: f64) -> f64` (method, since 0.4.0): The lower number. (right unless left < right, as in the original; differs from f64::min when NaN is involved)
  - `left` f64: First number.
  - `right` f64: Second number.
  - returns f64: left if left < right, otherwise right. (right if either is NaN)

  Example: The second value when NaN is involved

  ```rust
  use vanilla::math;
  
  assert_eq!(math::min(2.0, 1.0), 1.0);
  assert_eq!(math::min(f64::NAN, 1.0), 1.0);
  assert!(math::min(1.0, f64::NAN).is_nan());
  ```

- `pub fn max(left: f64, right: f64) -> f64` (method, since 0.4.0): The higher number. (right unless left > right, as in the original)
  - `left` f64: First number.
  - `right` f64: Second number.
  - returns f64: left if left > right, otherwise right. (right if either is NaN)
- `pub fn floor(value: f64) -> f64` (method, since 0.4.0): Floor. (infinity stays as is)
  - `value` f64: Number to round down.
  - returns f64: The largest integer less than or equal to value.
- `pub fn ceil(value: f64) -> f64` (method, since 0.4.0): Ceiling. (infinity stays as is)
  - `value` f64: Number to round up.
  - returns f64: The smallest integer greater than or equal to value.
- `pub fn round(value: f64) -> f64` (method, since 0.4.0): Rounding. (the original round: halves toward +infinity, -2.5 → -2, -0.5 → 0, infinity stays as is)
  - `value` f64: Number to round.
  - returns f64: The nearest integer. (halves toward +infinity, NaN and infinity stay as is)

  Example: Negative halves round up

  ```rust
  use vanilla::math;
  
  assert_eq!(math::round(2.5), 3.0);
  assert_eq!(math::round(-2.5), -2.0);
  assert_eq!(math::round(-2.6), -3.0);
  assert_eq!(math::round(f64::INFINITY), f64::INFINITY);
  ```

- `pub fn sqrt(value: f64) -> f64` (method, since 0.4.0): Square root. (NaN for negatives)
  - `value` f64: Number to take the square root of.
  - returns f64: Square root. (NaN for negative numbers)
- `pub fn abs(value: f64) -> f64` (method, since 0.4.0): Absolute value. (flips the sign if less than 0, as in the original)
  - `value` f64: Number to take the absolute value of.
  - returns f64: -value if less than 0, otherwise value. (-0 and NaN stay as is)
- `pub fn sin(value: f64) -> f64` (method, since 0.4.0): Sine.
  - `value` f64: Angle. (radians)
  - returns f64: Sine value. (-1 ~ 1)
- `pub fn cos(value: f64) -> f64` (method, since 0.4.0): Cosine.
  - `value` f64: Angle. (radians)
  - returns f64: Cosine value. (-1 ~ 1)
- `pub fn tan(value: f64) -> f64` (method, since 0.4.0): Tangent.
  - `value` f64: Angle. (radians)
  - returns f64: Tangent value.
- `pub fn asin(value: f64) -> f64` (method, since 0.4.0): Arcsine. (NaN outside the range)
  - `value` f64: Sine value. (-1 ~ 1)
  - returns f64: Angle. (radians, -PI / 2 ~ PI / 2, NaN if outside the range)
- `pub fn acos(value: f64) -> f64` (method, since 0.4.0): Arccosine. (NaN outside the range)
  - `value` f64: Cosine value. (-1 ~ 1)
  - returns f64: Angle. (radians, 0 ~ PI, NaN if outside the range)
- `pub fn pow(base: f64, exponent: f64) -> f64` (method, since 0.4.0): Power. (correct even for fractional or negative exponents)
  - `base` f64: Base.
  - `exponent` f64: Exponent.
  - returns f64: base raised to the power of exponent.
- `pub fn clamp(value: f64, minimum: f64, maximum: f64) -> f64` (method, since 0.3.2): Clamps to a range.
  - `value` f64: Number to clamp.
  - `minimum` f64: Minimum value.
  - `maximum` f64: Maximum value.
  - returns f64: minimum if value is less than minimum, maximum if greater than maximum, otherwise value. (minimum is checked first)
- `pub fn clamp01(value: f64) -> f64` (method, since 0.3.2): Clamps to the 0 ~ 1 range.
  - `value` f64: Number to clamp.
  - returns f64: The value clamped to 0 ~ 1.
- `pub fn degree_to_radian(degree: f64) -> f64` (method, since 0.3.2): Degrees → radians.
  - `degree` f64: Angle. (degrees)
  - returns f64: Angle. (radians)
- `pub fn radian_to_degree(radian: f64) -> f64` (method, since 0.3.2): Radians → degrees.
  - `radian` f64: Angle. (radians)
  - returns f64: Angle. (degrees)
- `pub fn lerp(from: f64, to: f64, time: f64) -> f64` (method, since 0.3.2): Linear interpolation.
  - `from` f64: Start value.
  - `to` f64: End value.
  - `time` f64: Interpolation ratio. (0 is from, 1 is to, values outside 0 ~ 1 are not clamped)
  - returns f64: from + (to - from) * time.
- `pub fn random() -> f64` (method, since 0.3.2): Random number from 0 inclusive to 1 exclusive.
  - returns f64: Random number from 0 inclusive to 1 exclusive. (in steps of 2 to the power of -24, each thread keeps its own state)
- `pub fn random_range(minimum: f64, maximum: f64) -> f64` (method, since 0.3.2): Random number in a range. (minimum inclusive to maximum exclusive)
  - `minimum` f64: Range start. (inclusive)
  - `maximum` f64: Range end.
  - returns f64: minimum + (maximum - minimum) * random().
- `pub fn random_int(minimum: i32, maximum: i32) -> i32` (method, since 0.4.0): Random integer in a range. (minimum to maximum inclusive)
  - `minimum` i32: Smallest value. (inclusive)
  - `maximum` i32: Largest value. (inclusive)
  - returns i32: An integer from minimum to maximum inclusive.

  Example: Roll a die

  ```rust
  use vanilla::math;
  
  let dice = math::random_int(1, 6);
  assert!((1..=6).contains(&dice));
  assert_eq!(math::random_int(5, 5), 5);
  ```

- `pub fn pick_random<T>(array: &[T]) -> Option<&T>` (method, since 0.4.0): One random element from an array. (None if empty, the original undefined)
  - `array` &[T]: Slice to pick from.
  - returns Option<&T>: Reference to the randomly picked element. None if empty.

  Example: Pick one from a list

  ```rust
  use vanilla::math;
  
  let item_list = ["sword", "shield", "potion"];
  match math::pick_random(&item_list) {
  	Some(item) => {
  		assert!(item_list.contains(item));
  	}
  	None => {
  		unreachable!();
  	}
  }
  let empty_list: [i32; 0] = [];
  assert!(math::pick_random(&empty_list).is_none());
  ```

- `pub fn shuffle<T>(array: &mut [T])` (method, since 0.4.0): Shuffles an array in place. (Fisher-Yates, engine random)
  - `array` &mut [T]: Slice to shuffle. (changed in place)
- `pub fn shuffle_with_random_function<T>(array: &mut [T], mut random_function: impl FnMut() -> f64)` (method, since 0.4.0): Shuffles an array in place with a passed random function (0 inclusive to 1 exclusive). (SeededRandom's next_value and such)
  - `array` &mut [T]: Slice to shuffle. (changed in place)
  - `random_function` impl FnMut() -> f64: Function returning 0 inclusive to 1 exclusive. (called element count - 1 times; values of 1 or more are clamped to the current position)

  Example: Always shuffle in the same order with a seeded random

  ```rust
  use vanilla::{math, SeededRandom};
  
  let mut first_list = [1, 2, 3, 4, 5];
  let mut second_list = [1, 2, 3, 4, 5];
  let mut first_random = SeededRandom::new(42);
  let mut second_random = SeededRandom::new(42);
  math::shuffle_with_random_function(&mut first_list, || first_random.next_value());
  math::shuffle_with_random_function(&mut second_list, || second_random.next_value());
  assert_eq!(first_list, second_list);
  
  let mut number_list = [1, 2, 3, 4];
  math::shuffle_with_random_function(&mut number_list, || 0.0);
  assert_eq!(number_list, [2, 3, 4, 1]);
  ```

- `pub fn approach(current_value: f64, target_value: f64, rate: f64, time_delta: f64) -> f64` (method, since 0.3.2): Frame-rate independent exponential decay follow. (does not jump even if the target changes midway; the larger rate is, the faster it catches up)
  - current + (target - current) * (1 - e^(-rate * time_delta))
  - `current_value` f64: Current value.
  - `target_value` f64: Target value.
  - `rate` f64: Catch-up speed. (per time unit, the larger the faster; unchanged if 0)
  - `time_delta` f64: Elapsed time. (in the same time unit as rate)
  - returns f64: Value moved toward the target. (does not overshoot if rate and time_delta are 0 or more)

  Example: Smoothly follow the target every frame

  ```rust
  use vanilla::math;
  
  let mut camera_x = 0.0;
  for _ in 0..60 {
  	camera_x = math::approach(camera_x, 100.0, 5.0, 1.0 / 60.0);
  }
  assert!(camera_x > 99.0 && camera_x < 100.0);
  ```

- `pub fn move_towards(current_value: f64, target_value: f64, maximum_delta: f64) -> f64` (method, since 0.4.0): Moves a value toward the target at a constant speed. (does not overshoot)
  - `current_value` f64: Current value.
  - `target_value` f64: Target value.
  - `maximum_delta` f64: Maximum distance to move at once. (0 or more)
  - returns f64: Value moved toward the target by maximum_delta. target_value if the remaining difference is maximum_delta or less.

  Example: Approach at a constant speed without overshooting

  ```rust
  use vanilla::math;
  
  assert_eq!(math::move_towards(0.0, 10.0, 3.0), 3.0);
  assert_eq!(math::move_towards(0.0, -10.0, 3.0), -3.0);
  assert_eq!(math::move_towards(9.0, 10.0, 3.0), 10.0);
  ```

- `pub fn ease_out_quad(time: f64) -> f64` (method, since 0.3.2): Easing: a quadratic curve decelerating outward.
  - `time` f64: Progress ratio. (0 ~ 1)
  - returns f64: 1 - (1 - time) * (1 - time). (0 at 0, 1 at 1)
