"""Detailed articulated horizontal fire-tube steam boiler."""
import math
import os
import sys

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

v4.reset()
pi = math.pi
deg = math.radians

# Enamelled pressure vessel, cast iron fittings and instrument metals.
green = v4.painted("boiler_enamel", color=(0.12, 0.25, 0.17), roughness=0.28)
green_light = v4.painted("edge_enamel", color=(0.20, 0.34, 0.23), roughness=0.3)
iron = v4.painted("black_cast_iron", color=(0.105, 0.12, 0.12), roughness=0.42)
steel = v4.metal("satin_steel", color=(0.68, 0.70, 0.68), roughness=0.3, brushed=True)
darksteel = v4.metal("darkened_steel", color=(0.28, 0.31, 0.31), roughness=0.4, brushed=False)
brass = v4.metal("warm_brass", color=(0.78, 0.56, 0.25), roughness=0.27, brushed=False)
glass = v4.glass("gauge_glass", color=(0.36, 0.68, 0.74), roughness=0.12)
white = v4.mat("dial_porcelain", (0.91, 0.87, 0.74), roughness=0.5)
red = v4.painted("warning_red", color=(0.63, 0.12, 0.08), roughness=0.34)

root = v4.body("pressure_vessel")
CY, CZ, R, L = 0.0, 1.18, 0.59, 2.35

def cyl_y(name, radius, depth, loc, mat, body, segments=48):
    return v4.cylinder(name, radius, depth, loc, rot=(pi/2, 0, 0), segments=segments, material=mat, body=body)

def tor_y(name, major, minor, loc, mat, body):
    return v4.torus(name, major, minor, loc, rot=(pi/2, 0, 0), material=mat, body=body)

def ring_x(name, major, minor, loc, mat, body):
    return v4.torus(name, major, minor, loc, rot=(0, pi/2, 0), material=mat, body=body)

def bolts_y(prefix, cx, cy, cz, radius, count, bolt_r, mat, body):
    for i in range(count):
        a = 2*pi*i/count
        x, z = cx + radius*math.cos(a), cz + radius*math.sin(a)
        v4.cylinder(f"{prefix}_{i:02d}", bolt_r, 0.012, (x, cy, z), rot=(pi/2,0,0),
                    segments=12, material=mat, body=body)

# Pressure vessel shell and formed end plates, axis along the boiler length (Y).
cyl_y("rolled_pressure_shell", R, L, (0, CY, CZ), green, root, 96)
cyl_y("front_dished_head", R*0.985, 0.045, (0, -L/2-0.014, CZ), green, root, 96)
cyl_y("rear_dished_head", R*0.985, 0.045, (0, L/2+0.014, CZ), green, root, 96)
for seam_i, y in enumerate((-1.04, -0.53, 0.0, 0.53, 1.04)):
    tor_y(f"shell_seam_{seam_i}", R-0.006, 0.012, (0,y,CZ), steel if abs(y)>1 else green_light, root)
# Shell rivet rows follow the curved circumference, set into the shell skin.
for row, theta in enumerate((-1.22,-0.82,-0.42,0.0,0.42,0.82,1.22,pi)):
    x, z = -R*math.sin(theta), CZ + R*math.cos(theta)
    for j in range(13):
        y = -1.04 + j*(2.08/12)
        v4.sphere(f"shell_rivet_{row}_{j}", 0.009, (x,y,z), segments=12, material=darksteel, body=root)

# Structural base: rolled channel rails, saddles and triangular gussets.
for sx in (-1, 1):
    v4.box(f"base_long_rail_{sx}", (0.12, 2.52, 0.11), (sx*0.43, 0, 0.10), bevel=0.012, material=darksteel, body=root)
for saddle_i, y in enumerate((-0.92, 0.92)):
    v4.box(f"saddle_web_{saddle_i}", (0.88, 0.09, 0.40), (0,y,0.39), bevel=0.012, material=iron, body=root)
    for sx in (-1,1):
        v4.box(f"saddle_rail_mount_{saddle_i}_{sx}",(0.13,0.13,0.07),(sx*0.42,y,0.18),bevel=0.008,material=steel,body=root)
    for sx in (-1,1):
        v4.extrude(f"saddle_gusset_{saddle_i}_{sx}", [(0,0),(0.24,0),(0.05,0.28)], 0.025,
                   loc=(sx*0.38-0.0125,y-0.05,0.15), rot=(pi/2,0,0), bevel=0.003, material=steel, body=root)
    # saddle crown sits against the underside of the cylindrical shell
    v4.box(f"saddle_crown_{saddle_i}", (0.93,0.14,0.065), (0,y,0.58), bevel=0.025, material=iron, body=root)
    for sx in (-1,1):
        v4.cylinder(f"saddle_bolt_{saddle_i}_{sx}", 0.018, 0.012, (sx*0.34,y-0.073,0.59),
                    rot=(pi/2,0,0), segments=12, material=brass, body=root)

# Front firebox plate is fixed to the pressure vessel; it carries fixed hinges and frame.
front_y = -1.205
v4.box("firebox_front_cheek", (0.88,0.055,1.00), (0,front_y,0.66), bevel=0.025, material=iron, body=root)
v4.box("front_top_crossbar", (0.90,0.07,0.075), (0,front_y-0.012,1.18), bevel=0.012, material=steel, body=root)
# Fixed mounting flange rings and bolt circle around fire and ash apertures.
cyl_y("firebox_opening_flange", 0.285, 0.035, (0,front_y-0.043,0.70), steel, root)
tor_y("firebox_flange_rim", 0.267, 0.012, (0,front_y-0.064,0.70), darksteel, root)
bolts_y("firebox_flange_bolt",0,front_y-0.069,0.70,0.268,16,0.012,brass,root)
v4.box("ash_opening_frame", (0.46,0.04,0.30), (0,front_y-0.04,0.245), bevel=0.016, material=steel, body=root)
for sx in (-1,1):
    for z in (0.14,0.35):
        v4.cylinder(f"ash_frame_bolt_{sx}_{z}",0.009,0.012,(sx*0.20,front_y-0.065,z),rot=(pi/2,0,0),segments=12,material=brass,body=root)

# Firebox access door, hinged at the left edge on the fixed firebox front.
fire = v4.body("firebox_door")
door_y = front_y-0.085
cyl_y("fire_door_cast_leaf",0.265,0.055,(0,door_y,0.70),iron,fire,64)
tor_y("fire_door_raised_bead",0.238,0.014,(0,door_y-0.032,0.70),steel,fire)
tor_y("fire_door_inner_bead",0.183,0.006,(0,door_y-0.035,0.70),darksteel,fire)
for i in range(8):
    a=2*pi*i/8
    # Short radial cast ribs on the outer face.
    v4.rod(f"fire_door_rib_{i}",(0.06*math.cos(a),door_y-0.035,0.70+0.06*math.sin(a)),
           (0.17*math.cos(a),door_y-0.035,0.70+0.17*math.sin(a)),0.007,material=steel,body=fire)
v4.cylinder("fire_door_lock_boss",0.048,0.026,(0,door_y-0.041,0.70),rot=(pi/2,0,0),material=darksteel,body=fire)
v4.cylinder("fire_door_lock_nut",0.028,0.035,(0,door_y-0.061,0.70),rot=(pi/2,0,0),segments=8,material=brass,body=fire)
v4.rod("fire_door_lock_bar",(-0.11,door_y-0.075,0.70),(0.11,door_y-0.075,0.70),0.012,material=brass,body=fire)
hingex=-0.255
for k,z in enumerate((0.51,0.88)):
    v4.cylinder(f"fire_hinge_knuckle_{k}",0.018,0.10,(hingex,front_y-0.077,z),segments=24,material=brass,body=fire)
    v4.rod(f"fire_hinge_bridge_{k}",(hingex+0.085,door_y-0.015,z),(hingex,front_y-0.077,z),0.012,material=steel,body=fire)
    v4.box(f"fire_hinge_fixed_leaf_{k}",(0.035,0.018,0.11),(hingex-0.022,front_y-0.018,z),bevel=0.004,material=steel,body=root)
v4.joint("firebox_hinge","revolute",root,fire,origin=(hingex,front_y-0.077,0.70),axis=(0,0,1),limits=(-deg(105),0))

# Ash-pit cleanout and draft-control door below the firebox.
ash=v4.body("ashpit_door")
ash_y=front_y-0.083
v4.box("ashpit_cast_leaf",(0.40,0.045,0.235),(0,ash_y,0.245),bevel=0.018,material=iron,body=ash)
v4.box("ashpit_inner_panel",(0.31,0.018,0.16),(0,ash_y-0.030,0.245),bevel=0.01,material=darksteel,body=ash)
for i in range(5):
    x=-0.12+i*0.06
    v4.box(f"ashpit_draft_slot_{i}",(0.027,0.004,0.075),(x,ash_y-0.042,0.245),bevel=0.01,material=iron,body=ash)
for sx in (-1,1):
    v4.cylinder(f"ashpit_latch_pin_{sx}",0.014,0.018,(sx*0.15,ash_y-0.037,0.245),rot=(pi/2,0,0),segments=16,material=brass,body=ash)
v4.rod("ashpit_latch_bar",(-0.13,ash_y-0.049,0.245),(0.13,ash_y-0.049,0.245),0.009,material=brass,body=ash)
ash_hx=-0.205
for k,z in enumerate((0.17,0.32)):
    v4.cylinder(f"ash_hinge_knuckle_{k}",0.014,0.065,(ash_hx,front_y-0.075,z),segments=20,material=brass,body=ash)
    v4.box(f"ash_hinge_fixed_{k}",(0.026,0.018,0.07),(ash_hx-0.018,front_y-0.018,z),bevel=0.003,material=steel,body=root)
v4.joint("ashpit_hinge","revolute",root,ash,origin=(ash_hx,front_y-0.075,0.245),axis=(0,0,1),limits=(-deg(95),0))

# Steam dome with formed shoulder, bolted base and top fittings.
v4.torus("steam_dome_base_gasket",0.285,0.018,(0,-0.12,1.765),material=darksteel,body=root)
v4.lathe("steam_dome",[(0,1.74),(0.25,1.74),(0.29,1.78),(0.29,1.84),(0.25,1.89),(0.22,1.97),(0.19,2.12),(0.15,2.17),(0,2.17)],
         material=green,body=root,segments=64)
for i in range(12):
    a=2*pi*i/12
    v4.sphere(f"dome_base_bolt_{i}",0.012,(0.265*math.cos(a),-0.12+0.265*math.sin(a),1.789),segments=12,material=brass,body=root)
# Main steam stop valve pedestal on forward portion of dome.
v4.lathe("stop_valve_standpipe",[(0,2.05),(0.085,2.05),(0.095,2.10),(0.065,2.14),(0.045,2.22),(0,2.22)],
         loc=(0.02,0.12,0),material=brass,body=root)
v4.torus("stop_valve_packing_gland",0.052,0.009,(0.02,0.12,2.20),material=darksteel,body=root)
wheel=v4.body("stop_valve_handwheel")
v4.torus("stop_handwheel_rim",0.118,0.009,(0.02,0.12,2.275),material=red,body=wheel)
v4.cylinder("stop_handwheel_hub",0.032,0.055,(0.02,0.12,2.245),material=brass,body=wheel)
for i in range(6):
    a=2*pi*i/6
    v4.rod(f"stop_handwheel_spoke_{i}",(0.02,0.12,2.275),(0.02+0.112*math.cos(a),0.12+0.112*math.sin(a),2.275),0.0055,material=brass,body=wheel)
v4.joint("stop_valve_rotation","continuous",root,wheel,origin=(0.02,0.12,2.23),axis=(0,0,1))

# Lift safety valve on the aft side of the dome, with bonnet and vent slots.
v4.cylinder("safety_valve_seat_flange",0.105,0.045,(0.34,-0.12,2.16),material=steel,body=root)
for i in range(8):
    a=2*pi*i/8
    v4.sphere(f"safety_seat_bolt_{i}",0.010,(0.34+0.087*math.cos(a),-0.12+0.087*math.sin(a),2.184),segments=12,material=brass,body=root)
safety=v4.body("safety_valve")
v4.lathe("safety_bonnet",[(0,2.17),(0.075,2.17),(0.085,2.20),(0.079,2.28),(0.06,2.34),(0.035,2.37),(0,2.37)],
         loc=(0.34,-0.12,0),material=brass,body=safety)
v4.cylinder("safety_cap",0.05,0.035,(0.34,-0.12,2.37),material=darksteel,body=safety)
for i in range(6):
    a=2*pi*i/6
    v4.box(f"safety_vent_{i}",(0.008,0.025,0.014),(0.34+0.081*math.cos(a),-0.12+0.081*math.sin(a),2.245),bevel=0.002,material=iron,body=safety)
v4.rod("safety_lift_stem",(0.34,-0.12,2.12),(0.34,-0.12,2.20),0.018,material=steel,body=safety)
v4.joint("safety_valve_lift","prismatic",root,safety,origin=(0.34,-0.12,2.17),axis=(0,0,1),limits=(0,0.09))

# Rear uptake: fixed flue tube, collar, stack cap and internal butterfly damper.
v4.cylinder("flue_base_neck",0.19,0.10,(0,0.88,1.76),material=darksteel,body=root)
v4.cylinder("flue_stack",0.145,0.57,(0,0.88,2.00),material=iron,body=root)
v4.torus("flue_lower_bead",0.147,0.012,(0,0.88,1.78),material=steel,body=root)
v4.torus("flue_top_rim",0.153,0.018,(0,0.88,2.285),material=steel,body=root)
for z in (1.89,2.04,2.19):
    tor_y(f"flue_roll_{z}",0.145,0.006,(0,0.88,z),darksteel,root)
damper=v4.body("damper")
v4.cylinder("damper_disc",0.137,0.018,(0,0.88,1.98),rot=(0,0,0),material=darksteel,body=damper,segments=64)
v4.rod("damper_crossbar",(-0.14,0.88,1.98),(0.14,0.88,1.98),0.012,material=steel,body=damper)
# Shaft ends and an external operating lever.
v4.rod("damper_shaft",(-0.19,0.88,1.98),(0.19,0.88,1.98),0.012,material=brass,body=damper)
v4.rod("damper_external_handle",(-0.19,0.88,1.98),(-0.27,0.88,2.12),0.009,material=brass,body=damper)
v4.sphere("damper_handle_grip",0.018,(-0.27,0.88,2.12),material=iron,body=damper)
v4.joint("flue_damper","revolute",root,damper,origin=(0,0.88,1.98),axis=(1,0,0),limits=(-deg(80),deg(80)))

# Water glass on the visible left side: protected glass, scale, shutoff cocks and drain.
gx, gy = -0.590, -0.18
v4.box("gauge_backing_plate",(0.018,0.20,0.69),(gx+0.013,gy,1.10),bevel=0.016,material=darksteel,body=root)
v4.cylinder("water_gauge_glass",0.021,0.49,(gx-0.012,gy,1.10),segments=32,material=glass,body=root)
for sy in (-1,1):
    z=1.10+sy*0.20
    v4.rod(f"gauge_guard_rail_{sy}",(gx-0.035,gy-0.055,0.80),(gx-0.035,gy-0.055,1.40),0.006,material=brass,body=root)
for z in (0.80,1.40):
    v4.box(f"gauge_mount_bracket_{z}",(0.08,0.12,0.045),(gx-0.015,gy,z),bevel=0.008,material=steel,body=root)
    v4.sphere(f"gauge_bracket_bolt_{z}",0.009,(gx-0.050,gy-0.055,z),segments=12,material=brass,body=root)
for i in range(9):
    z=0.90+i*0.05
    v4.box(f"gauge_scale_tick_{i}",(0.005,0.03 if i%2==0 else 0.018,0.003),(gx+0.002,gy-0.075,z),bevel=0.0008,material=white,body=root)

for idx,z in enumerate((1.40,0.80)):
    cock=v4.body(f"gauge_cock_{'upper' if idx==0 else 'lower'}")
    # The rotary plug crosses the shell radially; its lever rotates with its own body.
    v4.cylinder(f"gauge_cock_plug_{idx}",0.034,0.11,(gx-0.034,gy,z),rot=(0,pi/2,0),material=brass,body=cock)
    v4.cylinder(f"gauge_cock_gland_{idx}",0.047,0.023,(gx-0.074,gy,z),rot=(0,pi/2,0),material=darksteel,body=cock)
    v4.rod(f"gauge_cock_lever_{idx}",(gx-0.09,gy,z),(gx-0.09,gy-0.13,z),0.009,material=brass,body=cock)
    v4.sphere(f"gauge_cock_grip_{idx}",0.018,(gx-0.09,gy-0.13,z),material=iron,body=cock)
    v4.joint(f"gauge_cock_{idx}_turn","revolute",root,cock,origin=(gx-0.034,gy,z),axis=(1,0,0),limits=(-deg(90),deg(90)))
# Fixed blowdown pipe below the gauge with a capped elbow.
v4.tube("gauge_blowdown_pipe",[(gx,gy,0.80),(gx,gy,0.69),(gx,gy-0.13,0.63),(gx,gy-0.22,0.63)],0.012,material=steel,body=root)
v4.cylinder("blowdown_plug",0.025,0.035,(gx,gy-0.22,0.63),rot=(pi/2,0,0),material=brass,body=root)

# A dial pressure gauge mounted on the left-front quadrant, including bezel and pointer.
pg_x, pg_y, pg_z = -0.57, -0.73, 1.43
v4.cylinder("pressure_gauge_stem",0.018,0.13,(pg_x+0.07,pg_y,pg_z),rot=(0,pi/2,0),material=brass,body=root)
v4.cylinder("pressure_gauge_case",0.105,0.055,(pg_x,pg_y,pg_z),rot=(0,pi/2,0),material=darksteel,body=root)
v4.cylinder("pressure_gauge_dial",0.087,0.008,(pg_x-0.033,pg_y,pg_z),rot=(0,pi/2,0),material=white,body=root)
ring_x("pressure_gauge_bezel",0.093,0.009,(pg_x-0.039,pg_y,pg_z),brass,root)
v4.rod("pressure_gauge_pointer",(pg_x-0.041,pg_y,pg_z),(pg_x-0.043,pg_y-0.049,pg_z+0.035),0.003,material=red,body=root)
for i in range(11):
    a=pi*0.75-i*pi*0.15
    y=pg_y+0.071*math.cos(a); z=pg_z+0.071*math.sin(a)
    v4.sphere(f"pressure_gauge_tick_{i}",0.004,(pg_x-0.041,y,z),segments=10,material=darksteel,body=root)
v4.sphere("pressure_gauge_hub",0.009,(pg_x-0.045,pg_y,pg_z),segments=16,material=brass,body=root)

# Top manway flange and hinged oval cover (pivot along the rear edge).
mx,my,mz=0.02,0.42,1.765
v4.cylinder("manway_flange",0.235,0.055,(mx,my,mz),material=steel,body=root)
v4.torus("manway_gasket",0.197,0.012,(mx,my,mz+0.032),material=red,body=root)
for i in range(12):
    a=2*pi*i/12
    v4.sphere(f"manway_stud_{i}",0.013,(mx+0.211*math.cos(a),my+0.211*math.sin(a),mz+0.033),segments=12,material=brass,body=root)
man=v4.body("manway")
v4.cylinder("manway_cover",0.202,0.045,(mx,my,mz+0.074),material=iron,body=man,segments=64)
v4.torus("manway_cover_bead",0.18,0.009,(mx,my,mz+0.099),material=steel,body=man)
v4.cylinder("manway_lock_boss",0.06,0.025,(mx,my,mz+0.109),material=darksteel,body=man)
v4.rod("manway_swing_bolt",(mx-0.13,my+0.03,mz+0.12),(mx+0.13,my+0.03,mz+0.12),0.012,material=brass,body=man)
for sx in (-1,1):
    v4.cylinder(f"manway_hinge_knuckle_{sx}",0.018,0.075,(sx*0.12,my+0.14,mz+0.06),rot=(0,pi/2,0),material=brass,body=man)
v4.joint("manway_hinge","revolute",root,man,origin=(-0.10,my+0.14,mz+0.06),axis=(1,0,0),limits=(-deg(115),0))

# Front-facing maker's plate and embossed boiler identification.
v4.box("maker_plate",(0.36,0.012,0.12),(0.0,-1.247,1.02),bevel=0.008,material=brass,body=root)
v4.text("maker_brand","MERIDIAN",0.045,(0.0,-1.254,1.045),rot=(pi/2,0,0),material=darksteel,body=root)
v4.text("maker_type","STEAM  /  8 BAR",0.018,(0.0,-1.254,1.004),rot=(pi/2,0,0),material=darksteel,body=root)

# Fixed pipe unions and safety warning tags give the fittings a finished product look.
v4.tube("steam_outlet_elbow",[(0.20,-0.05,2.02),(0.20,-0.05,2.14),(0.28,-0.05,2.22),(0.39,-0.05,2.22)],0.022,material=steel,body=root)
v4.cylinder("steam_union",0.036,0.026,(0.40,-0.05,2.22),rot=(0,pi/2,0),material=brass,body=root)
v4.save(os.path.join(os.getcwd(),"asset.blend"))
print("saved asset.blend")
