"""Check the gear: the tooth's width where it crosses the base, pitch and tip circles (cut from the solid), and a close-up
of one tooth saved as zoom.png. Keep it in the same folder as gear.py."""
import math, matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import cadquery as cq
from gear import gear_profile, spur_gear
pts, d = gear_profile(2.0, 20, 20.0)
# tooth 0 is centred on the x axis: its width where it crosses each circle, from the solid itself
g, _ = spur_gear()
for name in ("base", "pitch", "tip"):
    r = d[name] / 2 - (0.01 if name == "tip" else 0)
    ring = cq.Workplane("XY").circle(r).circle(r - 0.001).extrude(8)
    cut = g.intersect(ring).val()
    # the tooth on the x axis: arc length of the part of the ring inside the solid, near angle 0
    angs = sorted(math.atan2(v.Y, v.X) for v in cut.Vertices() if v.X > 0 and abs(math.atan2(v.Y, v.X)) < math.pi / 20)
    print(f"{name:5s} circle Ø {2 * r:6.2f}: tooth width {r * (max(angs) - min(angs)):.3f} mm")
fig, ax = plt.subplots(figsize=(5, 5))
x, y = zip(*(pts + pts[:1]))
ax.plot(x, y, "o-", ms=2, color="#6d3fc4", lw=1)
for name in ("pitch", "base", "root", "tip"):
    ax.add_patch(plt.Circle((0, 0), d[name] / 2, fill=False, ls="--", color="#999", lw=0.7))
ax.set_aspect("equal"); ax.set(xlim=(15, 23.5), ylim=(-4.25, 4.25))
fig.savefig("zoom.png", dpi=110, bbox_inches="tight")
