"""Detailed articulated full-size grand piano, authored in v4lib."""
import math, os, sys
import bpy
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import v4lib as v4
v4.reset()
# Finishes
wood=v4.wood('black_grand_lacquer',light=(0.055,0.045,0.038),dark=(0.012,0.014,0.018),grain_scale=10,roughness=0.16,coat=0.9)
wood_edge=v4.wood('rim_walnut_core',light=(0.20,0.075,0.025),dark=(0.075,0.018,0.008),grain_scale=8,roughness=0.25,coat=0.55)
brass=v4.metal('polished_brass',color=(0.78,0.48,0.16),roughness=0.22)
steel=v4.metal('steel_strings',color=(0.58,0.61,0.64),roughness=0.24,brushed=True)
plate=v4.metal('cast_iron_plate',color=(0.24,0.29,0.31),roughness=0.38)
ivory=v4.mat('ivory',(.92,.88,.75),roughness=.26)
ebon=v4.painted('ebony',(.012,.014,.017),roughness=.17,coat=.8)
felt=v4.fabric('hammer_felt',(.42,.045,.028)); felt_dark=v4.fabric('action_felt',(.10,.025,.018))
spruce=v4.wood('spruce_soundboard',light=(.72,.48,.24),dark=(.36,.18,.075),grain_scale=12,roughness=.42)
case=v4.body('case')
# Grand outline: broad keyboard end, straight bass spine (left), curved treble bentside and rounded tail.
outline=[(-.675,0.00),(-.40,0.00),(0,0.00),(.40,0.00),(.665,0.00),(.704,.16),(.718,.38),(.724,.59),(.716,.81),(.69,1.02),(.62,1.18),(.49,1.30),(.31,1.38),(.12,1.43),(-.10,1.44),(-.34,1.42),(-.56,1.36),(-.675,1.28),(-.675,1.05),(-.675,.80),(-.675,.55),(-.675,.30)]
def smooth_closed(points, steps=4):
    out=[]; n=len(points)
    for i in range(n):
        p0=points[(i-1)%n]; p1=points[i]; p2=points[(i+1)%n]; p3=points[(i+2)%n]
        for j in range(steps):
            t=j/steps; t2=t*t; t3=t2*t
            out.append(tuple(.5*((2*p1[k])+(-p0[k]+p2[k])*t+(2*p0[k]-5*p1[k]+4*p2[k]-p3[k])*t2+(-p0[k]+3*p1[k]-3*p2[k]+p3[k])*t3) for k in range(2)))
    return out
def offset_closed(points, distance=.005):
    cx=sum(p[0] for p in points)/len(points); cy=sum(p[1] for p in points)/len(points)
    return [(x+(x-cx)/math.hypot(x-cx,y-cy)*distance,y+(y-cy)/math.hypot(x-cx,y-cy)*distance) for x,y in points]
smooth_outline=smooth_closed(outline)
# Smooth shell is a continuous deep rim, with edge bevels and high segment polygonal curvature.
v4.extrude('curved_grand_rim',smooth_outline,.19,loc=(0,0,.765),bevel=.004,material=wood,body=case)
inner=[(-.625,.08),(.615,.08),(.66,.20),(.665,.40),(.65,.59),(.615,.80),(.54,.96),(.41,1.09),(.22,1.20),(.03,1.255),(-.20,1.245),(-.43,1.20),(-.625,1.14)]
cutter=v4.extrude('rim_cavity_tool',smooth_closed(inner),.25,loc=(0,0,.74),bevel=0,material=None); v4.boolean(bpy.data.objects['curved_grand_rim'],cutter)
# Soundboard, soundboard ribs, bridge, cast plate and strings.
sb=[(-.62,.08),(.61,.08),(.66,.20),(.65,.44),(.59,.75),(.42,1.04),(.19,1.21),(-.08,1.265),(-.35,1.23),(-.57,1.11),(-.63,.79),(-.64,.40)]
v4.extrude('spruce_soundboard',sb,.014,loc=(0,0,.785),bevel=.002,material=spruce,body=case)
for i,x in enumerate((-.48,-.30,-.12,.06,.24,.42)):
    v4.rod(f'soundboard_rib_{i}',(x,.12,.792),(x*.62,1.12,.792),.008,material=wood_edge,body=case)
# Broad irregular cast-iron plate, with rails on top and visible dark iron surface.
plate_shape=[(-.48,-.08),(.38,-.08),(.48,.06),(.44,.68),(.30,1.08),(.10,1.21),(-.18,1.20),(-.42,1.00),(-.50,.60)]
v4.extrude('cast_iron_plate',plate_shape,.012,loc=(0,0,.797),bevel=.004,material=plate,body=case)
v4.box('bass_bridge',(1.04,.045,.05),(0,.12,.823),bevel=.006,material=wood_edge,body=case)
v4.box('treble_bridge',(1.00,.045,.05),(0,.62,.823),bevel=.006,material=wood_edge,body=case)
# Keyboard keybed, front key slip, fallboard and cheek blocks.
v4.box('keybed_slab',(1.30,.55,.04),(0,-.455,.748),bevel=.006,material=wood_edge,body=case)
# Cantilever supports tie the projecting keybed into the soundboard and rim, outside the key lanes.
for sx in (-1,1): v4.box(f'keybed_to_rim_support_{sx}',(.14,.38,.06),(sx*.48,-.02,.77),bevel=.004,material=wood_edge,body=case)
v4.box('key_slip',(1.34,.044,.046),(0,-.748,.738),bevel=.004,material=wood,body=case)
v4.box('fallboard',(1.32,.10,.055),(0,-.49,.842),bevel=.009,material=wood,body=case)
for side in (-1,1):
    v4.box(f'cheek_block_{side}',(.075,.43,.10),(side*.652,-.49,.823),bevel=.012,material=wood,body=case)
# Balance and front rails are attached to the case; rails support the moving keys.
rail_top=.765+.025/2
v4.box('balance_rail',(1.25,.055,.025),(0,-.49,.765),bevel=.004,material=wood_edge,body=case)
v4.box('front_rail',(1.29,.04,.025),(0,-.692,.735),bevel=.004,material=wood_edge,body=case)
# 88-note A0-C8 layout, 52 naturals and correct repeating 2/3 black-key groups.
white_pitch=1.08/52
natural=[]; blacks=[]; wi=0
for midi in range(21,109):
    sem=midi%12
    if sem in (1,3,6,8,10): blacks.append((midi,wi-.5))
    else: natural.append((midi,wi)); wi+=1
center=(51*white_pitch)/2
wx={m:(i*white_pitch-center) for m,i in natural}; bx={m:(slot*white_pitch-center) for m,slot in blacks}
for midi in range(21,109):
    black=midi%12 in (1,3,6,8,10); x=(bx[midi] if black else wx[midi])+.060
    key=v4.body(f'key_{midi-21:02d}')
    # One continuous wooden lever reaches from short visible key cap to the action rail.
    v4.box(f'key_lever_{midi}',(.018 if black else .021,.50,.018),(x,-.47,.7915),bevel=.0015,material=wood_edge,body=key)
    v4.box(f'action_lifter_{midi}',(.009,.030,.050),(x,-.195,.814),bevel=.002,material=wood_edge,body=key)
    if black:
        v4.box(f'black_key_{midi}',(.018,.205,.045),(x,-.666,.815),bevel=.004,material=ebon,body=key)
    else:
        v4.box(f'white_key_{midi}',(white_pitch*.94,.205,.018),(x,-.666,.802),bevel=.002,material=ivory,body=key)
        v4.box(f'key_front_lip_{midi}',(white_pitch*.90,.022,.006),(x,-.768,.805),bevel=.001,material=ivory,body=key)
    v4.cylinder(f'balance_pin_{midi}',.0028,.025,(x,-.49,.779),segments=12,bevel=.0002,material=brass,body=key)
    # Front key end drops approximately 10 mm over the 0.27 m balance-to-front arm.
    v4.joint(f'key_hinge_{midi-21:02d}','revolute',case,key,origin=(x,-.49,rail_top+.001),axis=(1,0,0),limits=(0,math.radians(4)))
    # Hammer butt pivot sits on the rear of its lever at the action contact height.
    hammer=v4.body(f'hammer_{midi-21:02d}')
    hp=(x,-.18,.827); head=(x,-.10+(midi%3)*.004,.845)
    # Keep the moving butt on the positive-Y side of its pivot; it follows the
    # rising rear key end without sweeping into the neighboring lifter.
    v4.box(f'hammer_butt_{midi}',(.006,.018,.010),(x,-.171,.827),bevel=.0015,material=wood_edge,body=hammer)
    v4.rod(f'hammer_shank_{midi}',hp,head,.004,segments=12,bevel=.0003,material=wood_edge,body=hammer)
    v4.sphere(f'hammer_head_{midi}',.0045,head,segments=12,material=felt,body=hammer)
    v4.joint(f'hammer_hinge_{midi-21:02d}','revolute',key,hammer,origin=hp,axis=(1,0,0),limits=(0,math.radians(12)))
# Action rail joins hammer butt area and provides fixed mounting framework.
v4.box('action_rail',(1.26,.05,.025),(0,-.12,.777),bevel=.004,material=wood_edge,body=case)
v4.box('damper_rail',(1.22,.035,.025),(0,.86,.87),bevel=.003,material=wood,body=case)
# Strings, bridges, tuning pins across remaining interior; string banks at staggered heights.
for i in range(50):
    x=-.47+i*.019
    endx=x*.68
    y0=-.04+(i%4)*.018; y1=1.18-(i%5)*.025
    z=.836+(i%3)*.002
    v4.rod(f'string_{i}',(x,y0,z),(endx,y1,z),.0011,segments=8,bevel=0,material=steel,body=case)
    v4.cylinder(f'tuning_pin_{i}',.004,.024,(x,y0-.006,z),rot=(math.pi/2,0,0),segments=12,material=brass,body=case)
# Three turned legs, mounted beneath the rim; front pair clear cheek blocks and keys.
leg_sites=[(-.70,-.31),(.70,-.31),(0,1.17)]
for i,(x,y) in enumerate(leg_sites):
    v4.lathe(f'turned_leg_{i}',[(0,0),(.070,0),(.074,.018),(.057,.055),(.040,.12),(.038,.27),(.050,.51),(.070,.72),(0,.72)],loc=(x,y,.045),material=wood_edge,body=case)
    v4.box(f'leg_mount_{i}',(.19,.19,.055),(x,y,.755),bevel=.014,material=wood,body=case)
    # Brass caster fork and horizontal wheel, all joined to the fixed leg body.
    v4.cylinder(f'caster_socket_{i}',.047,.025,(x,y,.045),material=brass,body=case)
    v4.cylinder(f'caster_wheel_{i}',.033,.07,(x,y,.035),rot=(0,math.pi/2,0),material=brass,body=case)
# Pedal lyre: substantial carved side cheeks, upper tie and diagonal braces to bottom board.
v4.box('lyre_top_block',(.49,.15,.12),(0,-.655,.585),bevel=.025,material=wood,body=case)
for s in (-1,1):
    v4.rod(f'lyre_cheek_{s}',(s*.20,-.61,.60),(s*.16,-.71,.19),.035,material=wood,body=case)
    v4.rod(f'lyre_brace_{s}',(s*.31,-.48,.72),(s*.16,-.70,.30),.025,material=wood_edge,body=case)
v4.box('lyre_rear_tie',(.34,.09,.055),(0,-.69,.30),bevel=.012,material=wood_edge,body=case)
for i,x in enumerate((-.12,0,.12)):
    p=v4.body(f'pedal_{i}'); pivot=(x,-.70,.225); toe=(x,-.84,.085)
    v4.rod(f'pedal_stem_{i}',pivot,toe,.012,material=brass,body=p)
    v4.box(f'pedal_toe_{i}',(.068,.17,.022),(x,-.84,.078),rot=(math.radians(-8),0,0),bevel=.012,material=brass,body=p)
    v4.joint(f'pedal_hinge_{i}','revolute',case,p,origin=pivot,axis=(-1,0,0),limits=(-math.radians(6),0))
# Whole wing lid covers the string field and turns about the straight bass spine (world Y).
lid=v4.body('lid')
lid_outline=smooth_closed(offset_closed(outline,.005))
v4.extrude('lid_panel',lid_outline,.045,loc=(0,0,.960),bevel=.006,material=wood,body=lid)
v4.extrude('lid_underpanel',[(x*.997,y*.997) for x,y in lid_outline],.005,loc=(0,0,.955),bevel=.002,material=wood_edge,body=lid)
v4.box('prop_cup_base',(.10,.10,.016),(.62,.95,.955),bevel=.004,material=wood_edge,body=lid)
v4.box('prop_cup_liner',(.064,.064,.010),(.62,.95,.943),bevel=.003,material=brass,body=lid)
# Spine hinge leaves and knuckles lie on the fixed left rim.
for i,y in enumerate((.14,.38,.62,.86,1.10)):
    v4.cylinder(f'lid_hinge_barrel_{i}',.022,.10,(-.675,y,.955),rot=(math.pi/2,0,0),material=brass,body=case)
v4.joint('lid_hinge','revolute',case,lid,origin=(-.675,.65,.955),axis=(0,-1,0),limits=(0,math.radians(50)))
# Short articulated action cover bridges the desk and the full-size lid over the hammers.
front_lid=v4.body('front_lid')
v4.extrude('front_lid_panel',[(-.675,-.34),(.675,-.34),(.675,0),(-.675,0)],.045,loc=(0,0,.960),bevel=.006,material=wood,body=front_lid)
for sx in (-.56,.56):
    v4.rod(f'front_lid_hinge_mount_arm_{sx}',(sx,.07,.962),(sx,.014,1.005),.008,material=brass,body=lid)
    v4.cylinder(f'front_lid_hinge_barrel_{sx}',.010,.075,(sx,0,1.005),rot=(0,math.pi/2,0),material=brass,body=lid)
v4.joint('front_lid_hinge','revolute',lid,front_lid,origin=(0,0,1.005),axis=(1,0,0),limits=(-math.pi,0))
# Treble-side prop pivots on the rim and rises into a cup under the open lid.
prop=v4.body('prop_stick'); pp=(.70,.95,.955); pt=(-.482,.95,.955)
v4.rod('prop_shaft',pp,pt,.014,material=wood_edge,body=prop)
v4.sphere('prop_head',.019,pt,segments=16,material=brass,body=prop)
v4.joint('prop_hinge','revolute',case,prop,origin=pp,axis=(0,1,0),limits=(0,math.radians(63.3)))
# Fixed music desk/rack sits ahead of the lid and behind the keys; broad mount joins the cheek blocks.
desk=case; dy=-.40; dz=.955
v4.box('music_desk_panel',(.78,.026,.22),(0,dy,.985),rot=(math.radians(-13),0,0),bevel=.008,material=wood,body=desk)
v4.box('music_desk_shelf',(.80,.075,.025),(0,-.50,.892),bevel=.006,material=wood_edge,body=desk)
for x in (-.35,.35): v4.rod(f'desk_support_{x}',(x,-.49,.90),(x,-.40,.99),.009,material=brass,body=desk)
v4.box('desk_mount',(1.35,.055,.04),(0,-.47,.88),bevel=.006,material=wood_edge,body=case)
v4.save(os.path.join(os.getcwd(),'asset.blend'))
print('saved asset.blend')
