"""Detailed articulated residential robotic lawn mower. Run with Blender -b --python build.py."""
import math, os, sys
import bpy, bmesh
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import v4lib as v4

v4.reset()
# Injection molded shell, rubber, and metal finishes.
orange = v4.painted('safety_orange_molded_shell', (0.92, 0.25, 0.045), roughness=0.27, coat=0.45)
orange_dark = v4.plastic('orange_lower_trim', (0.48, 0.105, 0.025), roughness=0.38)
charcoal = v4.plastic('graphite_chassis', (0.075, 0.085, 0.085), roughness=0.48)
underside_grey = v4.plastic('matte_grey_deck_underside', (0.23, 0.25, 0.26), roughness=0.68)
black = v4.plastic('black_panel', (0.018, 0.022, 0.022), roughness=0.3)
rubber = v4.rubber('tire_rubber', (0.035, 0.038, 0.036))
bumper_rubber = v4.rubber('soft_black_bumper', (0.045, 0.050, 0.052))
steel = v4.metal('satin_stainless', (0.68, 0.7, 0.69), roughness=0.3, brushed=True)
darksteel = v4.metal('dark_anodized_aluminum', (0.17, 0.19, 0.19), roughness=0.32)
cutter_alloy = v4.metal('cutter_carrier_anodized_alloy', (0.82, 0.61, 0.24), roughness=0.32)
red = v4.plastic('emergency_stop_red', (0.86, 0.025, 0.018), roughness=0.25)
white = v4.plastic('warm_white_marking', (0.9, 0.88, 0.78), roughness=0.45)
green = v4.emissive('status_green_led', (0.04, 0.85, 0.13), strength=2.4)
blue = v4.emissive('status_blue_led', (0.08, 0.4, 0.95), strength=2.0)

# Overall envelope: low shell about 420 mm long; tire-to-tire width about 560 mm.
chassis = v4.body('chassis')

# Rounded, tapered hood profile.  Its low sides stay inside the drive tires; the
# upper shoulder widens above tire height to give the familiar mower overhang.
def lofted_shell(name, lower, upper, z0, zmid, ztop, body, material):
    bm=bmesh.new(); n=len(lower)
    rings=[]
    crown=[(x*.88,y*.88) for x,y in upper]
    for outline,z in ((lower,z0),(lower,zmid),(upper,ztop),(crown,ztop+.010)):
        rings.append([bm.verts.new((x,y,z)) for x,y in outline])
    bm.faces.new(list(reversed(rings[0])))
    bm.faces.new(rings[-1])
    for k in range(len(rings)-1):
        a,b=rings[k],rings[k+1]
        for i in range(n): bm.faces.new((a[i],a[(i+1)%n],b[(i+1)%n],b[i]))
    bmesh.ops.recalc_face_normals(bm,faces=bm.faces)
    obj=v4._mesh_obj(name,bm)
    v4._finish(obj,body,material,bevel=.008,segments=4,smooth=True)
    return obj

# Compact molded perimeter, narrow at the nose and broad at the rear wheel wells.
def shorten_nose(outline):
    # Pull the leading lower-shell facets back together to open a guarded
    # sightline to the cutter while keeping the loft rings aligned.
    return [(x, y+.040 if y < -.09 else y) for x,y in outline]
hood_lower=shorten_nose([(-.120,-.230),(.120,-.230),(.155,-.190),(.174,-.110),(.175,.070),(.175,.145),(.155,.185),(-.155,.185),(-.175,.145),(-.175,.070),(-.174,-.110),(-.155,-.190)])
hood_upper=shorten_nose([(-.135,-.230),(.135,-.230),(.180,-.190),(.220,-.110),(.240,.070),(.240,.145),(.220,.190),(-.220,.190),(-.240,.145),(-.240,.070),(-.220,-.110),(-.180,-.190)])

# Low integrated cutting-deck skirt: slotted guard reveals the cutter while
# keeping a low perimeter rail around it. The front opening has a protective grille.
for side in (-1,1):
    # Split the upper band around a central inspection window aligned to the cutter.
    v4.box('low_side_guard_front_band_'+str(side),(.034,.030,.052),(side*.164,-.090,.092),bevel=.004,material=charcoal,body=chassis)
    v4.box('low_side_guard_rear_band_'+str(side),(.034,.160,.052),(side*.164,.105,.092),bevel=.004,material=charcoal,body=chassis)
    # Three stout supports leave a broad central inspection slot over the disc.
    for i,y in enumerate((-.095,.080,.145)):
        v4.box('low_side_guard_rib_%d_%d'%(side,i),(.034,.012,.038),(side*.164,y,.047),bevel=.002,material=charcoal,body=chassis)
    # Slit bars sit high in the guard band; the lower inspection window stays open to the cutter.
    for i,z in enumerate((.074,.081)):
        v4.box('low_side_guard_slot_bar_%d_%d'%(side,i),(.034,.290,.003),(side*.164,.040,z),bevel=.001,material=darksteel,body=chassis)
v4.box('low_rear_deck_skirt',(.330,.040,.092),(0,.160,.072),bevel=.009,material=charcoal,body=chassis)
# U-shaped belly pan leaves the center cutter visible from the open front underside.
pan_outline=[(-.145,-.125),(-.115,-.125),(-.115,.095),(.115,.095),(.115,-.125),(.145,-.125),(.170,-.075),(.170,.125),(.145,.190),(-.145,.190),(-.170,.125),(-.170,-.075)]
pan=v4.extrude('lower_chassis_belly_pan',pan_outline,.012,loc=(0,0,.051),bevel=.004,material=underside_grey,body=chassis)
# Front safety grille retains a skirt perimeter but opens a large sightline to the disc face.
v4.box('front_blade_guard_top_rail',(.240,.012,.010),(0,-.132,.113),bevel=.003,material=charcoal,body=chassis)
# Keep the lower mouth open so the protected rotating blades can be seen.
for side in (-1,1):
    v4.box('front_blade_guard_end_post_'+str(side),(.012,.012,.092),(side*.114,-.132,.072),bevel=.003,material=charcoal,body=chassis)
battery=v4.box('battery_bay',(.205,.160,.052),(0,.075,.089),bevel=.009,material=charcoal,body=chassis)
# Raised caster bridges are above the tire crowns; their tips stop 1 mm short of each swivel stem.
v4.box('caster_bridge_crossmember',(.320,.018,.010),(0,-.0465,.090),bevel=.002,material=darksteel,body=chassis)
for side in (-1,1):
    v4.box('caster_bridge_arm_'+str(side),(.018,.1145,.010),(side*.145,-.11275,.090),bevel=.002,material=darksteel,body=chassis)
# Thin fixed spindle bridge attaches at the open pan edges and clears the rotating hub by 1 mm.
v4.box('fixed_cutter_spindle_bridge',(.230,.010,.003),(0,-.020,.0505),bevel=.0005,material=darksteel,body=chassis)
# Motor pods and short axle stubs terminate 2 mm before the independent wheel bodies.
for side in (-1,1):
    x=side*.148
    v4.box('traction_motor_pod_'+str(side),(.050,.070,.044),(x,.105,.083),bevel=.009,material=darksteel,body=chassis)
    v4.rod('drive_axle_stub_'+str(side),(side*.174,.105,.078),(side*.186,.105,.078),.006,material=steel,body=chassis)
    v4.cylinder('drive_bearing_boss_'+str(side),.027,.006,(side*.184,.105,.078),rot=(0,math.pi/2,0),material=darksteel,body=chassis)
# Front caster pivots connect directly through their revolute joints.
# Rear charging contacts are mounted directly on the rear skirt face.
for side in (-1,1):
    x=side*.105
    v4.box('charging_contact_pad_'+str(side),(.034,.018,.030),(x,.178,.090),bevel=.003,material=black,body=chassis)
    v4.box('charging_contact_'+str(side),(.021,.004,.018),(x,.189,.090),bevel=0,material=steel,body=chassis)
# Discrete rear cooling slots on the upper exposed battery-bay wall.
v4.box('rear_cooling_grille',(.100,.003,.012),(0,.169,.111),bevel=.001,material=black,body=chassis)
# Lower chassis side vents and fasteners make the deck and battery housing read as serviceable.
for side in (-1,1):
    v4.box('side_vent_gasket_'+str(side),(.004,.070,.028),(side*.182,.030,.091),bevel=.003,material=black,body=chassis)
    for i in range(4):
        v4.box('side_vent_louver_%d_%d'%(side,i),(.002,.054,.002),(side*.185,.030,.081+i*.006),bevel=.0005,material=steel,body=chassis)
    for i,y in enumerate((-.080,.145)):
        v4.cylinder('deck_service_fastener_%d_%d'%(side,i),.003,.003,(side*.183,y,.108),rot=(0,math.pi/2,0),segments=16,material=steel,body=chassis)

# Rear traction wheels, tread blocks, hubs, and decorative wheel bolts.
def drive_wheel(name, s):
    b=v4.body(name)
    x=s*.214; yc=.105; zc=.078
    v4.cylinder(name+'_tire',.075,.052,(x,yc,zc),rot=(0,math.pi/2,0),segments=64,material=rubber,body=b)
    v4.cylinder(name+'_hub',.047,.054,(x,yc,zc),rot=(0,math.pi/2,0),segments=48,material=darksteel,body=b)
    v4.cylinder(name+'_hub_face',.032,.003,(s*.242,yc,zc),rot=(0,math.pi/2,0),material=steel,body=b)
    v4.cylinder(name+'_hub_cap',.018,.004,(s*.244,yc,zc),rot=(0,math.pi/2,0),material=charcoal,body=b)
    # Individually molded chunky lugs on both shoulders, radial around the tire.
    for side in (-1,1):
      xx=x+side*.020
      for i in range(24):
        a=2*math.pi*i/24
        yy=yc+.073*math.sin(a); zz=zc+.073*math.cos(a)
        v4.box(name+'_tread_%d_%d'%(side,i),(.012,.020,.009),(xx,yy,zz),rot=(a*.22,0,0),bevel=.002,material=rubber,body=b)
    for i in range(6):
      a=2*math.pi*i/6
      yy=yc+.024*math.sin(a); zz=zc+.024*math.cos(a)
      v4.cylinder(name+'_lug_bolt_'+str(i),.0032,.002,(s*.246,yy,zz),rot=(0,math.pi/2,0),segments=16,material=steel,body=b)
    v4.joint(name+'_axle','continuous',chassis,b,origin=(x,yc,zc),axis=(1,0,0))

drive_wheel('left_drive_wheel',-1)
drive_wheel('right_drive_wheel',1)

# Two small front casters swivel freely and spin on separate horizontal axles.
for side,label in [(-1,'left'),(1,'right')]:
    fork=v4.body(label+'_caster_fork')
    x=side*.145; y=-.170; wz=.035
    # Coaxial spindle has a 1 mm running gap from the fixed chassis boss.
    v4.cylinder(label+'_caster_swivel_stem',.006,.014,(x,y,.077),material=steel,body=fork)
    v4.cylinder(label+'_caster_bearing_housing',.014,.010,(x,y,.079),material=darksteel,body=fork)
    v4.torus(label+'_caster_bearing_seal',.011,.0015,(x,y,.084),material=steel,body=fork)
    v4.rod(label+'_fork_yoke',(x-.021,y,.073),(x+.021,y,.073),.004,material=darksteel,body=fork)
    # Fork cheeks sit just outside the tire sidewalls; axle stubs stop at the side faces.
    v4.rod(label+'_fork_leg_left',(x-.021,y,.073),(x-.021,y,wz),.003,material=darksteel,body=fork)
    v4.rod(label+'_fork_leg_right',(x+.021,y,.073),(x+.021,y,wz),.003,material=darksteel,body=fork)
    v4.joint(label+'_caster_swivel','continuous',chassis,fork,origin=(x,y,.084),axis=(0,0,1))
    wheel=v4.body(label+'_caster_wheel')
    v4.cylinder(label+'_caster_tire',.032,.034,(x,y,wz),rot=(0,math.pi/2,0),segments=48,material=rubber,body=wheel)
    v4.cylinder(label+'_caster_hub',.018,.030,(x,y,wz),rot=(0,math.pi/2,0),material=darksteel,body=wheel)
    v4.cylinder(label+'_caster_cap',.009,.002,(x+side*.012,y,wz),rot=(0,math.pi/2,0),material=steel,body=wheel)
    v4.torus(label+'_caster_sidewall_ring',.024,.0015,(x+side*.011,y,wz),rot=(0,math.pi/2,0),material=darksteel,body=wheel)
    v4.joint(label+'_caster_spin','continuous',fork,wheel,origin=(x,y,wz),axis=(1,0,0))

# Low powered cutter: fully inside the deck perimeter; carrier underside 32 mm above ground.
disc=v4.body('cutting_disc')
v4.cylinder('rotating_blade_carrier',.100,.006,(0,-.020,.035),segments=64,material=cutter_alloy,body=disc)
# Rolled perimeter on the disc makes the guarded cutter legible from low side views.
v4.torus('carrier_rolled_rim',.094,.006,(0,-.020,.0365),segments=64,ring_segments=12,material=cutter_alloy,body=disc)
v4.cylinder('carrier_top_hub',.027,.010,(0,-.020,.043),segments=48,material=darksteel,body=disc)
v4.torus('motor_hub_trim_ring',.023,.0015,(0,-.020,.047),material=steel,body=disc)
v4.cylinder('spindle_nut',.010,.004,(0,-.020,.046),segments=6,material=darksteel,body=disc)
for i in range(3):
    a=2*math.pi*i/3
    px=.085*math.cos(a); py=-.020+.085*math.sin(a)
    # Pivoting knife tabs mount on the carrier underside and overlap its lower face.
    v4.cylinder('knife_pivot_'+str(i),.006,.003,(px,py,.034),segments=24,material=steel,body=disc)
    tang=a+math.pi/2
    v4.box('replaceable_cutting_blade_'+str(i),(.085,.022,.006),(px+.0425*math.cos(tang),py+.0425*math.sin(tang),.0325),rot=(0,0,tang),bevel=.0009,material=steel,body=disc)
    v4.cylinder('knife_pivot_rivet_'+str(i),.0025,.0015,(px,py,.0303),segments=16,material=darksteel,body=disc)
v4.joint('blade_drive','continuous',chassis,disc,origin=(0,-.020,.035),axis=(0,0,1))

# Low tapered mower hood, rear-hinged; body profile flares over the drive wheels above tire height.
cover=v4.body('cover')
lofted_shell('upper_molded_hood',hood_lower,hood_upper,.118,.153,.176,cover,orange)
# The stepped inner crown lifts the center of the shell; its low side carries a fine parting line.
for side in (-1,1):
    v4.box('hood_parting_seam_'+str(side),(.002,.170,.0015),(side*.175,-.005,.146),bevel=.0005,material=orange_dark,body=cover)
# Recessed slotted cooling fields and a small molded model badge on the sculpted crown.
for side in (-1,1):
    v4.box('hood_vent_well_'+str(side),(.070,.026,.003),(side*.105,.090,.1875),bevel=.008,material=black,body=cover)
    for i in range(4):
        v4.box('hood_vent_slot_%d_%d'%(side,i),(.054,.0015,.0015),(side*.105,.081+i*.006,.18975),bevel=.0004,material=steel,body=cover)
v4.box('model_badge',(.082,.016,.003),(0,-.079,.1875),bevel=.003,material=black,body=cover)
v4.text('model_badge_legend','R-42',.008,loc=(-.016,-.082,.1892),extrude_depth=.0005,material=white,body=cover)
# A prominent cutting-height selector, separate from the safety/control panel.
v4.cylinder('cut_height_dial_base',.023,.006,(0,.074,.189),material=black,body=cover)
v4.cylinder('cut_height_dial_knob',.014,.020,(0,.074,.202),material=orange_dark,body=cover)
v4.cylinder('cut_height_dial_cap',.006,.003,(0,.074,.2135),material=steel,body=cover)
v4.box('cut_height_pointer',(.003,.012,.002),(0,.062,.214),bevel=.0005,material=white,body=cover)
# Recessed operator panel, safety stop, START/STOP controls, status lamps, and rain sensor.
v4.box('control_panel_gasket',(.102,.070,.007),(0,-.008,.1895),bevel=.010,material=black,body=cover)
v4.box('control_panel_glass',(.084,.052,.003),(0,-.008,.1945),bevel=.007,material=darksteel,body=cover)
v4.box('control_panel_display',(.038,.012,.0015),(0,.004,.19675),bevel=.002,material=black,body=cover)
for i in range(3):
    v4.box('display_status_bar_'+str(i),(.024-i*.004,.001,.001),(0,.001+i*.003,.198),bevel=.0003,material=green,body=cover)
for i,(x,mat) in enumerate([(-.025,green),(0,blue),(.025,green)]):
    v4.cylinder('status_led_'+str(i),.003,.0015,(x,-.028,.1965),segments=24,material=mat,body=cover)
v4.cylinder('emergency_stop_base',.016,.008,(0,-.008,.198),material=red,body=cover)
v4.cylinder('emergency_stop_cap',.012,.008,(0,-.008,.205),radius_top=.010,material=red,body=cover)
v4.box('start_button',(.020,.012,.004),(-.027,-.025,.197),bevel=.001,material=green,body=cover)
v4.box('stop_button',(.020,.012,.004),(.027,-.025,.197),bevel=.001,material=red,body=cover)
v4.cylinder('rain_sensor_gasket',.014,.004,(0,.125,.189),material=black,body=cover)
v4.cylinder('rain_sensor_lens',.010,.003,(0,.125,.1925),material=blue,body=cover)
# Short GPS/RTK antenna mast and low rounded rubber collision bumper.
v4.cylinder('rtk_mast_gasket',.014,.004,(.075,.151,.188),material=black,body=cover)
v4.rod('rtk_antenna_mast',(.075,.151,.190),(.075,.151,.222),.003,material=darksteel,body=cover)
v4.cylinder('rtk_antenna_puck',.012,.008,(.075,.151,.226),material=black,body=cover)
v4.cylinder('rtk_antenna_cap',.006,.002,(.075,.151,.231),material=white,body=cover)
# Front ultrasonic collision strip, lower than the nose seam, with inset proximity lenses.
v4.box('front_collision_bumper',(.200,.005,.016),(0,-.1915,.124),bevel=.006,material=bumper_rubber,body=cover)
for i,x in enumerate((-.064,0,.064)):
    v4.cylinder('front_collision_sensor_gasket_'+str(i),.008,.002,(x,-.1955,.124),rot=(math.pi/2,0,0),material=darksteel,body=cover)
    v4.cylinder('front_collision_sensor_lens_'+str(i),.005,.001,(x,-.197,.124),rot=(math.pi/2,0,0),material=blue,body=cover)
# Two metal charging pads sit at the bumper corners, clear of the three sensor lenses.
for side in (-1,1):
    v4.box('front_charge_contact_plate_'+str(side),(.024,.002,.008),(side*.085,-.1955,.122),bevel=.002,material=darksteel,body=cover)
    v4.box('front_charge_contact_pad_'+str(side),(.014,.001,.005),(side*.085,-.197,.122),bevel=.001,material=steel,body=cover)
# Rear lift grip and paired service hinge hardware.
v4.box('rear_hood_grip',(.072,.018,.009),(0,.151,.1905),bevel=.004,material=orange_dark,body=cover)
for side in (-1,1):
    v4.cylinder('cover_hinge_knuckle_'+str(side),.006,.036,(side*.135,.180,.164),rot=(0,math.pi/2,0),material=darksteel,body=cover)
    v4.box('cover_hinge_leaf_'+str(side),(.028,.006,.018),(side*.135,.166,.151),bevel=.002,material=steel,body=cover)
v4.joint('cover_hinge','revolute',chassis,cover,origin=(0,.180,.164),axis=(1,0,0),limits=(-math.radians(34),0))

# Mount details: charging / safety pictograms and model lettering are raised on faces.

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