# render_still.py: the slider crank GLB from FreeCAD, made into a Blender scene and rendered as one still.
# Blender 5.3. In the Blender window: Scripting tab, Open this file, set GLB below, Run Script.
# Without a window:  nice blender -b -P render_still.py -- /abs/path/SliderCrank-render.glb /abs/out/dir
# Writes SliderCrank.blend (the scene, for render_loop.py) and still.png in the out folder.
#
# What it does, in the order the lesson teaches it:
#   1 import the GLB (metres, part names kept)   2 materials from the item list   3 a floor, a pale world,
#   three lights and a camera, all aimed at one Empty   4 Cycles, few samples, denoise, Standard view   5 render.
import bpy, sys, os, re
from mathutils import Vector

args = sys.argv[sys.argv.index('--') + 1:] if '--' in sys.argv else []
GLB = args[0] if args else os.path.expanduser('~/SliderCrank-render.glb')   # change this in the Blender window
OUT = args[1] if len(args) > 1 else os.path.dirname(GLB)
THREADS = 4                                  # leave the rest of the machine free
SIZE, SAMPLES = (1280, 720), 64
if os.environ.get('QUICK'): SIZE, SAMPLES = (480, 270), 12   # a fast test picture

# ---- 1. a clean scene, then the GLB ----
for o in list(bpy.data.objects): bpy.data.objects.remove(o, do_unlink=True)
bpy.ops.import_scene.gltf(filepath=GLB)

def base_name(o):
    """'Crank001', 'Crank.001' or 'Crank (as assembled)' -> 'Crank'"""
    return re.sub(r'(\s*\(as assembled\))?(\.?\d{3})?$', '', o.name)
parts = {base_name(o): o for o in bpy.data.objects if o.type == 'MESH'}
print('parts:', sorted(parts))

# ---- 2. materials: the item list of lesson 1's drawing says what each part is made of ----
#               base colour (linear)     metallic roughness
FINISH = {
    'steel':     ((0.56, 0.57, 0.58), 1.0, 0.25),   # ground pins, stainless 1.4305
    'bronze':    ((0.62, 0.38, 0.18), 1.0, 0.32),   # the slider, CuSn8
    'anodised':  (None,               0.0, 0.40),   # coloured aluminium: keep the colour from FreeCAD
    'aluminium': ((0.55, 0.56, 0.58), 0.9, 0.45),   # clear anodised plate and guide
}
PART_FINISH = {'Base': 'aluminium', 'Guide': 'aluminium', 'Crank': 'anodised', 'ConnectingRod': 'anodised',
               'Slider': 'bronze', 'PivotPin': 'steel', 'CrankPin': 'steel', 'WristPin': 'steel'}
for name, o in (() if os.environ.get('AS_IMPORTED') else parts.items()):   # AS_IMPORTED=1: FreeCAD's colours only
    m = o.active_material.copy(); m.name = name + ' finish'; o.active_material = m
    b = m.node_tree.nodes['Principled BSDF']
    colour, metal, rough = FINISH[PART_FINISH.get(name, 'aluminium')]
    if colour: b.inputs['Base Color'].default_value = (*colour, 1)
    b.inputs['Metallic'].default_value = metal
    b.inputs['Roughness'].default_value = rough
    for p in o.data.polygons: p.use_smooth = True   # with the GLB's own normals, flat faces stay flat

# ---- 3. stage: floor, world, an Empty to aim at, camera, three lights ----
sc = bpy.context.scene
pts = [o.matrix_world @ Vector(c) for o in parts.values() for c in o.bound_box]
lo = Vector((min(p.x for p in pts), min(p.y for p in pts), min(p.z for p in pts)))
hi = Vector((max(p.x for p in pts), max(p.y for p in pts), max(p.z for p in pts)))
print('size, mm:', [round(1000 * v, 1) for v in hi - lo])

bpy.ops.mesh.primitive_plane_add(size=3, location=(0, 0, lo.z - 0.0002)); floor = bpy.context.object; floor.name = 'Floor'
fm = bpy.data.materials.new('Floor'); fm.use_nodes = True
fb = fm.node_tree.nodes['Principled BSDF']; fb.inputs['Base Color'].default_value = (0.80, 0.78, 0.72, 1); fb.inputs['Roughness'].default_value = 0.85
floor.data.materials.append(fm)

w = bpy.data.worlds.new('Pale'); sc.world = w; w.use_nodes = True
bg = w.node_tree.nodes['Background']; bg.inputs['Color'].default_value = (0.90, 0.89, 0.84, 1); bg.inputs['Strength'].default_value = 0.35

target = bpy.data.objects.new('Target', None); sc.collection.objects.link(target)
target.location = ((lo.x + hi.x) / 2, (lo.y + hi.y) / 2, lo.z + 0.25 * (hi.z - lo.z))
def aim(o):
    c = o.constraints.new('TRACK_TO'); c.target = target; c.track_axis = 'TRACK_NEGATIVE_Z'; c.up_axis = 'UP_Y'

cam = bpy.data.cameras.new('Camera'); cam.lens = 50; cam.clip_start = 0.01
co = bpy.data.objects.new('Camera', cam); sc.collection.objects.link(co); sc.camera = co
co.location = target.location + Vector((0.10, -0.33, 0.23)); aim(co)

for name, offset, watts, size in (('Key', (-0.35, -0.45, 0.55), 4, 0.35),    # bright, front left, high
                                  ('Fill', (0.55, -0.25, 0.25), 1.5, 0.50),    # soft, right, low
                                  ('Rim', (0.10, 0.55, 0.40), 3, 0.30)):     # behind, picks out the edges
    L = bpy.data.lights.new(name, 'AREA'); L.energy = watts; L.size = size
    lo_ = bpy.data.objects.new(name, L); sc.collection.objects.link(lo_); lo_.location = target.location + Vector(offset); aim(lo_)

# ---- 4. render settings ----
sc.render.engine = 'CYCLES'; sc.cycles.device = 'CPU'
sc.cycles.samples = SAMPLES; sc.cycles.use_denoising = True
sc.view_settings.view_transform = 'Standard'          # colours as chosen, not toned down by AgX
sc.render.resolution_x, sc.render.resolution_y = SIZE; sc.render.resolution_percentage = 100
sc.render.threads_mode = 'FIXED'; sc.render.threads = THREADS
sc.render.image_settings.file_format = 'PNG'

print('target at', [round(v, 4) for v in target.location], 'camera at', [round(v, 4) for v in co.location])
STILL = 'as-imported.png' if os.environ.get('AS_IMPORTED') else 'still.png'
if not os.environ.get('AS_IMPORTED'): bpy.ops.wm.save_as_mainfile(filepath=os.path.join(OUT, 'SliderCrank.blend'), compress=True)
# ---- 5. the still ----
sc.render.filepath = os.path.join(OUT, STILL)
bpy.ops.render.render(write_still=True)
print('wrote', sc.render.filepath)
