"""Detailed pusher fixed-wing UAV. Run with Blender: blender -b --python build.py"""
import math, os, sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import bpy
import bmesh
from mathutils import Vector
import v4lib as v4

v4.reset()

# Materials: glazed white composite airframe, dark carbon controls and high-vis accents.
white = v4.painted("warm_white_composite", (0.82, 0.84, 0.82), roughness=0.28, coat=0.72)
white2 = v4.plastic("fairing_ivory", (0.72, 0.75, 0.73), roughness=0.34)
navy = v4.painted("deep_navy_blue", (0.035, 0.09, 0.16), roughness=0.27, coat=0.5)
control_gray = v4.painted("satin_control_surface_gray", (0.30, 0.36, 0.39), roughness=0.42, coat=0.16)
orange = v4.painted("safety_orange", (0.95, 0.26, 0.035), roughness=0.32, coat=0.55)
carbon = v4.mat("carbon_control_gaps", (0.025, 0.032, 0.04), metallic=0.18, roughness=0.42)
black = v4.rubber("rubber_black", (0.025, 0.028, 0.03))
aluminum = v4.metal("anodized_aluminum", (0.57, 0.62, 0.66), roughness=0.27, brushed=True)
steel = v4.metal("stainless_fasteners", (0.76, 0.78, 0.79), roughness=0.24, brushed=False)
glass = v4.glass("camera_optics", (0.14, 0.22, 0.29), roughness=0.08)
red = v4.emissive("port_navigation_led", (1.0, 0.025, 0.015), 2.0)
green = v4.emissive("starboard_navigation_led", (0.02, 0.8, 0.12), 2.0)

# Aircraft coordinate system: nose is -Y, span is X, Z is up.
airframe = v4.body("airframe")

# Mesh utilities for smooth station lofts. Every loft is a closed solid.
def mesh_object(name, verts, faces, material, body):
    me = bpy.data.meshes.new(name + "Mesh")
    me.from_pydata(verts, [], faces)
    me.validate(); me.update()
    ob = bpy.data.objects.new(name, me)
    bpy.context.scene.collection.objects.link(ob)
    if material: v4.assign(ob, material)
    for p in me.polygons: p.use_smooth = True
    v4.part(ob, body)
    return ob

def fuselage_loft(name, stations, material, body, sides=32):
    # station = (y, rx, rz, z_center), rings become close-spaced at the rounded ends
    verts=[]; faces=[]
    for y,rx,rz,zc in stations:
        for k in range(sides):
            a=2*math.pi*k/sides
            verts.append((rx*math.cos(a), y, zc+rz*math.sin(a)))
    for j in range(len(stations)-1):
        for k in range(sides):
            a=j*sides+k; b=j*sides+(k+1)%sides
            faces.append((a,b,b+sides,a+sides))
    faces.append(tuple(range(sides-1,-1,-1)))
    faces.append(tuple((len(stations)-1)*sides+k for k in range(sides)))
    return mesh_object(name,verts,faces,material,body)

def airfoil_mesh(name, stations, material, body, n=12):
    """Stations are (x, leading_y, trailing_y, z, thickness). Lofted rounded airfoil."""
    verts=[]; faces=[]; m=2*n+1
    for x,le,te,zc,t in stations:
        chord=te-le
        outline=[]
        # Upper surface leading edge to trailing edge, then lower surface back.
        for i in range(n+1):
            u=i/n
            yt=5*t*(0.2969*math.sqrt(max(u,0))-0.1260*u-0.3516*u*u+0.2843*u**3-0.1036*u**4)
            cam=0.008*math.sin(math.pi*u)
            outline.append((x,le+chord*u,zc+cam+yt))
        for i in range(n-1,0,-1):
            u=i/n
            yt=5*t*(0.2969*math.sqrt(u)-0.1260*u-0.3516*u*u+0.2843*u**3-0.1036*u**4)
            cam=0.008*math.sin(math.pi*u)
            outline.append((x,le+chord*u,zc+cam-yt))
        verts.extend(outline)
    # Number of vertices per station is n+1 + n-1 = 2n.
    m=2*n
    for s in range(len(stations)-1):
        for k in range(m):
            a=s*m+k; b=s*m+(k+1)%m
            faces.append((a,b,b+m,a+m))
    faces.append(tuple(range(m-1,-1,-1)))
    faces.append(tuple((len(stations)-1)*m+k for k in range(m)))
    return mesh_object(name,verts,faces,material,body)

def thin_surface(name, stations, material, body, axis="x", n=10):
    # Rounded thin aerofoil used for control surfaces. x station rows; same profile function.
    return airfoil_mesh(name, stations, material, body, n)

def cylinder_x(name, r, length, xmid, y, z, material, body):
    return v4.cylinder(name,r,length,(xmid,y,z),rot=(0,math.pi/2,0),segments=24,bevel=0.0004,material=material,body=body)

def screw_x(name, x, y, z, material, body):
    v4.cylinder(name,0.0032,0.002,(x,y,z),rot=(0,math.pi/2,0),segments=16,bevel=0.0002,material=material,body=body)

def strut_fairing(name, a, b, width, depth, material, body):
    """Rounded elliptical section fairing around a diagonal gear leg."""
    a,b=Vector(a),Vector(b); axis=(b-a).normalized()
    wide=Vector((1,0,0)); wide=(wide-axis*wide.dot(axis)).normalized()
    deep=axis.cross(wide).normalized()
    verts=[]; faces=[]; ring_n=12
    for t,scale in ((0.0,0.55),(0.07,0.9),(0.18,1.0),(0.82,1.0),(0.93,0.9),(1.0,0.55)):
        c=a.lerp(b,t)
        for j in range(ring_n):
            ang=2*math.pi*j/ring_n
            p=c+wide*(math.cos(ang)*width*0.5*scale)+deep*(math.sin(ang)*depth*0.5*scale)
            verts.append(tuple(p))
    for r in range(5):
        for j in range(ring_n):
            i=r*ring_n+j; k=r*ring_n+(j+1)%ring_n
            faces.append((i,k,k+ring_n,i+ring_n))
    faces.append(tuple(range(ring_n-1,-1,-1)))
    faces.append(tuple(5*ring_n+j for j in range(ring_n)))
    return mesh_object(name,verts,faces,material,body)

# Long composite fuselage with rounded nose and tapering tail.
fuselage_loft("fuselage_shell", [
    (-0.910,0.002,0.002,0.30),(-0.895,0.024,0.030,0.30),(-0.855,0.046,0.052,0.30),
    (-0.79,0.062,0.071,0.30),(-0.68,0.076,0.082,0.30),(-0.45,0.083,0.090,0.30),
    (-0.16,0.078,0.086,0.30),(0.12,0.064,0.072,0.30),(0.36,0.048,0.048,0.30),
    (0.55,0.034,0.036,0.30),(0.69,0.019,0.025,0.30),(0.735,0.002,0.003,0.30)],white,airframe)
# Dorsal electronics bay panel and perimeter seam.
v4.box("top_battery_hatch",(0.085,0.28,0.006),(0,0.015,0.359),bevel=0.012,material=white2,body=airframe)
for x in (-0.033,0.033):
    for y in (-0.09,0.12):
        v4.cylinder("hatch_quarter_turn",0.0035,0.0015,(x,y,0.363),segments=16,bevel=0.0002,material=steel,body=airframe)
# Rear electronics access hatch and side inspection panel with fasteners.
v4.box("aft_service_hatch",(0.068,0.16,0.004),(0,-0.405,0.369),bevel=0.009,material=white2,body=airframe)
for x in (-0.024,0.024):
    for y in (-0.465,-0.345):
        v4.cylinder("aft_hatch_fastener",0.0027,0.0015,(x,y,0.372),segments=12,bevel=0.00015,material=steel,body=airframe)
v4.box("fuselage_side_access_panel",(0.003,0.145,0.045),(0.066,-0.405,0.30),bevel=0.007,material=white2,body=airframe)
for y in (-0.46,-0.35):
    for z in (0.285,0.315):
        v4.cylinder("side_panel_fastener",0.0025,0.0015,(0.068,y,z),rot=(0,math.pi/2,0),segments=12,bevel=0.00015,material=steel,body=airframe)
# Small dorsal GNSS puck and antenna.
v4.cylinder("gnss_puck_base",0.027,0.008,(0,0.22,0.355),bevel=0.002,material=navy,body=airframe)
v4.cylinder("gnss_dome",0.021,0.009,(0,0.22,0.363),bevel=0.004,material=white,body=airframe)
v4.rod("telemetry_whip",(0,0.38,0.34),(0,0.43,0.51),0.0018,material=aluminum,body=airframe)

# Main high-mounted tapered wing, 2.20 m span; thick root and thin rounded tips.
wing_stations=[(-1.10,-0.08,0.118,0.362,0.020),(-0.92,-0.12,0.098,0.358,0.026),
               (-0.65,-0.19,0.073,0.353,0.032),(-0.32,-0.27,0.042,0.347,0.036),
               (0.0,-0.31,0.045,0.345,0.039),(0.32,-0.27,0.042,0.347,0.036),
               (0.65,-0.19,0.073,0.353,0.032),(0.92,-0.12,0.098,0.358,0.026),
               (1.10,-0.08,0.118,0.362,0.020)]
airfoil_mesh("main_wing",wing_stations,white,airframe,16)
# Center wing-to-fuselage fairing and discrete panel outlines / access covers.
root_fairing=v4.sphere("wing_root_fairing",0.205,(0,-0.075,0.365),segments=48,material=white,body=airframe)
root_fairing.scale=(0.82,1.22,0.08)
for s in (-1,1):
    # Wingtip safety orange area, inset into the last 14 cm of the span.
    v4.box("wingtip_orange_inlay",(0.002,0.155,0.002),(s*1.035,-0.002,0.359),bevel=0.001,material=orange,body=airframe)
    # Servo access panel seated on upper wing, and four fasteners.
    x=s*0.69
    v4.box("aileron_servo_cover",(0.095,0.125,0.003),(x,-0.015,0.3695),bevel=0.009,material=white2,body=airframe)
    for dx in (-0.038,0.038):
        for dy in (-0.048,0.048):
            v4.cylinder("servo_cover_screw",0.0023,0.001,(x+dx,-0.015+dy,0.371),segments=12,bevel=0.00015,material=steel,body=airframe)
# Tailplane and fixed vertical fin on the aft fuselage.
tail_stations=[(-0.36,0.48,0.621,0.36,0.014),(-0.27,0.49,0.621,0.36,0.019),
               (0,0.50,0.621,0.36,0.022),(0.27,0.49,0.621,0.36,0.019),(0.36,0.48,0.621,0.36,0.014)]
airfoil_mesh("horizontal_tailplane",tail_stations,white,airframe,12)
# Fin mesh as extrusion of swept Y-Z outline, centered thickness along X.
def plate_x(name, outline_yz, x0, thickness, material, body):
    verts=[]
    for x in (x0-thickness/2,x0+thickness/2):
        verts.extend((x,y,z) for y,z in outline_yz)
    n=len(outline_yz); faces=[tuple(range(n-1,-1,-1)),tuple(range(n,2*n))]
    for i in range(n): faces.append((i,(i+1)%n,(i+1)%n+n,i+n))
    return mesh_object(name,verts,faces,material,body)

def plate_x_tapered(name, outline_yz, leading_y, full_y, nose_width, full_width, material, body):
    """Extruded fin surface with a narrow rounded hinge nose that clears its fixed fin."""
    verts=[]
    for side in (-1,1):
        for y,z in outline_yz:
            t=max(0.0,min(1.0,(y-leading_y)/(full_y-leading_y)))
            width=nose_width+(full_width-nose_width)*t
            verts.append((side*width/2,y,z))
    n=len(outline_yz); faces=[tuple(range(n-1,-1,-1)),tuple(range(n,2*n))]
    for i in range(n): faces.append((i,(i+1)%n,(i+1)%n+n,i+n))
    return mesh_object(name,verts,faces,material,body)
plate_x("vertical_fin",[(0.39,0.30),(0.44,0.37),(0.48,0.66),(0.57,0.69),(0.600,0.66),(0.600,0.30)],0,0.045,white,airframe)
# Fin accent stripe along the upper rudder-facing rear panel.
plate_x("fin_navy_chevron",[(0.515,0.45),(0.565,0.47),(0.585,0.60),(0.548,0.61)],0,0.047,navy,airframe)
# Tail service panels and hinge hardware.
for s in (-1,1):
    v4.box("tail_servo_cover",(0.09,0.07,0.002),(s*0.20,0.52,0.372),bevel=0.008,material=white2,body=airframe)
    for hx in (s*0.10,s*0.25,s*0.34):
        v4.cylinder("elevator_hinge_pin",0.003,0.021,(hx,0.625,0.36),rot=(0,math.pi/2,0),segments=20,bevel=0.0003,material=steel,body=airframe)
# Fixed hinge leaves touch the fin and come within 1 mm of the rudder nose.
for z in (0.46,0.58):
    v4.box("rudder_fixed_hinge_leaf",(0.012,0.010,0.035),(0,0.598,z),bevel=0.001,material=aluminum,body=airframe)

# Rear pusher motor sits aft of the fin and elevator, carried by a pair of carbon struts.
for sx in (-1,1):
    v4.rod("pusher_mount_strut",(sx*0.022,0.69,0.30),(sx*0.022,0.76,0.38),0.006,material=navy,body=airframe)
v4.cylinder("motor_stator",0.042,0.085,(0,0.80,0.405),rot=(math.pi/2,0,0),segments=48,bevel=0.006,material=aluminum,body=airframe)
motor_cowling=v4.sphere("pusher_motor_cowling",0.050,(0,0.80,0.405),segments=40,material=white2,body=airframe)
motor_cowling.scale=(0.84,0.80,0.84)
# Tail boom-side cooling slots represented by inset dark louvers on the motor can.
for z in (0.383,0.394,0.405,0.416,0.427):
    v4.box("motor_vent",(0.006,0.002,0.004),(0.041,0.80,z),bevel=0.001,material=carbon,body=airframe)

# Sensor package under nose: compact two-axis-like fixed gimbal housing and camera window.
v4.cylinder("camera_gimbal_ring",0.050,0.018,(0,-0.785,0.190),rot=(math.pi/2,0,0),segments=40,bevel=0.004,material=aluminum,body=airframe)
v4.sphere("camera_pod",0.050,(0,-0.797,0.190),segments=32,material=navy,body=airframe)
v4.cylinder("camera_lens_bezel",0.024,0.008,(0,-0.830,0.190),rot=(math.pi/2,0,0),segments=32,bevel=0.002,material=aluminum,body=airframe)
v4.sphere("camera_lens_glass",0.017,(0,-0.835,0.190),segments=32,material=glass,body=airframe)
v4.sphere("lens_inner_reflection",0.004,(0.006,-0.846,0.190),segments=20,material=green,body=airframe)
for sx in (-1,1):
    v4.rod("camera_gimbal_yoke",(sx*0.041,-0.761,0.223),(sx*0.041,-0.793,0.190),0.0045,material=aluminum,body=airframe)
    v4.cylinder("camera_trunnion_cap",0.008,0.006,(sx*0.044,-0.793,0.190),rot=(0,math.pi/2,0),segments=24,bevel=0.001,material=steel,body=airframe)

# Simple fixed landing gear, twin black low-pressure wheels on alloy axles.
for s in (-1,1):
    v4.rod("main_gear_strut",(s*0.045,-0.10,0.27),(s*0.24,-0.12,0.065),0.009,material=aluminum,body=airframe)
    strut_fairing("main_gear_aero_fairing",(s*0.045,-0.10,0.27),(s*0.24,-0.12,0.065),0.040,0.018,white2,airframe)
    v4.rod("main_gear_fork",(s*0.24,-0.12,0.065),(s*0.24,-0.12,0.034),0.006,material=aluminum,body=airframe)
    v4.cylinder("main_wheel",0.042,0.024,(s*0.24,-0.12,0.042),rot=(0,math.pi/2,0),segments=40,bevel=0.003,material=black,body=airframe)
    v4.cylinder("main_wheel_hub",0.017,0.026,(s*0.24,-0.12,0.042),rot=(0,math.pi/2,0),segments=32,bevel=0.002,material=aluminum,body=airframe)
    v4.cylinder("hub_cap",0.006,0.028,(s*0.24,-0.12,0.042),rot=(0,math.pi/2,0),segments=24,bevel=0.001,material=navy,body=airframe)
# Tail skid shoe, touches ground and tail fairing.
tail_fairing=v4.sphere("tail_gear_root_fairing",0.052,(0,0.647,0.252),segments=32,material=white2,body=airframe)
tail_fairing.scale=(0.52,0.78,0.88)
v4.sphere("tail_gear_saddle",0.024,(0,0.638,0.282),segments=28,material=aluminum,body=airframe)
v4.rod("tail_skid",(0,0.625,0.29),(0,0.70,0.035),0.009,material=aluminum,body=airframe)
strut_fairing("tail_gear_aero_fairing",(0,0.625,0.29),(0,0.70,0.035),0.028,0.016,white2,airframe)
v4.cylinder("tail_wheel",0.022,0.018,(0,0.70,0.027),rot=(0,math.pi/2,0),segments=32,bevel=0.002,material=black,body=airframe)
v4.cylinder("tail_wheel_hub",0.009,0.020,(0,0.70,0.027),rot=(0,math.pi/2,0),segments=24,bevel=0.001,material=aluminum,body=airframe)

# Navigation / identification details on wing and fuselage.
v4.sphere("port_nav_lamp",0.010,(-1.075,-0.015,0.378),segments=20,material=red,body=airframe)
v4.sphere("starboard_nav_lamp",0.010,(1.075,-0.015,0.378),segments=20,material=green,body=airframe)
v4.text("wing_registration_left","SKY / 07",0.027,(-0.70,-0.105,0.377),rot=(0,0,0),extrude_depth=0.0003,material=navy,body=airframe)
v4.text("wing_registration_right","UAV 07",0.027,(0.70,-0.105,0.377),rot=(0,0,math.pi),extrude_depth=0.0003,material=navy,body=airframe)
v4.text("fuselage_side_label","AEROMAP  /  ELECTRIC",0.016,(0.058,-0.36,0.302),rot=(math.pi/2,0,math.pi/2),extrude_depth=0.0003,material=navy,body=airframe)
# Pitot probe projects from port leading side; tube root meets wing.
v4.rod("pitot_probe",(-0.18,-0.285,0.35),(-0.18,-0.405,0.35),0.0025,material=aluminum,body=airframe)
v4.sphere("pitot_tip",0.003,(-0.18,-0.406,0.35),segments=16,material=steel,body=airframe)

# --------------------------- articulated control surfaces -----------------------------
# Surface bodies carry their markings and moving hinge knuckles.
def make_aileron(label, sgn):
    b=v4.body("aileron_"+label)
    # The hinge spar follows the swept, slightly rising trailing-edge line.
    if sgn > 0:
        st=[(0.31,0.044,0.133,0.3468,0.010),(0.66,0.077,0.176,0.3535,0.009),(0.99,0.108,0.195,0.359,0.006)]
        pivot=(0.31,0.044,0.3468)
        axis=(0.68,0.064,0.0122)
    else:
        st=[(-0.99,0.108,0.195,0.359,0.006),(-0.66,0.077,0.176,0.3535,0.009),(-0.31,0.044,0.133,0.3468,0.010)]
        pivot=(-0.31,0.044,0.3468)
        axis=(-0.68,0.064,0.0122)
    thin_surface("aileron_"+label+"_shell",st,control_gray,b,n=10)
    # Thin orange root ID stripe and hinge barrels ride with the control surface.
    v4.box("aileron_id_band",(0.055,0.003,0.003),(sgn*0.42,0.058,0.355),bevel=0.001,material=orange,body=b)
    for hx,hy,hz in ((sgn*0.39,0.052,0.3484),(sgn*0.64,0.076,0.3531),(sgn*0.88,0.098,0.3574)):
        v4.cylinder("moving_aileron_knuckle",0.004,0.022,(hx,hy,hz),rot=(0,math.pi/2,0),segments=20,bevel=0.0003,material=aluminum,body=b)
    for hx in (sgn*0.515,sgn*0.765):
        ay=0.044 + (0.064/0.68)*(abs(hx)-0.31)
        az=0.3468 + (0.0122/0.68)*(abs(hx)-0.31)
        v4.cylinder("fixed_aileron_hinge_barrel",0.0034,0.020,(hx,ay,az),rot=(0,math.pi/2,0),segments=20,bevel=0.0003,material=steel,body=airframe)
    # Short exposed horn at the inboard end, seated through the hinge line.
    v4.box("aileron_control_horn",(0.009,0.012,0.025),(sgn*0.345,0.064,0.354),bevel=0.002,material=aluminum,body=b)
    v4.sphere("aileron_horn_bearing",0.004,(sgn*0.35,0.070,0.342),segments=16,material=steel,body=b)
    v4.rod("aileron_pushrod",(sgn*0.35,0.070,0.342),(sgn*0.66,0.005,0.319),0.0018,material=aluminum,body=b)
    v4.sphere("aileron_pushrod_end",0.0032,(sgn*0.66,0.005,0.319),segments=16,material=steel,body=b)
    v4.box("aileron_servo_arm",(0.010,0.008,0.028),(sgn*0.66,-0.010,0.337),bevel=0.002,material=navy,body=airframe)
    v4.joint("aileron_"+label+"_hinge","revolute",airframe,b,origin=pivot,axis=axis,limits=(-math.radians(20),math.radians(20)))
    return b
make_aileron("left",-1)
make_aileron("right",1)

# Split elevator surfaces keep a proper clearance notch around the central rudder hinge.
for side in ("left","right"):
    elev=v4.body("elevator_"+side)
    if side=="left":
        elev_st=[(-0.36,0.625,0.70,0.36,0.009),(-0.20,0.625,0.70,0.36,0.013),(-0.05,0.625,0.70,0.36,0.014)]
        xs=(-0.31,-0.16,-0.07); pivot=-0.205
    else:
        elev_st=[(0.05,0.625,0.70,0.36,0.014),(0.20,0.625,0.70,0.36,0.013),(0.36,0.625,0.70,0.36,0.009)]
        xs=(0.07,0.16,0.31); pivot=0.205
    thin_surface("elevator_"+side+"_shell",elev_st,control_gray,elev,n=10)
    # Fixed hinge pins on the airframe remain visible along this split moving seam.
    sx=-1 if side=="left" else 1
    v4.box("elevator_control_horn",(0.010,0.016,0.024),(sx*0.17,0.645,0.351),bevel=0.002,material=aluminum,body=elev)
    v4.sphere("elevator_horn_bearing",0.0038,(sx*0.17,0.649,0.340),segments=16,material=steel,body=elev)
    v4.rod("elevator_pushrod",(sx*0.17,0.649,0.340),(sx*0.20,0.55,0.340),0.0017,material=aluminum,body=elev)
    v4.sphere("elevator_pushrod_end",0.003,(sx*0.20,0.55,0.340),segments=16,material=steel,body=elev)
    v4.box("elevator_servo_arm",(0.010,0.010,0.024),(sx*0.20,0.54,0.348),bevel=0.002,material=navy,body=airframe)
    v4.joint("elevator_"+side+"_hinge","revolute",airframe,elev,origin=(pivot,0.625,0.36),axis=(1,0,0),limits=(-math.radians(25),math.radians(25)))

# Rudder trailing panel, rotating about a real vertical hinge line.
rudder=v4.body("rudder")
plate_x_tapered("rudder_shell",[(0.608,0.38),(0.672,0.39),(0.674,0.48),(0.657,0.61),(0.622,0.655),(0.608,0.64)],0.608,0.628,0.008,0.043,control_gray,rudder)
plate_x("rudder_orange_flash",[(0.641,0.48),(0.667,0.485),(0.654,0.56),(0.629,0.56)],0,0.045,orange,rudder)
# Round moving nose, pin, and knuckles share the actual hinge axis at y=0.608.
v4.cylinder("rudder_hinge_pin",0.0022,0.275,(0,0.608,0.5175),segments=24,bevel=0.0002,material=steel,body=rudder)
v4.cylinder("rudder_rounded_leading_edge",0.004,0.275,(0,0.608,0.5175),segments=24,bevel=0.0002,material=control_gray,body=rudder)
for z in (0.405,0.53,0.64):
    v4.cylinder("rudder_moving_knuckle",0.0045,0.022,(0,0.608,z),segments=20,bevel=0.0003,material=aluminum,body=rudder)
v4.box("rudder_control_horn",(0.034,0.010,0.010),(0.018,0.653,0.417),bevel=0.002,material=aluminum,body=rudder)
v4.sphere("rudder_horn_bearing",0.004,(0.034,0.653,0.421),segments=16,material=steel,body=rudder)
v4.rod("rudder_pushrod",(0.034,0.653,0.421),(0.034,0.638,0.505),0.0018,material=aluminum,body=rudder)
v4.sphere("rudder_pushrod_end",0.0032,(0.034,0.638,0.505),segments=16,material=steel,body=rudder)
v4.joint("rudder_hinge","revolute",airframe,rudder,origin=(0,0.608,0.405),axis=(0,0,1),limits=(-math.radians(25),math.radians(25)))

# Rear two-blade propeller on a continuously rotating Y-axis motor shaft.
prop=v4.body("pusher_propeller")
# Spinner/hub surfaces along local Y; v4 cylinder default axis Z, rotate into aircraft axis.
v4.cylinder("propeller_hub",0.017,0.035,(0,0.860,0.405),rot=(math.pi/2,0,0),segments=40,bevel=0.002,material=aluminum,body=prop)
v4.sphere("propeller_spinner",0.026,(0,0.880,0.405),segments=32,material=orange,body=prop)
# Tapered propeller loft with changing pitch and a rounded NACA-like section.
def prop_blade_airfoil(name, sign, material, body):
    stations=[(0.012,-0.002,0.050,28,0.13),(0.060,-0.004,0.048,26,0.125),
              (0.120,-0.008,0.040,22,0.115),(0.180,-0.014,0.030,17,0.105),
              (0.225,-0.018,0.021,13,0.09)]
    n=10; verts=[]; faces=[]
    for r,sweep,chord,pitch,thick_ratio in stations:
        angle=math.radians(pitch); cv=Vector((math.cos(angle),math.sin(angle),0)); tv=Vector((-math.sin(angle),math.cos(angle),0))
        section=[]
        for i in range(n+1):
            u=i/n; yt=5*thick_ratio*chord*(0.2969*math.sqrt(max(u,0))-0.1260*u-0.3516*u*u+0.2843*u**3-0.1036*u**4)
            p=Vector((sweep,0.86,0.405+sign*r))+cv*(u*chord)+tv*yt
            section.append(tuple(p))
        for i in range(n-1,0,-1):
            u=i/n; yt=5*thick_ratio*chord*(0.2969*math.sqrt(u)-0.1260*u-0.3516*u*u+0.2843*u**3-0.1036*u**4)
            p=Vector((sweep,0.86,0.405+sign*r))+cv*(u*chord)-tv*yt
            section.append(tuple(p))
        if sign<0:
            section=[(-x,y,z) for x,y,z in section]
        verts.extend(section)
    m=2*n
    for st in range(len(stations)-1):
        for k in range(m):
            a=st*m+k; b=st*m+(k+1)%m
            faces.append((a,b,b+m,a+m))
    faces.append(tuple(range(m-1,-1,-1)))
    faces.append(tuple((len(stations)-1)*m+k for k in range(m)))
    mesh_object(name,verts,faces,material,body)
prop_blade_airfoil("prop_blade_upper",1,carbon,prop)
prop_blade_airfoil("prop_blade_lower",-1,carbon,prop)
# Narrow high-visibility tip decals follow the swept blades.
for sign in (-1,1):
    v4.sphere("prop_tip_safety_mark",0.005,(-sign*0.007,0.862,0.405+sign*0.222),segments=20,material=orange,body=prop)
v4.cylinder("prop_retaining_nut",0.006,0.007,(0,0.887,0.405),rot=(math.pi/2,0,0),segments=6,bevel=0.0008,material=steel,body=prop)
v4.joint("propeller_spin","continuous",airframe,prop,origin=(0,0.860,0.405),axis=(0,1,0))

# Save at the mechanically neutral pose.
v4.rest()
v4.save(os.path.join(os.getcwd(),"asset.blend"))
print("saved asset.blend")
