"""Detailed articulated 608-size deep-groove ball bearing."""
import math
import os
import sys
import bpy

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import v4lib as v4

v4.reset()

# 608 nominal envelope: 22 mm OD x 8 mm bore x 7 mm wide.
ZC = 0.0035
PITCH = 0.0078
BALL_R = 0.00165
N_BALLS = 8

steel = v4.metal("raceway_ground_steel", color=(0.68, 0.71, 0.74), roughness=0.42, brushed=True)
face_steel = v4.metal("ground_end_face_steel", color=(0.53, 0.56, 0.59), roughness=0.62, brushed=True)
raceway_steel = v4.metal("superfinished_raceway_steel", color=(0.82, 0.85, 0.89), roughness=0.19, brushed=False)
chrome = v4.metal("polished_bearing_chrome", color=(0.88, 0.90, 0.94), roughness=0.12, brushed=False)
dark_steel = v4.metal("dark_etched_steel", color=(0.24, 0.28, 0.32), roughness=0.32, brushed=False)
cage_metal = v4.metal("pressed_cage_steel", color=(0.50, 0.54, 0.58), roughness=0.40, brushed=True)
ball_witness = v4.mat("black_oxide_ball_witness", color=(0.025, 0.03, 0.035), metallic=0.08, roughness=0.62)

outer = v4.body("outer_raceway")
inner = v4.body("inner_race")
cage = v4.body("cage")

def ring_profile_mesh(name, profile, body, material, segments=192):
    """Closed radial/axial section revolved about Z."""
    # v4.lathe revolves a profile in the local R/Z plane. The closed section
    # creates one continuous turned steel ring with smooth circumferential faces.
    return v4.lathe(name, profile, loc=(0, 0, ZC), segments=segments, material=material, body=body)

def satin_end_faces(obj):
    """Give the truly planar end annuli a distinct, finely ground finish."""
    obj.data.materials.append(face_steel)
    idx = len(obj.data.materials) - 1
    for poly in obj.data.polygons:
        if all(abs(abs(obj.data.vertices[vi].co.z) - 0.00350) < 1e-7 for vi in poly.vertices):
            poly.material_index = idx

def polished_raceway(obj, rmin, rmax):
    """Assign a bright superfinished steel to the ball track, within the ring mesh."""
    obj.data.materials.append(raceway_steel)
    idx = len(obj.data.materials) - 1
    for poly in obj.data.polygons:
        coords = [obj.data.vertices[vi].co for vi in poly.vertices]
        radii = [math.hypot(v.x, v.y) for v in coords]
        if (all(-0.001651 <= v.z <= 0.001651 for v in coords)
                and all(rmin <= r <= rmax for r in radii)):
            poly.material_index = idx

# Outer ring section: square ground OD and a sampled, generous concave race groove.
outer_profile = [
    (0.01072, -0.00350), (0.01092, -0.00338), (0.01100, -0.00318),
    (0.01100,  0.00318), (0.01092,  0.00338), (0.01072,  0.00350),
    (0.00982,  0.00350), (0.00962,  0.00332), (0.00960,  0.00280),
    (0.00960,  0.00165),
]
# Race groove bottom is at the ball's outer pole radius. Interpolate a circular-ish
# race arc, smoothly opening to the shoulder on either side of the ball row.
for i in range(1, 17):
    z = 0.00165 * (1 - 2 * i / 17)
    # Mild concavity, sized to support the ball without pinching it.
    r = 0.00945 + 0.00023 * (z / 0.00165) ** 2
    outer_profile.append((r, z))
outer_profile += [
    (0.00960, -0.00165), (0.00960, -0.00280), (0.00962, -0.00332),
    (0.00982, -0.00350),
]
outer_obj = ring_profile_mesh("outer_raceway_turning", outer_profile, outer, steel)
polished_raceway(outer_obj, 0.00940, 0.00961)
satin_end_faces(outer_obj)

# Inner ring section: 8 mm through bore and convex outer profile forming its half
# of the deep groove. The contact crown reaches the inner pole radius of each ball.
inner_profile = [
    (0.00418, -0.00350), (0.00402, -0.00332), (0.00400, -0.00308),
    (0.00400,  0.00308), (0.00402,  0.00332), (0.00418,  0.00350),
    (0.00586,  0.00350), (0.00594,  0.00342), (0.00596,  0.00310),
    (0.00596,  0.00165),
]
for i in range(1, 17):
    z = 0.00165 * (1 - 2 * i / 17)
    r = 0.00615 - 0.00019 * (z / 0.00165) ** 2
    inner_profile.append((r, z))
inner_profile += [
    (0.00596, -0.00165), (0.00596, -0.00310), (0.00594, -0.00342), (0.00586, -0.00350),
]
inner_obj = ring_profile_mesh("inner_race_turning", inner_profile, inner, steel)
polished_raceway(inner_obj, 0.00594, 0.00616)
satin_end_faces(inner_obj)

# Subtle precision-ground edge bands on the exposed end faces, all within their
# parent race bodies and kept clear of the rolling elements.
for sign in (-1, 1):
    z = ZC + sign * 0.00348
    v4.torus(f"outer_face_finish_band_{sign}", 0.01025, 0.000035,
             loc=(0, 0, z), material=dark_steel, body=outer, segments=192, ring_segments=8)
mark = v4.mat("laser_marking", (0.20, 0.23, 0.27), metallic=0.45, roughness=0.42)
v4.text("bearing_designation", "608", 0.00046,
        loc=(0, -0.01027, ZC + 0.00350), rot=(0, 0, 0), extrude_depth=0.000018,
        material=mark, body=outer, on=None)

# Cage: two pressed, scalloped sheet-steel shells follow the ball row at its
# axial flanks. Each wave passes outside a ball and inside the inter-ball gap,
# leaving the radial rolling contacts visible. Eight rivets join the shells.
def pressed_wave_shell(name, zcenter):
    import bmesh
    bm = bmesh.new()
    samples = 256
    wave = 0.00148
    half_width = 0.00021
    half_thickness = 0.00010
    loops = []
    for i in range(samples):
        a = 2 * math.pi * i / samples
        r = PITCH + wave * math.cos(N_BALLS * a)
        loop = []
        # Rectangular sheet section: radial width by axial thickness.
        for dr, dz in ((-half_width, -half_thickness), (half_width, -half_thickness),
                       (half_width, half_thickness), (-half_width, half_thickness)):
            rr = r + dr
            loop.append(bm.verts.new((rr * math.cos(a), rr * math.sin(a), zcenter + dz)))
        loops.append(loop)
    for i in range(samples):
        here, nxt = loops[i], loops[(i + 1) % samples]
        for j in range(4):
            bm.faces.new((here[j], here[(j + 1) % 4], nxt[(j + 1) % 4], nxt[j]))
    bmesh.ops.recalc_face_normals(bm, faces=bm.faces)
    mesh = bpy.data.meshes.new(name)
    bm.to_mesh(mesh)
    bm.free()
    obj = bpy.data.objects.new(name, mesh)
    bpy.context.collection.objects.link(obj)
    v4.part(obj, cage)
    obj.data.materials.append(cage_metal)
    bevel = obj.modifiers.new("rolled_sheet_edges", "BEVEL")
    bevel.width = 0.000025
    bevel.segments = 2
    bevel.limit_method = "ANGLE"
    for poly in obj.data.polygons:
        poly.use_smooth = True
    obj.modifiers.new("sheet_normals", "WEIGHTED_NORMAL")
    return obj

for sign in (-1, 1):
    pressed_wave_shell(f"pressed_wave_shell_{sign}", ZC + sign * 0.00120)
for i in range(N_BALLS):
    a = 2 * math.pi * (i + 0.5) / N_BALLS
    r = PITCH - 0.00148
    x, y = r * math.cos(a), r * math.sin(a)
    v4.cylinder(f"cage_rivet_shank_{i:02d}", 0.00017, 0.00260,
                (x, y, ZC), segments=16, material=cage_metal, body=cage)
    for sign in (-1, 1):
        v4.sphere(f"cage_rivet_head_{i:02d}_{sign}", 0.00020,
                  (x, y, ZC + sign * 0.00120), segments=16,
                  material=cage_metal, body=cage)

# The root stays fixed. Both races/cage revolve about the true bearing axis.
v4.joint("inner_race_rotation", "continuous", outer, inner,
         origin=(0, 0, ZC), axis=(0, 0, 1))
v4.joint("cage_orbit", "continuous", outer, cage,
         origin=(0, 0, ZC), axis=(0, 0, 1))

for i in range(N_BALLS):
    a = 2 * math.pi * i / N_BALLS
    x, y = PITCH * math.cos(a), PITCH * math.sin(a)
    ball = v4.body(f"ball_{i:02d}")
    ball_obj = v4.sphere(f"chrome_ball_{i:02d}", BALL_R, (x, y, ZC),
                         segments=48, material=chrome, body=ball)
    # Small flush witness mark on the upper oblique surface makes axial spin
    # visible in the motion renders. Keep it away from the Z spin axis.
    ux, uy = math.cos(a), math.sin(a)
    witness_radius = BALL_R - 0.000045
    v4.sphere(f"ball_witness_{i:02d}", 0.00024,
              (x + ux * witness_radius * 0.45,
               y + uy * witness_radius * 0.45,
               ZC + witness_radius * math.sqrt(1 - 0.45 ** 2)), segments=16,
              material=ball_witness, body=ball)
    # In this radial, zero-contact-angle bearing, ball spin is parallel to the
    # bearing axis. The cage carries each ball center around that same axis.
    v4.joint(f"ball_spin_{i:02d}", "continuous", cage, ball,
             origin=(x, y, ZC), axis=(0, 0, 1))

v4.save(os.path.join(os.getcwd(), "asset.blend"))
print("saved asset.blend")
