# Gear outlines for gears.jl: the mkparts spur outline of pinion and wheel in each gear's
# body frame, written as x, y in mm. The polar angle is the usual one (x = r cos θ), so
# tooth 0 is centred on the +x axis of the body frame; gears.jl turns each gear into place.
import numpy as np
import matplotlib.pyplot as plt
from pathlib import Path
from mkparts.geometry import spur_outline

m, phi = 4.0, 20.0
here = Path(__file__).parent

for name, N in [('pinion', 20), ('wheel', 30)]:
    th, r = spur_outline(N, m, phi_deg=phi, fillet=0.3*m, n_flank=60, n_land=16)
    np.savetxt(here/f'{name}_outline.csv', np.c_[r*np.cos(th), r*np.sin(th)], delimiter=',')

# Check plot: one pinion tooth with its fillet circle, base, root and pitch circles
th, r = spur_outline(20, m, phi_deg=phi, fillet=0.3*m, n_flank=60, n_land=16)
x, y = r*np.cos(th), r*np.sin(th)
rp = m*20/2; rb, rf, R = rp*np.cos(np.radians(phi)), rp - 1.25*m, 0.3*m
inv = np.tan(np.radians(phi)) - np.radians(phi)
half = np.pi/40 + inv
delta = np.arcsin(R/(rf + R))
fig, ax = plt.subplots(figsize=(6, 6))
ax.plot(x, y, '.-', ms=2, lw=0.8, color='k')
a = np.linspace(-0.3, 0.3, 200)
for rr, c, lab in [(rb, 'C0', 'base'), (rf, 'C1', 'root'), (rp, 'C2', 'pitch')]:
    ax.plot(rr*np.cos(a), rr*np.sin(a), color=c, lw=0.6, label=lab)
for sgn in (1, -1):
    c = (rf + R)*np.array([np.cos(sgn*(half + delta)), np.sin(sgn*(half + delta))])
    ax.add_patch(plt.Circle(c, R, fill=False, ls='--', color='C3'))
    ax.plot([rf*np.cos(sgn*half), (rp + m)*np.cos(sgn*half)],
            [rf*np.sin(sgn*half), (rp + m)*np.sin(sgn*half)], ':', color='0.5', lw=0.6)
ax.set_xlim(33, 45); ax.set_ylim(-6, 6); ax.set_aspect('equal'); ax.legend()
fig.savefig(here/'out'/'outline_check.png', dpi=150)
