use crate::scale;
pub const ONE: i128 = 1 << 16;
pub const LIMIT: i128 = 1 << 63;
pub const UNIT: i128 = 1 << 62;
pub const FULL_TURN: i128 = scale::FULL_TURN as i128 * ONE;
pub const HALF_TURN: i128 = FULL_TURN / 2;
pub const QUARTER_TURN: i128 = scale::QUARTER_TURN as i128 * ONE;
const EIGHTH_TURN: i128 = FULL_TURN / 8;
const PI: i128 = 14_488_038_916_154_245_685;
const HALF_PI: i128 = 7_244_019_458_077_122_842;
const QUARTER_PI: i128 = 3_622_009_729_038_561_421;
#[must_use]
pub fn rounded(dividend: i128, divisor: i128) -> i128 {
if divisor == 0 {
return 0;
}
let (quotient, rest) = (dividend / divisor, dividend % divisor);
if rest.unsigned_abs() >= divisor.unsigned_abs() - rest.unsigned_abs() {
quotient + dividend.signum() * divisor.signum()
} else {
quotient
}
}
#[must_use]
pub fn product(a: i128, b: i128) -> i128 {
rounded(a * b, UNIT)
}
#[must_use]
pub const fn root(square: u128) -> i128 {
square.isqrt().cast_signed()
}
#[must_use]
pub fn sin_cos(angle: i128) -> [i128; 2] {
let turned = angle.rem_euclid(FULL_TURN);
let (quarter, rest) = (turned / QUARTER_TURN, turned % QUARTER_TURN);
let [sin, cos] = if rest <= EIGHTH_TURN {
series(rounded(rest * QUARTER_PI, EIGHTH_TURN))
} else {
let [sin, cos] = series(rounded((QUARTER_TURN - rest) * QUARTER_PI, EIGHTH_TURN));
[cos, sin]
};
match quarter {
0 => [sin, cos],
1 => [cos, -sin],
2 => [-sin, -cos],
_ => [-cos, sin],
}
}
fn series(x: i128) -> [i128; 2] {
let square = product(x, x);
let sum = |first: i128, first_power: i128| {
let (mut total, mut term, mut power) = (0, first, first_power);
while term != 0 {
total += term;
term = -rounded(product(term, square), (power + 1) * (power + 2));
power += 2;
}
total
};
[sum(x, 1), sum(UNIT, 0)]
}
#[must_use]
pub fn angle_of(x: i128, y: i128) -> i128 {
if x == 0 && y == 0 {
return 0;
}
let (across, up) = (x.unsigned_abs(), y.unsigned_abs());
let shift = (128 - across.max(up).leading_zeros()).saturating_sub(64);
let (across, up) = (across >> shift, up >> shift);
let ratio =
|small: u128, large: u128| rounded((small << 62).cast_signed(), large.cast_signed());
let first = if up <= across {
arctangent(ratio(up, across))
} else {
HALF_PI - arctangent(ratio(across, up))
};
let half = if x < 0 { PI - first } else { first };
let radians = if y < 0 { -half } else { half };
rounded(radians * HALF_TURN, PI)
}
fn arctangent(t: i128) -> i128 {
let halved = |t: i128| {
let square = (UNIT * UNIT + t * t).cast_unsigned();
rounded(t * UNIT, UNIT + root(square))
};
let small = halved(halved(t));
let square = product(small, small);
let (mut total, mut power, mut divisor) = (0, small, 1);
while power != 0 {
total += rounded(power, divisor);
power = -product(power, square);
divisor += 2;
}
4 * total
}
#[cfg(test)]
mod tests;