"""Detailed articulated 48 mm packing tape applicator. Run with Blender's Python."""
import math, os, sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import bpy
import bmesh
import v4lib as v4

v4.reset()
# Materials
blue = v4.plastic("petrol_blue_molded_nylon", color=(0.035, 0.19, 0.22), roughness=0.32)
blue_hi = v4.plastic("blue_edge_panels", color=(0.055, 0.27, 0.29), roughness=0.3)
rubber = v4.rubber("black_grip_rubber", color=(0.025, 0.032, 0.033), roughness=0.78)
roller_mat = v4.rubber("roller_neoprene", color=(0.07, 0.075, 0.073), roughness=0.58)
steel = v4.metal("satin_stainless", color=(0.67, 0.72, 0.73), roughness=0.28, brushed=True)
edge = v4.metal("darkened_steel", color=(0.22, 0.25, 0.26), roughness=0.42, brushed=False)
tape = v4.plastic("amber_packing_tape", color=(0.72, 0.49, 0.23), roughness=0.25, texture=0.035)
tape_band = v4.plastic("wound_layer_edge", color=(0.73, 0.50, 0.27), roughness=0.32, texture=0.025)
clear_tape = v4.plastic("translucent_amber_film", color=(0.82, 0.63, 0.39), roughness=0.2, texture=0.025)
clear_bsdf = next(n for n in clear_tape.node_tree.nodes if n.type == "BSDF_PRINCIPLED")
clear_bsdf.inputs["Alpha"].default_value = 0.58
clear_bsdf.inputs["Transmission Weight"].default_value = 0.32
clear_tape.surface_render_method = "DITHERED"
kraft = v4.mat("kraft_cardboard", color=(0.52, 0.34, 0.18), roughness=0.82)
white = v4.mat("raised_cream_print", color=(0.85, 0.82, 0.68), roughness=0.55)

frame = v4.body("frame")
roll = v4.body("tape_roll")
arm = v4.body("applicator_arm")
roller = v4.body("pressure_roller")
blade = v4.body("cutter_blade")

# Utility: smooth a closed polygon through its control points (Catmull-Rom profile).
def smooth_outline(points, steps=3):
    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
            x=0.5*((2*p1[0])+(-p0[0]+p2[0])*t+(2*p0[0]-5*p1[0]+4*p2[0]-p3[0])*t2+(-p0[0]+3*p1[0]-3*p2[0]+p3[0])*t3)
            y=0.5*((2*p1[1])+(-p0[1]+p2[1])*t+(2*p0[1]-5*p1[1]+4*p2[1]-p3[1])*t2+(-p0[1]+3*p1[1]-3*p2[1]+p3[1])*t3)
            out.append((x,y))
    return out

# Utility: a bevelled, centered prism whose outline is in world Y/Z and whose width is X.
def yz_prism(name, outline, width, xcenter, body, material, bevel=0.001):
    outline=smooth_outline(outline,3)
    n=len(outline); x0=xcenter-width/2; x1=xcenter+width/2
    verts=[(x0,y,z) for y,z in outline]+[(x1,y,z) for y,z in outline]
    faces=[tuple(range(n-1,-1,-1)), tuple(range(n,2*n))]
    for i in range(n):
        j=(i+1)%n; faces.append((i,j,n+j,n+i))
    me=bpy.data.meshes.new(name+"_mesh"); me.from_pydata(verts,[],faces); me.update()
    ob=bpy.data.objects.new(name,me); bpy.context.collection.objects.link(ob)
    if material: ob.data.materials.append(material)
    if bevel:
        mod=ob.modifiers.new("soft molded edges","BEVEL"); mod.width=bevel; mod.segments=5
        mod.profile=0.5
        mod2=ob.modifiers.new("weighted corner normals","WEIGHTED_NORMAL")
    v4.part(ob,body); return ob

# Crosswise blade plate, profile lies in X/Z and thickness runs along Y.
def xz_prism(name, outline, depth, ycenter, body, material, bevel=0.0004):
    n=len(outline); y0=ycenter-depth/2; y1=ycenter+depth/2
    verts=[(x,y0,z) for x,z in outline]+[(x,y1,z) for x,z in outline]
    faces=[tuple(range(n-1,-1,-1)),tuple(range(n,2*n))]
    for i in range(n):
        j=(i+1)%n; faces.append((i,j,n+j,n+i))
    me=bpy.data.meshes.new(name+"_mesh"); me.from_pydata(verts,[],faces); me.update()
    ob=bpy.data.objects.new(name,me); bpy.context.collection.objects.link(ob); ob.data.materials.append(material)
    if bevel:
        mod=ob.modifiers.new("ground edge bevel","BEVEL"); mod.width=bevel; mod.segments=2
        ob.modifiers.new("weighted normals","WEIGHTED_NORMAL")
    v4.part(ob,body); return ob

# Solid annular winding, axial direction X. All four surfaces are modeled explicitly.
def annulus(name, outer, inner, width, xcenter, ycenter, zcenter, body, material, steps=96, outer_material=None):
    vs=[]
    for x in (xcenter-width/2,xcenter+width/2):
        for r in (outer,inner):
            for i in range(steps):
                a=2*math.pi*i/steps
                vs.append((x,ycenter+r*math.cos(a),zcenter+r*math.sin(a)))
    def ix(side,ring,i): return side*2*steps+ring*steps+(i%steps)
    fs=[]
    for i in range(steps):
        j=(i+1)%steps
        fs.append((ix(0,0,i),ix(0,0,j),ix(1,0,j),ix(1,0,i)))
        fs.append((ix(0,1,j),ix(0,1,i),ix(1,1,i),ix(1,1,j)))
        fs.append((ix(0,0,j),ix(0,0,i),ix(0,1,i),ix(0,1,j)))
        fs.append((ix(1,0,i),ix(1,0,j),ix(1,1,j),ix(1,1,i)))
    me=bpy.data.meshes.new(name+"_mesh"); me.from_pydata(vs,[],fs); me.update()
    bm=bmesh.new(); bm.from_mesh(me); bmesh.ops.recalc_face_normals(bm,faces=bm.faces); bm.to_mesh(me); bm.free()
    ob=bpy.data.objects.new(name,me); bpy.context.collection.objects.link(ob); ob.data.materials.append(material)
    if outer_material:
        ob.data.materials.append(outer_material)
        for poly in me.polygons:
            radii=[math.hypot(me.vertices[i].co.y-ycenter,me.vertices[i].co.z-zcenter) for i in poly.vertices]
            if radii and all(abs(r-outer)<1e-5 for r in radii): poly.material_index=1
    v4.part(ob,body); return ob

# Axles run across the 50 mm tape width (X).
def axle_cyl(name, radius, depth, loc, body, mat, bevel=0.0005):
    return v4.cylinder(name,radius,depth,loc,rot=(0,math.pi/2,0),segments=48,
                       bevel=bevel,material=mat,body=body)

def screw_x(name,x,y,z,body=frame):
    axle_cyl(name,0.0032,0.0018,(x,y,z),body,steel,0.0002)

# Main frame is a pair of molded side cheeks, leaving the wound roll exposed.
# Rear bridge, lower handle root, and forward nose form a strong one-piece carrier.
for sx in (-1,1):
    x=sx*0.035
    yz_prism("side_cheek_"+str(sx), [
        (0.068,0.179),(0.082,0.173),(0.082,0.148),(0.076,0.119),
        (0.045,0.098),(0.011,0.102),(-0.025,0.125),(-0.047,0.148),
        (-0.076,0.146),(-0.122,0.119),(-0.155,0.111),(-0.162,0.096),
        (-0.142,0.080),(-0.108,0.073),(-0.070,0.082),(-0.044,0.105),
        (-0.032,0.061),(-0.005,0.031),(0.044,0.022),(0.077,0.043),
        (0.087,0.076),(0.060,0.104),(0.047,0.128),(0.061,0.162)
    ],0.006,x,frame,blue_hi,0.002)
# Central bridge web and nose block; slight separation between cheek inner faces and rolling tape.
# The open center is intentional: the tape leader and roller remain visible between cheeks.

# Roll hub: fixed steel spindle and flange cheeks, with a small felt brake shoe.
roll_y, roll_z = 0.035, 0.165
axle_cyl("fixed_core_spindle",0.017,0.068,(0,roll_y,roll_z),frame,steel)
for sx in (-1,1):
    axle_cyl("hub_flange_"+str(sx),0.024,0.003,(sx*0.029,roll_y,roll_z),frame,blue_hi,0.0008)
    axle_cyl("hub_cap_"+str(sx),0.009,0.0035,(sx*0.032,roll_y,roll_z),frame,steel,0.0007)
    # Fixed knurled tension dial sits just outside the roll and its fixed flange.
    axle_cyl("brake_adjuster_"+str(sx),0.013,0.002,(sx*0.0346,roll_y,roll_z),frame,blue_hi,0.0006)
    for k in range(12):
        a=2*math.pi*k/12
        axle_cyl("brake_dial_grip_%s_%02d"%(sx,k),0.00105,0.0015,
                 (sx*0.03635,roll_y+0.0122*math.cos(a),roll_z+0.0122*math.sin(a)),frame,steel,0.00015)
# brake pad touches the inner side of the roll near its upper rear quadrant
v4.rod("brake_pad_stem",(0,roll_y+0.017,roll_z),(0,roll_y+0.018,roll_z),0.0025,material=steel,body=frame)
v4.box("felt_brake_pad",(0.018,0.004,0.010),(0,roll_y+0.020,roll_z),bevel=0.0008,material=rubber,body=frame)
# Tape roll is a real annular body, with a visible kraft core and subtly banded windings.
annulus("wound_amber_tape",0.058,0.022,0.048,0,roll_y,roll_z,roll,tape,outer_material=clear_tape)
annulus("kraft_core",0.0235,0.0205,0.048,0,roll_y,roll_z,roll,kraft)
# Fine axial winding seams wrap the clear film around the circumference.
# They sit almost flush with the skin so the roll reads as smooth film.
for wi in range(6):
    x=-0.019+wi*0.0076
    annulus("outer_winding_track_%02d"%wi,0.05808,0.05801,0.00022,x,roll_y,roll_z,roll,
            tape,96)
# Contrasting side-face core rim and fine, closely spaced winding seams.
for sx in (-1,1):
    annulus("visible_cardboard_core_rim_"+str(sx),0.0218,0.0105,0.0006,sx*0.0243,roll_y,roll_z,roll,kraft,72)
    for ri,ro in enumerate((0.0562,0.0535,0.0508,0.0481)):
        annulus("winding_seam_%s_%02d"%(sx,ri),ro,ro-0.00035,0.0006,sx*0.0243,roll_y,roll_z,roll,tape_band,96)

# Pistol grip drops back from the rear cheek. Its wide root meets both molded cheeks;
# the elastomer body has softened edges and fills the natural hand-contact area.
yz_prism("ergonomic_handle_grip",[(0.052,0.065),(0.075,0.047),(0.088,0.021),(0.101,-0.015),(0.103,-0.048),(0.089,-0.078),(0.067,-0.094),(0.044,-0.088),(0.030,-0.071),(0.038,-0.060),(0.024,-0.049),(0.037,-0.037),(0.023,-0.024),(0.037,-0.011),(0.022,0.003),(0.034,0.021),(0.043,0.045)],0.067,0,frame,rubber,0.006)
# Structural ribs and gussets between the hub and grip/nose.
for sx in (-1,1):
    v4.rod("rear_support_"+str(sx),(sx*0.032,0.067,0.145),(sx*0.032,0.060,0.061),0.0045,material=blue_hi,body=frame)
    v4.rod("nose_gusset_"+str(sx),(sx*0.032,-0.072,0.126),(sx*0.032,-0.139,0.103),0.004,material=blue_hi,body=frame)
# Fixing screws and molded circular axle bosses on both cheeks.
for sx in (-1,1):
    axle_cyl("arm_pivot_boss_"+str(sx),0.009,0.003,(sx*0.039, -0.018,0.112),frame,blue_hi)
    screw_x("cheek_fastener_"+str(sx),sx*0.039,0.064,0.136)
    screw_x("handle_fastener_"+str(sx),sx*0.039,0.060,0.058)

# Static leader strip from the roll toward the pressure roller; the tape itself is flexible in use.
# A slim continuous ribbon approximates the local tape path without inventing a coupling.
def tape_ribbon(name, path, width, body, material):
    verts=[]
    for y,z in path:
        verts.extend([(-width/2,y,z),(width/2,y,z)])
    faces=[]
    for i in range(len(path)-1): faces.append((2*i,2*i+1,2*i+3,2*i+2))
    me=bpy.data.meshes.new(name+"_mesh"); me.from_pydata(verts,[],faces); me.update()
    ob=bpy.data.objects.new(name,me); bpy.context.collection.objects.link(ob); ob.data.materials.append(material); v4.part(ob,body)
    return ob
# The leader descends from the roll to the rear of the pressure roller, wraps
# around its underside, then rises to the cutter. A small radial offset keeps
# the film visibly seated on the rubber without z-fighting.
tape_path=[(-0.0061,0.1239),(-0.032,0.112),(-0.060,0.098),(-0.082,0.086),
           (-0.090,0.080),(-0.099,0.072),(-0.104,0.064)]
contact_radius=0.01435
for i in range(19):
    theta=math.radians(-180*i/18)
    tape_path.append((-0.121+contact_radius*math.cos(theta),
                      0.052+contact_radius*math.sin(theta)))
tape_path.extend([(-0.139,0.058),(-0.145,0.073),(-0.158,0.106)])
tape_ribbon("visible_tape_leader",tape_path,0.047,frame,tape)

# Spring arm: paired links hinge on transverse pin and support the free-turning pressure roller.
pivot=(-0.018,0.112); roller_center=(-0.121,0.052)
for sx in (-1,1):
    v4.rod("arm_link_"+str(sx),(sx*0.027,pivot[0],pivot[1]),(sx*0.027,roller_center[0],roller_center[1]),0.005,material=blue_hi,body=arm)
    axle_cyl("arm_pivot_collar_"+str(sx),0.0045,0.003,(sx*0.028,pivot[0],pivot[1]),arm,steel,0.0003)
    axle_cyl("roller_axle_collar_"+str(sx),0.0045,0.003,(sx*0.028,roller_center[0],roller_center[1]),arm,steel,0.0003)
axle_cyl("roller_axle",0.0055,0.074,(0,roller_center[0],roller_center[1]),arm,steel,0.0004)
# Cylindrical pressure roller and end flanges are one rotating body.
annulus("rubber_pressure_roller",0.014,0.0058,0.052,0,roller_center[0],roller_center[1],roller,roller_mat,64)
for sx in (-1,1):
    axle_cyl("roller_end_cap_"+str(sx),0.016,0.003,(sx*0.0275,roller_center[0],roller_center[1]),roller,blue,0.0008)
    axle_cyl("roller_bearing_ring_"+str(sx),0.006,0.001,(sx*0.0295,roller_center[0],roller_center[1]),roller,steel,0.0003)

# Fixed cutter bracket at the nose. Two ears carry a transverse hinge pin.
for sx in (-1,1):
    yz_prism("cutter_bracket_ear_"+str(sx),[(-0.151,0.118),(-0.169,0.119),(-0.174,0.103),(-0.164,0.091),(-0.148,0.096)],0.007,sx*0.035,frame,steel,0.001)
axle_cyl("cutter_hinge_pin",0.0035,0.078,(0,-0.158,0.106),frame,steel,0.0003)
# Crosswise blade body; serrations are real triangular teeth along its lower cutting edge.
blade_outline=[(-0.037,0.111),(0.037,0.111),(0.037,0.100)]
tooth_pitch=0.072/31
for k in range(30,-1,-1):
    x=-0.036+k*tooth_pitch
    blade_outline.extend([(x+tooth_pitch*0.50,0.092),(x+tooth_pitch,0.100)])
blade_outline.append((-0.037,0.100))
xz_prism("tempered_serrated_blade",blade_outline,0.004,-0.165,blade,steel,0.00025)
# Dark blade heel and hinge barrels travel with the blade.
for sx in (-1,1):
    axle_cyl("blade_hinge_knuckle_"+str(sx),0.0046,0.011,(sx*0.030,-0.158,0.106),blade,edge,0.00025)
    axle_cyl("blade_hinge_end_cap_"+str(sx),0.0055,0.0015,(sx*0.0375,-0.158,0.106),blade,steel,0.0002)
# Safety guard lip fixed above the cutting teeth.
v4.box("blade_guard_lip",(0.078,0.004,0.003),(0,-0.164,0.116),bevel=0.001,material=blue,body=frame)

# Tree joints: all axes are real transverse pins along X.
v4.joint("roll_spin","continuous",frame,roll,origin=(0,roll_y,roll_z),axis=(1,0,0))
v4.joint("arm_hinge","revolute",frame,arm,origin=(0,pivot[0],pivot[1]),axis=(1,0,0),limits=(0,math.radians(18)))
v4.joint("roller_spin","continuous",arm,roller,origin=(0,roller_center[0],roller_center[1]),axis=(1,0,0))
v4.joint("blade_hinge","revolute",frame,blade,origin=(0,-0.158,0.106),axis=(1,0,0),limits=(-math.radians(35),math.radians(42)))

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