"""Detailed single-bottom adjustable moldboard plow."""
import math
import os
import sys

import bpy
from mathutils import Vector

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

v4.reset()

# Materials: agricultural enamel, forged steel and the polished working surfaces.
red = v4.painted("implement_red_enamel", color=(0.52, 0.035, 0.025), roughness=0.27)
red_dark = v4.painted("pivot_housing_red", color=(0.31, 0.018, 0.012), roughness=0.32)
steel = v4.metal("tempered_plow_steel", color=(0.56, 0.60, 0.62), roughness=0.28, brushed=True)
bright = v4.metal("ground_edge_steel", color=(0.77, 0.79, 0.79), roughness=0.23, brushed=True)
dark = v4.metal("forged_dark_steel", color=(0.18, 0.20, 0.20), roughness=0.38, brushed=False)
zinc = v4.metal("zinc_hardware", color=(0.69, 0.72, 0.73), roughness=0.32, brushed=False)
soil = v4.mat("dried_furrow_soil", color=(0.19, 0.105, 0.052), roughness=0.9)
label = v4.mat("cream_enamel_label", color=(0.94, 0.82, 0.48), roughness=0.5)

hitch = v4.body("hitch")
frame = v4.body("frame")
blade = v4.body("blade")

# -- Hitch and vertical turntable (root body) -----------------------------------------
# Tongue is a substantial rectangular drawbar with a tractor drawbar clevis.
v4.box("drawbar_tongue", (0.12, 1.30, 0.12), (0, -0.78, 0.74), bevel=0.018, material=red, body=hitch)
v4.box("tongue_cap", (0.15, 0.13, 0.15), (0, -1.39, 0.74), bevel=0.022, material=red_dark, body=hitch)
for sx in (-1, 1):
    ear = v4.box(f"clevis_ear_{sx}", (0.025, 0.22, 0.22), (sx*0.083, -1.49, 0.74), bevel=0.012, material=red_dark, body=hitch)
    cutter = v4.cylinder(f"clevis_hole_cutter_{sx}", 0.026, 0.06, (sx*0.083, -1.54, 0.74),
                         rot=(0, math.pi/2, 0), material=dark, body=hitch)
    v4.boolean(ear, cutter)
v4.lathe("clevis_pin", [(0,0),(0.034,0),(0.034,0.020),(0.025,0.020),(0.025,0.235),
                          (0.034,0.235),(0.034,0.255),(0,0.255)],
         loc=(-0.115,-1.54,0.74), rot=(0,math.pi/2,0), material=bright, body=hitch)
v4.torus("clevis_lynch_pin_ring", 0.022, 0.004, (0.145,-1.54,0.74), rot=(0,math.pi/2,0), material=zinc, body=hitch)
# Twin height plates at the front of the tongue provide selectable clevis elevation.
for sx in (-1,1):
    height_plate = v4.box(f"hitch_height_plate_{sx}", (0.025,0.34,0.34), (sx*0.068,-1.18,0.74),
                          bevel=0.008, material=red_dark, body=hitch)
    for j,z in enumerate((0.62,0.74,0.86)):
        bore = v4.cylinder(f"hitch_height_bore_{sx}_{j}", 0.021, 0.06, (sx*0.068,-1.18,z),
                           rot=(0,math.pi/2,0), material=dark, body=hitch)
        v4.boolean(height_plate,bore)
# Longitudinal reinforcing bars tie the tongue into the turntable pedestal.
for sx in (-1, 1):
    v4.rod(f"tongue_gusset_{sx}", (sx*0.045,-1.22,0.68), (sx*0.12,-0.18,0.72), 0.018, material=red_dark, body=hitch)
# Pedestal and large kingpin plates. The lower and upper plates straddle the frame hub.
v4.box("turntable_pedestal", (0.30, 0.30, 0.22), (0, -0.12, 0.81), bevel=0.035, material=red_dark, body=hitch)
v4.cylinder("kingpin_lower_washer", 0.115, 0.025, (0, -0.12, 0.926), material=bright, body=hitch)
v4.cylinder("kingpin_lower_boss", 0.074, 0.105, (0, -0.12, 0.99), material=dark, body=hitch)
v4.cylinder("kingpin_upper_washer", 0.105, 0.018, (0, -0.12, 1.045), material=zinc, body=hitch)
v4.cylinder("kingpin_cap", 0.045, 0.035, (0, -0.12, 1.072), material=dark, body=hitch)
v4.box("turntable_side_guard_L", (0.018, 0.31, 0.14), (-0.16, -0.12, 0.89), bevel=0.009, material=red, body=hitch)
v4.box("turntable_side_guard_R", (0.018, 0.31, 0.14), (0.16, -0.12, 0.89), bevel=0.009, material=red, body=hitch)
# A broad captive clamp bar at the kingpin retains the selected beam angle.
v4.box("turntable_clamp_bar", (0.30,0.055,0.028), (0, -0.12, 1.066), bevel=0.012, material=dark, body=hitch)
v4.cylinder("turntable_clamp_bolt", 0.032, 0.075, (0, -0.12, 1.104), material=zinc, body=hitch)
v4.cylinder("turntable_clamp_handle_hub", 0.026, 0.04, (0, -0.12, 1.154), material=dark, body=hitch)
v4.rod("turntable_clamp_handle", (0,-0.12,1.154), (0.19,-0.12,1.19), 0.012, material=zinc, body=hitch)
v4.sphere("turntable_handle_grip", 0.025, (0.205,-0.12,1.193), material=label, body=hitch)

# Perforated angle quadrant with a captive setting pin. It sits above the rotating hub,
# making the indexed yaw setting legible while retaining clearance through the full sweep.
qverts, qfaces = [], []
qsteps = 32
for i in range(qsteps + 1):
    a = math.radians(-52 + 104*i/qsteps)
    for z in (1.145, 1.165):
        for r in (0.205, 0.315):
            qverts.append((r*math.sin(a), -0.12+r*math.cos(a), z))
for i in range(qsteps):
    b = 4*i
    # inner top, outer top, inner bottom, outer bottom
    qfaces.extend([(b+1,b+5,b+7,b+3), (b,b+2,b+6,b+4),
                   (b,b+4,b+5,b+1), (b+2,b+3,b+7,b+6)])
qfaces.extend([(0,1,3,2), (qsteps*4,qsteps*4+2,qsteps*4+3,qsteps*4+1)])
qmesh = bpy.data.meshes.new("turntable_quadrant_mesh")
qmesh.from_pydata(qverts, [], qfaces)
qmesh.update()
quadrant = bpy.data.objects.new("perforated_yaw_quadrant", qmesh)
bpy.context.collection.objects.link(quadrant)
v4.part(quadrant, hitch)
quadrant.data.materials.append(dark)
for i, deg in enumerate((-40,-30,-20,-10,0,10,20,30,40)):
    a = math.radians(deg)
    x, y = 0.26*math.sin(a), -0.12+0.26*math.cos(a)
    hole = v4.cylinder(f"quadrant_bore_{i}", 0.013, 0.06, (x,y,1.155), material=dark, body=hitch)
    v4.boolean(quadrant, hole)
qbev = quadrant.modifiers.new("quadrant_debur", "BEVEL")
qbev.width = 0.002
qbev.segments = 2
for sx, deg in ((-1,-48),(1,48)):
    a = math.radians(deg)
    target = (0.26*math.sin(a), -0.12+0.26*math.cos(a), 1.145)
    v4.rod(f"quadrant_stay_{sx}", (sx*0.15,-0.12,0.94), target, 0.014, material=red_dark, body=hitch)
# Squared end stops terminate the indexed ±28 degree working sector.
for sx,deg in ((-1,-48),(1,48)):
    a=math.radians(deg)
    x,y=0.26*math.sin(a),-0.12+0.26*math.cos(a)
    v4.box(f"yaw_arc_stop_{sx}", (0.055,0.065,0.055), (x,y,1.19), bevel=0.010, material=red_dark, body=hitch)
# Raised index pin is parked directly over the selected centre setting hole.
v4.cylinder("yaw_setting_pin", 0.011, 0.065, (0,-0.12+0.26,1.195), material=bright, body=hitch)
v4.cylinder("yaw_pin_collar", 0.024, 0.012, (0,-0.12+0.26,1.162), material=zinc, body=hitch)
v4.rod("yaw_pin_pull_handle", (0,-0.12+0.26,1.225), (0.075,-0.12+0.26,1.245), 0.008, material=zinc, body=hitch)
v4.sphere("yaw_pin_grip", 0.014, (0.082,-0.12+0.26,1.247), material=label, body=hitch)

# -- Swinging frame -------------------------------------------------------------------
# Main beam, flanged root hub, and reinforcing diagonal struts.
v4.box("plow_beam_tube", (0.15, 0.96, 0.15), (0, 0.36, 0.69), bevel=0.018, material=red, body=frame)
v4.cylinder("frame_turntable_hub", 0.13, 0.20, (0, -0.12, 0.94), material=red_dark, body=frame)
v4.cylinder("frame_hub_bearing", 0.076, 0.17, (0, -0.12, 0.85), material=dark, body=frame)
for sx in (-1, 1):
    v4.rod(f"beam_gusset_{sx}", (sx*0.055, -0.08, 0.69), (sx*0.18, 0.46, 0.63), 0.022, material=red_dark, body=frame)
# Rear standard saddle / transverse trunnion clevis.
v4.rod("hinge_support_L", (-0.07,0.74,0.66), (-0.13,0.74,0.54), 0.034, material=red_dark, body=frame)
v4.rod("hinge_support_R", (0.07,0.74,0.66), (0.13,0.74,0.54), 0.034, material=red_dark, body=frame)
v4.box("hinge_cheek_front", (0.075, 0.18, 0.17), (-0.20, 0.74, 0.55), bevel=0.018, material=red, body=frame)
v4.box("hinge_cheek_back", (0.075, 0.18, 0.17), (0.20, 0.74, 0.55), bevel=0.018, material=red, body=frame)
v4.cylinder("blade_hinge_pin", 0.034, 0.48, (0, 0.74, 0.54), rot=(0, math.pi/2, 0), material=bright, body=frame)
for sx in (-1, 1):
    v4.cylinder(f"hinge_pin_cap_{sx}", 0.048, 0.025, (sx*0.245, 0.74, 0.54), rot=(0, math.pi/2, 0), material=dark, body=frame)
    v4.cylinder(f"hinge_grease_nipple_{sx}", 0.008, 0.024, (sx*0.263, 0.74, 0.54), rot=(0, math.pi/2, 0), material=zinc, body=frame)

# -- Tilting blade carrier and working surfaces ---------------------------------------
# Cast standard runs from the trunnion down to the share and broadens into the moldboard.
v4.rod("plow_standard_core", (0, 0.74, 0.54), (0, 0.83, 0.20), 0.045, material=red_dark, body=blade)
v4.box("standard_foot", (0.15, 0.17, 0.11), (0, 0.84, 0.20), bevel=0.022, material=red, body=blade)
# One-piece cast frog / standard: broadens beneath the trunnion and spreads into the share heel.
frog_profile = [(0.67,0.57),(0.78,0.55),(0.82,0.46),(0.84,0.35),(0.98,0.27),
                (0.97,0.20),(0.85,0.16),(0.74,0.22),(0.70,0.38)]
fverts = [(x,y,z) for x in (-0.072,0.072) for y,z in frog_profile]
nf = len(frog_profile)
ffaces = [tuple(range(nf)), tuple(range(nf,2*nf))[::-1]]
for i in range(nf):
    j=(i+1)%nf
    ffaces.append((i,j,nf+j,nf+i))
fmesh=bpy.data.meshes.new("cast_frog_standard_mesh")
fmesh.from_pydata(fverts,[],ffaces)
fmesh.update()
frog=bpy.data.objects.new("cast_frog_standard",fmesh)
bpy.context.collection.objects.link(frog)
v4.part(frog,blade)
frog.data.materials.append(red_dark)
fbev=frog.modifiers.new("cast_fillet_edges","BEVEL")
fbev.width=0.012
fbev.segments=3
for side in (-1,1):
    for j,(y,z) in enumerate(((0.77,0.45),(0.83,0.34),(0.91,0.25))):
        v4.cylinder(f"frog_side_bolt_{side}_{j}",0.012,0.020,(side*0.076,y,z),
                    rot=(0,math.pi/2,0),material=zinc,body=blade)
for sx in (-1, 1):
    v4.cylinder(f"blade_trunnion_{sx}", 0.043, 0.13, (sx*0.105, 0.74, 0.54), rot=(0, math.pi/2, 0), material=red_dark, body=blade)
# A vertical threaded pitch screw and hand nut sit on the carrier's hinge arm as its
# retained fine-adjuster. The screw remains part of the blade assembly.
v4.box("pitch_screw_foot", (0.075,0.11,0.07), (0.15,0.74,0.575), bevel=0.012, material=red_dark, body=blade)
v4.rod("pitch_adjuster_threaded_shaft", (0.15,0.74,0.59), (0.15,0.74,0.88), 0.012, material=dark, body=blade)
for i in range(6):
    v4.torus(f"pitch_screw_thread_{i}", 0.012, 0.0025, (0.15,0.74,0.62+i*0.035), material=zinc, body=blade)
v4.cylinder("pitch_screw_lock_nut", 0.030, 0.035, (0.15,0.74,0.755), material=zinc, body=blade)
v4.cylinder("pitch_screw_jam_nut", 0.026, 0.022, (0.15,0.74,0.785), material=dark, body=blade)
v4.cylinder("pitch_adjuster_handwheel", 0.045, 0.025, (0.15,0.74,0.84), rot=(0,math.pi/2,0), material=bright, body=blade)
v4.rod("pitch_adjuster_handle", (0.15,0.74,0.84), (0.15,0.83,0.84), 0.007, material=zinc, body=blade)
v4.sphere("pitch_adjuster_grip", 0.014, (0.15,0.84,0.84), material=label, body=blade)

# Curved, twisted moldboard shell: narrow at the shin, broadening and curling outward
# as it rises to carry the furrow slice over and aside.
def mold_surface(u, v, offset=0.0):
    width = 0.30 + 0.42*u
    twist = 1.20*u
    x = 0.20*u + v*width*math.cos(twist)
    y = 0.80 + 0.26*u + 0.11*math.sin(math.pi*u) + v*width*math.sin(twist) + 0.055*(2*v)**2*u
    z = 0.27 + 0.67*u + 0.055*v*math.sin(math.pi*u)
    return (x, y+offset, z)

verts, faces = [], []
nz, nx = 18, 12
for iz in range(nz + 1):
    u = iz / nz
    for ix in range(nx + 1):
        v = ix / nx - 0.5
        verts.append(mold_surface(u,v))
for iz in range(nz):
    for ix in range(nx):
        a = iz*(nx+1)+ix
        faces.append((a, a+1, a+nx+2, a+nx+1))
mesh = bpy.data.meshes.new("moldboard_swept_sheet_mesh")
mesh.from_pydata(verts, [], faces)
mesh.update()
ob = bpy.data.objects.new("curved_moldboard", mesh)
bpy.context.collection.objects.link(ob)
v4.part(ob, blade)
ob.data.materials.append(steel)
solid = ob.modifiers.new("formed_sheet_thickness", "SOLIDIFY")
solid.thickness = 0.024
solid.offset = 0
bev = ob.modifiers.new("rolled_sheet_edges", "BEVEL")
bev.width = 0.012
bev.segments = 3
for p in ob.data.polygons:
    p.use_smooth = True

# Pointed, crowned share. Its swept cutting wings rise from the toe into the board's heel.
outline = [(-0.31,0.80,0.238),(-0.29,0.94,0.252),(-0.16,1.09,0.270),
           (0.0,1.27,0.265),(0.16,1.09,0.270),(0.29,0.94,0.252),(0.31,0.80,0.238)]
center = (0.0,0.96,0.292)
sverts = outline + [center] + [(x,y,z-0.045) for x,y,z in outline] + [(0.0,0.96,0.247)]
faces = []
ci, bi, bc = 7, 8, 15
for i in range(7):
    j = (i+1)%7
    faces.append((ci,i,j))
    faces.append((bc,bi+j,bi+i))
    faces.append((i,bi+i,bi+j,j))
smesh = bpy.data.meshes.new("forged_share_wedge_mesh")
smesh.from_pydata(sverts, [], faces)
smesh.update()
share = bpy.data.objects.new("replaceable_plow_share", smesh)
bpy.context.collection.objects.link(share)
v4.part(share, blade)
share.data.materials.append(bright)
share.data.materials.append(soil)
for i,p in enumerate(share.data.polygons):
    # A few integrated dark soil scuffs at the heel and wing roots.
    if i in (2,5,8,11):
        p.material_index = 1
share_bevel = share.modifiers.new("share_edge_break", "BEVEL")
share_bevel.width = 0.008
share_bevel.segments = 2
# Separate replaceable shin point laps onto the share toe.
shin = v4.extrude("replaceable_shin_point", [(-0.075,1.16),(0.075,1.16),(0.0,1.365)], 0.060,
                   loc=(0,0,0.218), bevel=0.012, material=steel, body=blade)
v4.rod("swept_hardfaced_cutting_edge_L", (-0.29,0.94,0.256), (-0.16,1.09,0.276), 0.009, material=steel, body=blade)
v4.rod("swept_hardfaced_cutting_edge_R", (0.16,1.09,0.276), (0.29,0.94,0.256), 0.009, material=steel, body=blade)
# Countersunk frog bolts along the moldboard heel, following its twisted lower skin.
for i,(u,v) in enumerate(((0.10,-0.34),(0.10,0.34),(0.20,-0.36),(0.20,0.36),(0.30,-0.38),(0.30,0.38))):
    x,y,z = mold_surface(u,v,offset=-0.006)
    v4.cylinder(f"frog_moldboard_bolt_{i}", 0.013, 0.016, (x,y,z), rot=(math.pi/2,0,0), material=zinc, body=blade)

# Landside is one forged wear bar, joined to the frog by a stout diagonal web.
v4.rod("landside_frog_bridge", (-0.33,0.73,0.26), (-0.04,0.79,0.31), 0.030, material=red_dark, body=blade)
landside = v4.box("landside_wear_bar", (0.085,0.56,0.11), (-0.36,0.73,0.255), bevel=0.009, material=bright, body=blade)
for i,y in enumerate((0.52,0.66,0.80,0.94)):
    head = v4.cylinder(f"landside_frog_bolt_{i}", 0.014, 0.045, (-0.39,y,0.27),
                       rot=(0,math.pi/2,0), material=dark, body=blade)
    v4.boolean(landside, head, op="UNION")

# Share faces retain small earth stained areas while its sharpened edge stays bright.
# Small maker plate on the beam, with lettering snapped to the outward face.
plate = v4.box("maker_plate", (0.105,0.004,0.052), (0.078,0.33,0.77), bevel=0.004, material=dark, body=frame)
v4.text("maker_mark", "FIELD 14", 0.018, loc=(0.078,0.33,0.797), rot=(math.pi/2,0,0), on=plate, material=label, body=frame)

# Fasteners on the beam flanges.
for sx in (-1,1):
    for y in (-0.02, 0.28, 0.57):
        v4.cylinder(f"frame_service_bolt_{sx}_{y}", 0.012, 0.008, (sx*0.079,y,0.69), rot=(0,math.pi/2,0), material=zinc, body=frame)

# Physical articulated structure.
v4.joint("frame_yaw", "revolute", hitch, frame, origin=(0,-0.12,0.85), axis=(0,0,1),
         limits=(-math.radians(28), math.radians(28)))
v4.joint("blade_tilt", "revolute", frame, blade, origin=(0,0.74,0.54), axis=(1,0,0),
         limits=(-math.radians(12), math.radians(12)))

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