"""Detailed twist-action pen. Run with Blender in this directory."""
import math, os, sys
import bpy
from mathutils import Matrix
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import v4lib as v4

v4.reset()

# Finishes: dark ink-blue lacquer, black elastomer, nickel and refill steel.
navy = v4.painted("midnight_blue_lacquer", (0.035, 0.105, 0.23), roughness=0.24, coat=0.8)
blue_trim = v4.painted("deep_blue_trim", (0.025, 0.065, 0.14), roughness=0.3, coat=0.65)
rubber = v4.rubber("charcoal_grip", (0.035, 0.04, 0.045), roughness=0.78)
nickel = v4.metal("satin_nickel", (0.70, 0.73, 0.76), roughness=0.26)
bright = v4.metal("polished_nickel", (0.84, 0.86, 0.88), roughness=0.16, brushed=False)
steel = v4.metal("refill_steel", (0.52, 0.56, 0.59), roughness=0.34)
ball_metal = v4.metal("ballpoint_tungsten", (0.19, 0.21, 0.23), roughness=0.2, brushed=False)
tip_gold = v4.metal("ballpoint_nib_gold", (0.78, 0.55, 0.22), roughness=0.22, brushed=False)
ink = v4.plastic("ink_tube", (0.035, 0.055, 0.075), roughness=0.38, texture=0.06)

# Dimensions in metres. Pen points down along -Z; top of crown is z=145 mm.
lower = v4.body("lower_body")
upper = v4.body("upper_barrel")
refill = v4.body("refill")

# Lower shell is a thin-walled turned tube, with realistic open bore for the cartridge.
v4.lathe("lower_lacquer_shell", [(0.00455,0.030),(0.00525,0.032),(0.00525,0.062),
          (0.00515,0.065),(0.00365,0.065),(0.00365,0.031),(0.0040,0.030)],
         material=navy, body=lower)
# Nose cone/socket, hollow so the refill point can travel through it.
v4.lathe("tapered_nose_cone", [(0.0014,0.004),(0.0015,0.005),(0.0036,0.022),
          (0.0045,0.030),(0.00375,0.031),(0.0030,0.023),(0.0006,0.006),(0.0006,0.004)],
         material=bright, body=lower)
# Dark annular liner makes the open 1.2 mm bore legible while leaving clearance for the nib.
v4.lathe("nose_bore_liner", [(0.00060,0.004),(0.00060,0.0054),(0.00058,0.0054),(0.00058,0.004)],
         material=rubber, body=lower)
v4.torus("nose_socket_seam", 0.00425, 0.00028, loc=(0,0,0.0297), material=nickel, body=lower)
# A dark internal nose bushing and a fine brass-toned contact ring.
v4.lathe("nose_bushing", [(0.0031,0.022),(0.00345,0.022),(0.00345,0.027),(0.0031,0.027)],
         material=blue_trim, body=lower)
v4.torus("nose_contact_ring", 0.00372, 0.00018, loc=(0,0,0.0302), material=nickel, body=lower)

# Rubber grip lands and narrow flutes, terminating at crisp molded shoulders.
v4.lathe("grip_core", [(0.0049,0.031),(0.00525,0.032),(0.00525,0.047),
          (0.00495,0.048),(0.00435,0.048),(0.00435,0.032)], material=rubber, body=lower)
for z in (0.033,0.0355,0.038,0.0405,0.043,0.0455,0.047):
    v4.torus("grip_rib_%.4f" % z, 0.00524, 0.00020, loc=(0,0,z), material=rubber, body=lower)
v4.torus("grip_front_bead", 0.00525, 0.00033, loc=(0,0,0.032), material=nickel, body=lower)
v4.torus("grip_rear_bead", 0.00523, 0.00025, loc=(0,0,0.048), material=nickel, body=lower)

# Fixed cam sleeve. A broad annular track band is visible through the 8 mm joint gap.
v4.lathe("cam_sleeve", [(0.00505,0.0615),(0.00565,0.062),(0.00565,0.0705),
          (0.0051,0.071),(0.00365,0.071),(0.00365,0.062)], material=steel, body=lower)
v4.torus("cam_lower_rim", 0.00555, 0.00030, loc=(0,0,0.0624), material=bright, body=lower)
v4.torus("cam_upper_rim", 0.00555, 0.00030, loc=(0,0,0.0697), material=bright, body=lower)
# Twin raised helical cam ramps on the sleeve surface.
for phase in (0.0, math.pi):
    pts=[]
    for i in range(97):
        t=i/96
        a=phase + 2*math.pi*t
        z=0.0630 + 0.0060*t
        pts.append((0.00566*math.cos(a),0.00566*math.sin(a),z))
    v4.tube("helical_cam_ramp_%d" % int(phase>0), pts, 0.00024, material=bright, body=lower)
# Small fixed indexing markers and two detent pockets around sleeve perimeter.
for i,a in enumerate((math.radians(30), math.radians(210))):
    x,y=0.00568*math.cos(a),0.00568*math.sin(a)
    v4.sphere("cam_detent_%d"%i, 0.00042, (x,y,0.066), material=blue_trim, body=lower)

# Upper barrel lower skirt sits around (with clearance over) the fixed cam sleeve.
v4.lathe("rotating_skirt", [(0.00608,0.0702),(0.00645,0.0708),(0.00645,0.0785),
          (0.0061,0.079),(0.00588,0.079),(0.00588,0.0708)], material=blue_trim, body=upper)
# Crowned main tube; thin wall around refill, with softly turned shoulders.
main_shell = v4.lathe("upper_lacquer_barrel", [(0.00575,0.0775),(0.0060,0.079),(0.0060,0.1385),
          (0.00585,0.141),(0.00555,0.142),(0.00415,0.142),(0.00415,0.079)],
         material=navy, body=upper)
# Seam and crown metal details.
v4.torus("upper_seam_ring", 0.00640, 0.00025, loc=(0,0,0.0784), material=bright, body=upper)
v4.torus("crown_lower_ring", 0.00591, 0.00024, loc=(0,0,0.1377), material=nickel, body=upper)
v4.lathe("crown_finial", [(0.0040,0.141),(0.00555,0.141),(0.0055,0.143),
          (0.0048,0.145),(0,0.145)], material=navy, body=upper)
v4.cylinder("finial_inlay", 0.0023, 0.00045, loc=(0,0,0.1451), material=bright, body=upper)

# Pocket clip: formed satin-nickel strip on the front side, with integral bridge and a curved toe.
# The clip legs are kept over the barrel surface and terminate at the top clip mount.
v4.box("clip_mount_pad", (0.0020,0.0022,0.006), (0,-0.00585,0.132), bevel=0.0007, material=nickel, body=upper)
v4.rod("clip_mount_bridge", (0,-0.0060,0.130), (0,-0.0061,0.127), 0.00072, material=bright, body=upper)
clip_pts=[(0,-0.00615,0.128),(0,-0.00645,0.124),(0,-0.00675,0.117),
          (0,-0.00695,0.109),(0,-0.00695,0.101),(0,-0.0067,0.094),
          (0,-0.0061,0.089),(0,-0.00585,0.088)]
v4.tube("formed_pocket_clip", clip_pts, 0.00062, material=bright, body=upper, resolution=16)
# Fine pressed channel down the clip's spine for a finished stamped-metal look.
v4.tube("clip_spine_channel", [(0.00020,y,z) for _,y,z in clip_pts[1:-1]], 0.00010,
        material=nickel, body=upper, resolution=10)

# Small, restrained front-face imprint, conformed to the curved lacquer surface.
v4.text("barrel_brand", "NOVA  •  0.7", 0.00145, loc=(0,-0.00595,0.115),
        rot=(math.pi/2,0,0), extrude_depth=0.00008, material=bright, body=upper, on=main_shell, height=0.00009)

# Refill carriage slides through hollow body. Refill components form one moving rigid assembly.
v4.cylinder("ink_reservoir", 0.00138, 0.092, loc=(0,0,0.084), material=ink, body=refill, bevel=0.0002)
v4.cylinder("steel_front_shoulder", 0.00165, 0.005, loc=(0,0,0.0325), material=steel, body=refill, bevel=0.0002)
# Narrow metal core joins the point, shoulder and ink cartridge into one true refill assembly.
v4.cylinder("refill_core_stem", 0.00072, 0.022, loc=(0,0,0.0305), material=steel, body=refill, bevel=0.0001)
# 3 mm writing nib ends 2 mm inside the nose opening at rest; the polished ball is visible at its point.
v4.lathe("ballpoint_nib", [(0,0.006),(0.00050,0.0065),(0.00050,0.0088),
          (0.00042,0.0092),(0.00034,0.0087),(0,0.006)],
         material=tip_gold, body=refill)
v4.sphere("ballpoint_ball", 0.00048, (0,0,0.00625), material=ball_metal, body=refill)
# Slim feed stem stays within the 1.2 mm nose bore as the refill advances.
v4.cylinder("nib_feed_stem", 0.00042, 0.012, loc=(0,0,0.0145), material=steel, body=refill, bevel=0.00008)
v4.cylinder("rear_drive_plug", 0.0017, 0.004, loc=(0,0,0.132), material=steel, body=refill, bevel=0.00025)
v4.torus("refill_collar", 0.00165, 0.00022, loc=(0,0,0.035), material=bright, body=refill)

# Lay the pen on its side for the studio pose. The refill remains coaxial, but its travel now runs
# horizontally so the studio floor cannot hide the deployed nib. The 0.77 mm axial offset puts
# the ball 1.5 mm inside the cone mouth at rest.
horizontal = Matrix.Translation((0, 0, 0.008)) @ Matrix.Rotation(math.pi/2, 4, 'Y')
refill_offset = Matrix.Translation((-0.00077, 0, 0))
for obj in bpy.data.objects:
    if obj.type not in ('MESH', 'CURVE'):
        continue
    owner = obj.parent
    while owner is not None and owner.get('v4_kind') != 'body':
        owner = owner.parent
    transform = (refill_offset @ horizontal) if owner == refill else horizontal
    if obj.type == 'MESH':
        local_transform = obj.matrix_world.inverted() @ transform @ obj.matrix_world
        obj.data.transform(local_transform)
    else:
        obj.matrix_world = transform @ obj.matrix_world

# The barrel's cam rotation is centred at the sleeve; refill travel is the axial follower output.
v4.joint("barrel_twist", "revolute", lower, upper,
         origin=(0.069,0,0.008), axis=(1,0,0), limits=(-0.85,0.85))
v4.joint("refill_travel", "prismatic", lower, refill,
         origin=(0.025,0,0.008), axis=(-1,0,0), limits=(0,0.005))

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