"""Geoff Boyle's slow-motion white-wine shot, rebuilt as a Cycles scene.

Kit (Cooke Optics, "Don't complicate lighting", ~1:20):
  - the redhead behind the glass, firing straight down the lens
  - the trace frame between them, close to the glass  -> a glowing backdrop
  - black flags brought in either side                -> the dark lines that draw the glass
  - pour the wine

Usage:
  blender -b --factory-startup --python wine_glass.py -- --pass full --out /work/renders/wine/full.png
Passes: bare (redhead only), trace (+ trace frame), full (+ flags), overview
Pour: --pour <cache dir> --frame N  uses a baked Mantaflow sim (see wine_pour_bake.py)
"""
import argparse, math, sys
import bpy, bmesh
from mathutils import Vector

argv = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []
ap = argparse.ArgumentParser()
ap.add_argument("--pass", dest="pas", default="full", choices=["bare", "trace", "full", "overview"])
ap.add_argument("--out", default="/work/renders/wine/full.png")
ap.add_argument("--samples", type=int, default=256)
ap.add_argument("--res", type=int, default=1000)
ap.add_argument("--exposure", type=float, default=1.6)
ap.add_argument("--slot", type=float, default=0.06, help="half-width of the gap between the flags, m")
ap.add_argument("--fill", type=float, default=0.45, help="wine level as a fraction of bowl height")
ap.add_argument("--bake", default="", help="bake a Mantaflow pour into this cache dir, save pour.blend beside it, don't render")
ap.add_argument("--fres", type=int, default=128, help="sim resolution along the domain's longest side")
ap.add_argument("--frames", type=int, default=96)
ap.add_argument("--timescale", type=float, default=0.25, help="0.25 = 4x slow motion")
ap.add_argument("--save-blend", default="")
ap.add_argument("--ovcam", default="1.6,-1.5,1.0")
a = ap.parse_args(argv)

bpy.ops.wm.read_factory_settings(use_empty=True)
scn = bpy.context.scene

def look_at(obj, target):
    obj.rotation_euler = (Vector(target) - obj.location).to_track_quat("-Z", "Y").to_euler()

def principled(name, **kw):
    m = bpy.data.materials.new(name); m.use_nodes = True
    b = m.node_tree.nodes["Principled BSDF"]
    for k, v in kw.items():
        b.inputs[k].default_value = v
    return m, b

# ---------------------------------------------------------------- the glass
# A white-wine glass as a lathe profile (r, z) in metres, outer wall up then inner wall down.
OUTER = [(0.0, 0.0), (0.038, 0.0), (0.040, 0.002), (0.006, 0.006), (0.0035, 0.012),
         (0.0035, 0.085), (0.010, 0.095), (0.028, 0.110), (0.040, 0.135),
         (0.043, 0.160), (0.041, 0.185), (0.036, 0.210)]
def smooth(pts, n=6):
    """Catmull-Rom through the control points, n samples per segment, ends kept."""
    out = []
    P = [pts[0]] + pts + [pts[-1]]
    for i in range(1, len(P) - 2):
        p0, p1, p2, p3 = P[i - 1], P[i], P[i + 1], P[i + 2]
        for k in range(n):
            t = k / n
            out.append(tuple(0.5 * ((2 * p1[c]) + (-p0[c] + p2[c]) * t + (2 * p0[c] - 5 * p1[c] + 4 * p2[c] - p3[c]) * t * t
                                    + (-p0[c] + 3 * p1[c] - 3 * p2[c] + p3[c]) * t ** 3) for c in (0, 1)))
    out.append(pts[-1])
    return [(max(r, 0.0), z) for r, z in out]
# keep the foot and stem crisp, smooth the bowl
OUTER = OUTER[:6] + smooth(OUTER[5:])[1:]
WALL = 0.0012
def inner_profile():
    # bowl interior: offset the bowl part of the outer profile inward by the wall thickness
    pts = []
    for r, z in OUTER[::-1]:
        if z < 0.097:
            break
        pts.append((max(r - WALL, 0.0), z if z < 0.21 else z))
    pts.append((0.0, 0.0972))
    return pts
INNER = inner_profile()
GLASS_PROFILE = OUTER + [(OUTER[-1][0] - WALL, OUTER[-1][1])] + INNER[1:]

def lathe(name, profile, steps=128, cap_axis=True):
    me = bpy.data.meshes.new(name); bm = bmesh.new()
    axis = {j: bm.verts.new((0, 0, z)) for j, (r, z) in enumerate(profile) if r == 0}
    rings = []
    for i in range(steps):
        t = 2 * math.pi * i / steps
        rings.append([axis[j] if j in axis else bm.verts.new((r * math.cos(t), r * math.sin(t), z))
                      for j, (r, z) in enumerate(profile)])
    for i in range(steps):
        a_, b_ = rings[i], rings[(i + 1) % steps]
        for j in range(len(profile) - 1):
            vs = [a_[j], b_[j], b_[j + 1], a_[j + 1]]
            uniq = list(dict.fromkeys(vs))
            if len(uniq) >= 3:
                try: bm.faces.new(uniq)
                except ValueError: pass
    bmesh.ops.recalc_face_normals(bm, faces=bm.faces)
    bm.to_mesh(me); bm.free()
    o = bpy.data.objects.new(name, me); scn.collection.objects.link(o)
    for p in me.polygons: p.use_smooth = True
    return o

glass = lathe("glass", GLASS_PROFILE)
glass_mat, gb = principled("glass", **{"Transmission Weight": 1.0, "Roughness": 0.0, "IOR": 1.52,
                                      "Base Color": (1, 1, 1, 1)})
glass.data.materials.append(glass_mat)

# ---------------------------------------------------------------- the wine (still version)
wine_mat, wb = principled("wine", **{"Transmission Weight": 1.0, "Roughness": 0.0, "IOR": 1.34,
                                    "Base Color": (1, 1, 1, 1)})
# pale straw colour as absorption in the volume, not as surface tint
vol = wine_mat.node_tree.nodes.new("ShaderNodeVolumeAbsorption")
vol.inputs["Color"].default_value = (0.98, 0.86, 0.45, 1); vol.inputs["Density"].default_value = 22.0
wine_mat.node_tree.links.new(vol.outputs[0], wine_mat.node_tree.nodes["Material Output"].inputs["Volume"])

if not a.bake:
    z0, z1 = 0.0975, 0.0975 + a.fill * (0.21 - 0.0975)
    prof = [(0.0, z0)]
    for r, z in INNER[::-1]:
        if z0 < z < z1:
            prof.append((max(r - 0.0002, 0), z))
    # radius at fill height by interpolation along the inner wall
    pts = sorted(INNER, key=lambda p: p[1])
    for (r0, za), (r1, zb) in zip(pts, pts[1:]):
        if za <= z1 <= zb:
            rf = r0 + (r1 - r0) * (z1 - za) / (zb - za) - 0.0002; break
    prof += [(rf, z1), (rf * 0.97, z1 + 0.0012), (0.0, z1 + 0.0012)]   # a hint of meniscus
    wine = lathe("wine", prof)
    wine.data.materials.append(wine_mat)

# ---------------------------------------------------------------- table and room
table_mat, _ = principled("black_perspex", **{"Base Color": (0.01, 0.01, 0.01, 1), "Roughness": 0.05})
bpy.ops.mesh.primitive_plane_add(size=3, location=(0, 0.5, 0)); bpy.context.active_object.data.materials.append(table_mat)
room_mat, _ = principled("studio", **{"Base Color": (0.05, 0.05, 0.05, 1), "Roughness": 0.9})
bpy.ops.mesh.primitive_cube_add(size=1, location=(0, 0.5, 1.0)); room = bpy.context.active_object
room.scale = (6, 8, 3.5); room.location.z = 1.2; room.data.materials.append(room_mat)

# ---------------------------------------------------------------- camera
GLASS_C = Vector((0, 0, 0.13))
cd = bpy.data.cameras.new("cam"); cam = bpy.data.objects.new("cam", cd); scn.collection.objects.link(cam)
scn.camera = cam; cd.sensor_width = 36
if a.pas == "overview":
    cam.location = tuple(map(float, a.ovcam.split(","))); cd.lens = 20; look_at(cam, (0, 0.25, 0.12))
    # a stand-in camera body where the real lens is
    body_mat, _ = principled("cambody", **{"Base Color": (0.06, 0.06, 0.06, 1), "Roughness": 0.4})
    bpy.ops.mesh.primitive_cube_add(size=1, location=(0, -1.03, 0.13))
    cb = bpy.context.active_object; cb.scale = (0.12, 0.16, 0.10); cb.data.materials.append(body_mat)
    bpy.ops.mesh.primitive_cylinder_add(radius=0.035, depth=0.09, location=(0, -0.92, 0.13))
    ln = bpy.context.active_object; ln.rotation_euler = (math.pi / 2, 0, 0); ln.data.materials.append(body_mat)
else:
    cam.location = (0, -0.95, 0.13); cd.lens = 100; look_at(cam, Vector((0, 0, 0.112)))

# ---------------------------------------------------------------- the kit
# redhead behind the glass, on the lens axis, firing straight at the camera
RH = Vector((0, 1.8, 0.15))
ld = bpy.data.lights.new("redhead", "SPOT"); ld.energy = 800 * 0.12
ld.spot_size = math.radians(40); ld.spot_blend = 0.3; ld.shadow_soft_size = 0.03
ld.use_nodes = True
bbn = ld.node_tree.nodes.new("ShaderNodeBlackbody"); bbn.inputs[0].default_value = 3200
ld.node_tree.links.new(bbn.outputs[0], ld.node_tree.nodes["Emission"].inputs["Color"])
rh = bpy.data.objects.new("redhead", ld); scn.collection.objects.link(rh); rh.location = RH; look_at(rh, cam.location)
# the bulb itself, so the bare pass shows what the lens sees
bulb_mat = bpy.data.materials.new("bulb"); bulb_mat.use_nodes = True
nt = bulb_mat.node_tree; nt.nodes.remove(nt.nodes["Principled BSDF"])
em = nt.nodes.new("ShaderNodeEmission"); em.inputs["Strength"].default_value = 3000
bb2 = nt.nodes.new("ShaderNodeBlackbody"); bb2.inputs[0].default_value = 3200
nt.links.new(bb2.outputs[0], em.inputs["Color"]); nt.links.new(em.outputs[0], nt.nodes["Material Output"].inputs["Surface"])
bpy.ops.mesh.primitive_uv_sphere_add(radius=0.012, location=RH + Vector((0, -0.02, 0)))
bulb = bpy.context.active_object; bulb.data.materials.append(bulb_mat)
bulb.visible_shadow = False
housing_mat, _ = principled("redhead_body", **{"Base Color": (0.5, 0.05, 0.03, 1), "Roughness": 0.5})
bpy.ops.mesh.primitive_cylinder_add(radius=0.07, depth=0.16, location=RH + Vector((0, 0.09, 0)))
h = bpy.context.active_object; h.rotation_euler = (math.pi / 2, 0, 0); h.data.materials.append(housing_mat)

if a.pas in ("trace", "full", "overview"):
    # trace frame: diffusion fabric close behind the glass. Mostly transmits, diffusely.
    tr_mat = bpy.data.materials.new("trace"); tr_mat.use_nodes = True
    nt = tr_mat.node_tree; nt.nodes.remove(nt.nodes["Principled BSDF"])
    tl = nt.nodes.new("ShaderNodeBsdfTranslucent"); tl.inputs["Color"].default_value = (0.8, 0.8, 0.8, 1)
    df = nt.nodes.new("ShaderNodeBsdfDiffuse"); df.inputs["Color"].default_value = (0.8, 0.8, 0.8, 1)
    mx = nt.nodes.new("ShaderNodeMixShader"); mx.inputs[0].default_value = 0.3
    nt.links.new(tl.outputs[0], mx.inputs[1]); nt.links.new(df.outputs[0], mx.inputs[2])
    nt.links.new(mx.outputs[0], nt.nodes["Material Output"].inputs["Surface"])
    bpy.ops.mesh.primitive_plane_add(size=1, location=(0, 0.30, 0.35))
    tf = bpy.context.active_object; tf.name = "trace_frame"; tf.scale = (1.0, 0.8, 1)
    tf.rotation_euler = (math.pi / 2, 0, 0); tf.data.materials.append(tr_mat)

if a.pas in ("full", "overview"):
    flag_mat, _ = principled("duvetyne", **{"Base Color": (0.02, 0.02, 0.02, 1), "Roughness": 1.0})
    for side in (-1, 1):
        w = 0.5
        bpy.ops.mesh.primitive_plane_add(size=1, location=(side * (a.slot + w / 2), 0.22, 0.35))
        f = bpy.context.active_object; f.name = f"black_flag_{side}"; f.scale = (w, 0.8, 1)
        f.rotation_euler = (math.pi / 2, 0, 0); f.data.materials.append(flag_mat)

if a.pas == "overview":
    wl = bpy.data.lights.new("worklight", "AREA"); wl.energy = 30; wl.size = 3
    w = bpy.data.objects.new("worklight", wl); scn.collection.objects.link(w)
    w.location = (1.2, -1.5, 2.5); look_at(w, (0, 0.3, 0.2))

# ---------------------------------------------------------------- render
scn.render.engine = "CYCLES"; scn.cycles.device = "CPU"
scn.cycles.samples = a.samples; scn.cycles.use_denoising = True
scn.cycles.max_bounces = 32; scn.cycles.transmission_bounces = 32
scn.cycles.transparent_max_bounces = 32
scn.cycles.caustics_refractive = True; scn.cycles.caustics_reflective = True
scn.cycles.blur_glossy = 0.0
scn.render.resolution_y = a.res
scn.render.resolution_x = int(a.res * (16 / 9 if a.pas == "overview" else 2 / 3))
scn.view_settings.view_transform = "AgX"; scn.view_settings.look = "AgX - Base Contrast"
scn.view_settings.exposure = a.exposure
scn.view_settings.use_white_balance = a.pas != "overview"
scn.view_settings.white_balance_temperature = 3200
scn.world = bpy.data.worlds.new("black"); scn.world.color = (0, 0, 0)
scn.render.filepath = a.out

if a.bake:
    import os
    # collider: the bowl's inner surface, thickened 12 mm outward so the sim can't leak through
    IB = INNER[::-1]
    T = 0.012
    # the sim keeps liquid about a cell away from obstacles, so the collider's inner face sits
    # D outside the real glass: the rendered wine then meets the glass instead of leaving an air gap
    D = 0.0015
    IBd = [(r + D if r > 0 else 0.0, z - D if r == 0 else z) for r, z in IB]
    cprof = ([(0.0, IB[0][1] - T)] + [(r + T, z) for r, z in IB[1:]] + [(IB[-1][0] + T, 0.214),
             (IBd[-1][0], 0.214)] + IBd[::-1])
    col = lathe("collider", cprof, steps=64)
    col.hide_render = True
    m = col.modifiers.new("fluid", "FLUID"); m.fluid_type = "EFFECTOR"
    m.effector_settings.effector_type = "COLLISION"
    # domain: around the bowl and the falling stream
    bpy.ops.mesh.primitive_cube_add(size=1, location=(0, 0, 0.215))
    dom = bpy.context.active_object; dom.name = "wine_domain"; dom.scale = (0.13, 0.13, 0.25)
    bpy.ops.object.transform_apply(scale=True)
    dom.data.materials.append(wine_mat)
    m = dom.modifiers.new("fluid", "FLUID"); m.fluid_type = "DOMAIN"
    ds = m.domain_settings
    ds.domain_type = "LIQUID"; ds.resolution_max = a.fres
    ds.use_mesh = True; ds.mesh_scale = 2; ds.mesh_smoothen_pos = 2
    ds.time_scale = a.timescale
    ds.cache_directory = a.bake; ds.cache_type = "ALL"
    ds.cache_frame_start = 1; ds.cache_frame_end = a.frames
    # inflow: an 8 mm stream entering just above frame, off-centre and angled so it swirls
    bpy.ops.mesh.primitive_cylinder_add(radius=0.004, depth=0.008, location=(0.014, 0, 0.325))
    inflow = bpy.context.active_object; inflow.name = "pour"; inflow.hide_render = True
    m = inflow.modifiers.new("fluid", "FLUID"); m.fluid_type = "FLOW"
    fs = m.flow_settings
    fs.flow_type = "LIQUID"; fs.flow_behavior = "INFLOW"; fs.flow_source = "MESH"
    fs.use_initial_velocity = True; fs.velocity_coord = (-0.15, 0.35, -0.9)
    fs.use_inflow = True; fs.keyframe_insert("use_inflow", frame=1)
    fs.use_inflow = False; fs.keyframe_insert("use_inflow", frame=int(a.frames * 0.45))
    scn.frame_start, scn.frame_end = 1, a.frames
    bpy.context.view_layer.objects.active = dom; dom.select_set(True)
    print("BAKING", a.frames, "frames at res", a.fres, flush=True)
    bpy.ops.fluid.bake_all()
    bpy.ops.wm.save_as_mainfile(filepath=os.path.join(os.path.dirname(a.bake.rstrip("/")), "pour.blend"))
    print("BAKED", a.bake, flush=True)
    sys.exit(0)
if a.save_blend:
    bpy.ops.wm.save_as_mainfile(filepath=a.save_blend)
bpy.ops.render.render(write_still=True)
print("WROTE", a.out)
