use std::f32::consts::TAU;
const TEETH: f32 = 14.0;
const TOOTH_TOP: f32 = 0.20;
const TOOTH_BASE: f32 = 0.36;
const TOOTH_ROOT: f32 = 0.82;
const TOOTH_TALL: f32 = 0.18;
const STROKE: f32 = 0.072;
#[inline]
pub fn tooth_profile(x: f32, y: f32) -> f32 {
let u = (y.atan2(x) / TAU * TEETH).rem_euclid(1.0);
let t = (u - 0.5).abs() * 2.0;
if t <= TOOTH_TOP {
1.0
} else if t >= TOOTH_BASE {
0.0
} else {
(TOOTH_BASE - t) / (TOOTH_BASE - TOOTH_TOP)
}
}
#[inline]
pub fn disc(x: f32, y: f32) -> f32 {
let r = (x * x + y * y).sqrt();
r - (TOOTH_ROOT + TOOTH_TALL * tooth_profile(x, y))
}
#[inline]
fn segment(px: f32, py: f32, ax: f32, ay: f32, bx: f32, by: f32, w: f32) -> f32 {
let pax = px - ax;
let pay = py - ay;
let bax = bx - ax;
let bay = by - ay;
let h = ((pax * bax + pay * bay) / (bax * bax + bay * bay)).clamp(0.0, 1.0);
let dx = pax - bax * h;
let dy = pay - bay * h;
(dx * dx + dy * dy).sqrt() - w
}
#[inline]
pub fn mark(x: f32, y: f32) -> f32 {
let dy = y - 0.15;
let r = (x * x + dy * dy).sqrt();
let mut d = (r - 0.34).abs() - STROKE;
d = d.min((r - 0.112).abs() - STROKE);
d = d.min(segment(x, y, 0.0, 0.12, 0.0, -0.54, STROKE));
d = d.min(segment(x, y, 0.0, -0.54, 0.19, -0.58, STROKE));
d = d.min(segment(x, y, -0.50, 0.30, -0.575, 0.02, STROKE));
d = d.min(segment(x, y, -0.575, 0.02, -0.575, -0.26, STROKE));
let dx = x - 0.485;
let dy2 = y + 0.02;
d.min((dx * dx + dy2 * dy2).sqrt() - 0.066)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn disc_covers_the_tooth_ring() {
assert!(disc(0.0, 0.78) < 0.0);
assert!(disc(0.0, 0.0) < 0.0);
assert!(disc(0.0, 1.05) > 0.0);
}
#[test]
fn mark_hollows_the_p_bowl() {
assert!(mark(0.0, 0.15 + 0.34) < 0.0);
assert!(mark(0.0, 0.15 + 0.22) > 0.0);
assert!(mark(0.485, -0.02) < 0.0);
}
#[test]
fn tooth_profile_alternates() {
let mut hi = 0;
let mut lo = 0;
for k in 0..100 {
let a = k as f32 / 100.0 * TAU;
let p = tooth_profile(a.cos(), a.sin());
if p > 0.9 {
hi += 1;
}
if p < 0.1 {
lo += 1;
}
}
assert!(hi > 20 && lo > 20, "齿顶 {hi} / 齿谷 {lo}");
}
}