"""A parametric involute spur gear in CadQuery. Change the numbers at the top and run it again: STL for the 3D printer,
STEP for any CAD program."""
import math
import cadquery as cq

MODULE = 2.0            # mm: tooth size (pitch diameter / number of teeth)
TEETH = 20
WIDTH = 8.0             # mm: face width
BORE = 8.0              # mm: shaft hole
PRESSURE_ANGLE = 20.0   # degrees: the standard

def involute(rb, t):
    """A point on the involute of a circle of radius rb, at roll angle t (radians)."""
    return rb * (math.cos(t) + t * math.sin(t)), rb * (math.sin(t) - t * math.cos(t))

def gear_profile(m, z, alpha_deg, n=12):
    """The outline of the whole gear, as points: for each tooth, the root arc, one involute flank up to the tip, the other
    flank back down."""
    alpha = math.radians(alpha_deg)
    r = m * z / 2                      # pitch radius
    rb = r * math.cos(alpha)           # base radius: where the involute starts
    ra = r + m                         # tip (addendum) radius
    rf = r - 1.25 * m                  # root (dedendum) radius
    t_tip = math.sqrt((ra / rb) ** 2 - 1)
    beta = math.pi / (2 * z) + (math.tan(alpha) - alpha)       # half the tooth's angle at the base circle
    flank = [involute(rb, t_tip * i / n) for i in range(n + 1)]
    polar = [(math.hypot(x, y), math.atan2(y, x)) for x, y in flank]
    xy = lambda rr, a: (rr * math.cos(a), rr * math.sin(a))
    pts = []
    for k in range(z):
        c = 2 * math.pi * k / z                                  # this tooth's centre line
        a_start, a_end = c - beta, c + beta                      # where its flanks leave the base circle
        prev_end = c - 2 * math.pi / z + beta                    # where the previous tooth ended
        for i in range(1, 4):                                    # the root arc between the two teeth
            pts.append(xy(rf, prev_end + (a_start - prev_end) * i / 4))
        if rb > rf:
            pts.append(xy(rf, a_start))                          # straight down from the base circle to the root
        pts += [xy(rr, a_start + a) for rr, a in polar]           # one flank, base to tip
        pts += [xy(rr, a_end - a) for rr, a in reversed(polar)]   # the other flank, tip to base
        if rb > rf:
            pts.append(xy(rf, a_end))
    return pts, dict(pitch=2 * r, base=2 * rb, tip=2 * ra, root=2 * rf)

def spur_gear(m=MODULE, z=TEETH, width=WIDTH, bore=BORE, alpha=PRESSURE_ANGLE):
    pts, d = gear_profile(m, z, alpha)
    g = cq.Workplane("XY").polyline(pts).close().extrude(width)
    g = g.faces(">Z").workplane().hole(bore)
    return g, d

if __name__ == "__main__":
    g, d = spur_gear()
    print(f"module {MODULE} mm, {TEETH} teeth: pitch Ø {d['pitch']:.2f}, tip Ø {d['tip']:.2f}, root Ø {d['root']:.2f}, base Ø {d['base']:.2f} mm")
    bb = g.val().BoundingBox()
    print(f"bounding box {bb.xlen:.2f} x {bb.ylen:.2f} x {bb.zlen:.2f} mm, volume {g.val().Volume() / 1000:.2f} cm³")
    cq.exporters.export(g, "gear.stl")
    cq.exporters.export(g, "gear.step")
    print("saved gear.stl and gear.step")
