"""Stage 7: materials, environment, lights and cameras for the Mossback mech.
Run:  blender -b <06_walk.blend> -P scene.py -- <meta.json> <out.blend>
Everything is procedural. The ground, rocks, footprints and camera repeat
exactly every LOOP_DIST metres / NF frames, so the clip loops without a seam.
"""
import bpy, bmesh, json, sys, math, random
from math import sin, cos, pi, radians, exp, floor
from mathutils import Vector, Matrix, noise

ARGS = sys.argv[sys.argv.index('--') + 1:]
META = json.load(open(ARGS[0]))
OUTB = ARGS[1]
SC = bpy.context.scene
FPS, NF, TC, V, P = META['fps'], META['nf'], META['tc'], META['v'], META['loop_dist']
random.seed(7)


# ------------------------------------------------------------------ node DSL
class NB:
    def __init__(self, m):
        m.use_nodes = True
        self.nt = m.node_tree
        self.nt.nodes.clear()
        self.out = self.nt.nodes.new('ShaderNodeOutputMaterial')

    def n(self, t, **kw):
        nd = self.nt.nodes.new(t)
        for k, v in kw.items():
            setattr(nd, k, v)
        return nd

    def set(self, sock, v):
        if hasattr(v, 'is_output'):
            self.nt.links.new(v, sock)
        else:
            sock.default_value = v

    def math(self, op, a, b=None, clamp=False):
        nd = self.n('ShaderNodeMath', operation=op, use_clamp=clamp)
        self.set(nd.inputs[0], a)
        if b is not None:
            self.set(nd.inputs[1], b)
        return nd.outputs[0]

    def mixf(self, fac, a, b):
        nd = self.n('ShaderNodeMix', data_type='FLOAT', clamp_factor=True)
        ins = [s for s in nd.inputs if s.type == 'VALUE']
        self.set(ins[0], fac)
        self.set(ins[1], a)
        self.set(ins[2], b)
        return [s for s in nd.outputs if s.type == 'VALUE'][0]

    def mixc(self, fac, a, b, blend='MIX'):
        nd = self.n('ShaderNodeMix', data_type='RGBA', clamp_factor=True, blend_type=blend)
        self.set([s for s in nd.inputs if s.type == 'VALUE'][0], fac)
        cs = [s for s in nd.inputs if s.type == 'RGBA']
        self.set(cs[0], a)
        self.set(cs[1], b)
        return [s for s in nd.outputs if s.type == 'RGBA'][0]

    def maprange(self, x, a, b, c=0.0, d=1.0, smooth=True):
        nd = self.n('ShaderNodeMapRange', interpolation_type='SMOOTHSTEP' if smooth else 'LINEAR')
        self.set(nd.inputs['Value'], x)
        nd.inputs['From Min'].default_value = a
        nd.inputs['From Max'].default_value = b
        nd.inputs['To Min'].default_value = c
        nd.inputs['To Max'].default_value = d
        return nd.outputs['Result']

    def noise(self, vec, scale, detail=5.0, rough=0.55, dist=0.0):
        nd = self.n('ShaderNodeTexNoise')
        if vec is not None:
            self.set(nd.inputs['Vector'], vec)
        nd.inputs['Scale'].default_value = scale
        nd.inputs['Detail'].default_value = detail
        nd.inputs['Roughness'].default_value = rough
        nd.inputs['Distortion'].default_value = dist
        return nd.outputs['Fac']

    def sep(self, v):
        nd = self.n('ShaderNodeSeparateXYZ')
        self.set(nd.inputs[0], v)
        return nd.outputs

    def comb(self, x, y, z):
        nd = self.n('ShaderNodeCombineXYZ')
        self.set(nd.inputs[0], x)
        self.set(nd.inputs[1], y)
        self.set(nd.inputs[2], z)
        return nd.outputs[0]

    def rgb(self, c):
        nd = self.n('ShaderNodeRGB')
        nd.outputs[0].default_value = (c[0], c[1], c[2], 1.0)
        return nd.outputs[0]

    def bsdf(self, **kw):
        nd = self.n('ShaderNodeBsdfPrincipled')
        for k, v in kw.items():
            self.set(nd.inputs[k], v)
        return nd


def paint_mat(m, color, rough=0.45, lines=1.0, chip=1.0, metal_col=(0.42, 0.42, 0.42), stripes=None, coat=0.0):
    b = NB(m)
    tc = b.n('ShaderNodeTexCoord')
    obj = tc.outputs['Object']
    nrm = tc.outputs['Normal']
    o = b.sep(obj)
    nn = b.sep(nrm)
    # triplanar panel seams (object space, so they stay put on moving parts)
    wts = []
    briks = []
    for (u, v, w) in ((1, 2, 0), (0, 2, 1), (0, 1, 2)):
        vec = b.comb(o[u], o[v], 0.0)
        br = b.n('ShaderNodeTexBrick', offset=0.5)
        b.set(br.inputs['Vector'], vec)
        br.inputs['Scale'].default_value = 1.0
        br.inputs['Mortar Size'].default_value = 0.0022
        br.inputs['Mortar Smooth'].default_value = 0.2
        br.inputs['Brick Width'].default_value = 1.35
        br.inputs['Row Height'].default_value = 0.58
        briks.append(br.outputs['Fac'])
        wts.append(b.math('POWER', b.math('ABSOLUTE', nn[w]), 6.0))
    num = b.math('ADD', b.math('ADD', b.math('MULTIPLY', briks[0], wts[0]), b.math('MULTIPLY', briks[1], wts[1])), b.math('MULTIPLY', briks[2], wts[2]))
    den = b.math('ADD', b.math('ADD', wts[0], wts[1]), b.math('ADD', wts[2], 1e-4))
    seam = b.math('MULTIPLY', b.math('DIVIDE', num, den), lines * 0.75)
    # cavity grime and convex edge wear from ambient occlusion
    ao = b.n('ShaderNodeAmbientOcclusion', samples=4, only_local=True)
    ao.inputs['Distance'].default_value = 0.12
    cav = b.math('SUBTRACT', 1.0, ao.outputs['AO'])
    aoi = b.n('ShaderNodeAmbientOcclusion', samples=4, inside=True, only_local=True)
    aoi.inputs['Distance'].default_value = 0.03
    edge = b.maprange(b.math('SUBTRACT', 1.0, aoi.outputs['AO']), 0.12, 0.55)
    chipn = b.noise(obj, 9.0, 8.0, 0.65, 0.4)
    chipm = b.maprange(b.math('MULTIPLY', b.math('ADD', edge, b.math('MULTIPLY', chipn, 0.35)), chip), 0.52, 0.62)
    # dust: per-part amount, settles low on the part and on upward faces
    at = b.n('ShaderNodeAttribute', attribute_type='OBJECT', attribute_name='dust')
    z0 = b.n('ShaderNodeAttribute', attribute_type='OBJECT', attribute_name='dz0')
    z1 = b.n('ShaderNodeAttribute', attribute_type='OBJECT', attribute_name='dz1')
    grad = b.math('DIVIDE', b.math('SUBTRACT', z1.outputs['Fac'], o[2]), b.math('MAXIMUM', b.math('SUBTRACT', z1.outputs['Fac'], z0.outputs['Fac']), 0.01))
    geo = b.n('ShaderNodeNewGeometry')
    up = b.maprange(b.sep(geo.outputs['Normal'])[2], 0.4, 0.95)
    dn = b.noise(obj, 3.0, 6.0, 0.6, 0.3)
    dmask = b.math('MULTIPLY', at.outputs['Fac'], b.math('ADD', b.math('MULTIPLY', grad, 0.9), b.math('MULTIPLY', up, 0.6)))
    dust = b.maprange(b.math('ADD', b.math('MULTIPLY', dmask, 1.1), b.math('MULTIPLY', dn, 0.5)), 0.55, 1.05)
    # colour
    base = b.rgb(color) if stripes is None else stripes(b, obj)
    var = b.noise(obj, 1.3, 3.0, 0.5)
    base = b.mixc(b.math('MULTIPLY', b.math('SUBTRACT', var, 0.5), 0.5), base, (1, 1, 1, 1), 'OVERLAY')
    streak = b.noise(b.comb(b.math('MULTIPLY', o[0], 2.5), b.math('MULTIPLY', o[1], 2.5), b.math('MULTIPLY', o[2], 0.6)), 1.0, 2.0, 0.4)
    base = b.mixc(b.math('MULTIPLY', b.maprange(streak, 0.6, 0.8), 0.12), base, (0.05, 0.04, 0.03, 1), 'MULTIPLY')
    base = b.mixc(b.math('MULTIPLY', cav, 0.85), base, (0.02, 0.018, 0.015, 1))
    base = b.mixc(b.math('MULTIPLY', seam, 0.8), base, (0.01, 0.01, 0.01, 1))
    base = b.mixc(dust, base, (0.40, 0.29, 0.18, 1))
    base = b.mixc(chipm, base, (*metal_col, 1))
    r = b.math('ADD', rough, b.math('MULTIPLY', b.math('SUBTRACT', b.noise(obj, 6.0, 4.0, 0.5), 0.5), 0.25))
    r = b.mixf(dust, r, 0.92)
    r = b.mixf(chipm, r, 0.32)
    r = b.mixf(seam, r, 0.8)
    bump = b.n('ShaderNodeBump')
    bump.inputs['Strength'].default_value = 0.35
    bump.inputs['Distance'].default_value = 0.004
    h = b.math('SUBTRACT', b.math('MULTIPLY', b.noise(obj, 40.0, 4.0, 0.5), 0.15), b.math('ADD', seam, b.math('MULTIPLY', chipm, 0.3)))
    b.set(bump.inputs['Height'], h)
    pb = b.bsdf(**{'Base Color': base, 'Roughness': r, 'Metallic': chipm, 'Normal': bump.outputs['Normal'], 'Coat Weight': coat})
    b.set(b.out.inputs['Surface'], pb.outputs[0])


def metal_mat(m, color, rough, aniso=0.0, grime=0.6):
    b = NB(m)
    tc = b.n('ShaderNodeTexCoord')
    obj = tc.outputs['Object']
    ao = b.n('ShaderNodeAmbientOcclusion', samples=4, only_local=True)
    ao.inputs['Distance'].default_value = 0.08
    cav = b.math('SUBTRACT', 1.0, ao.outputs['AO'])
    base = b.mixc(b.math('MULTIPLY', cav, grime), b.rgb(color), (0.03, 0.025, 0.02, 1))
    base = b.mixc(b.math('MULTIPLY', b.maprange(b.noise(obj, 4.0, 6.0, 0.6), 0.5, 0.8), 0.5), base, (0.08, 0.07, 0.06, 1))
    r = b.math('ADD', rough, b.math('MULTIPLY', b.math('SUBTRACT', b.noise(obj, 25.0, 5.0, 0.6), 0.5), 0.2))
    r = b.mixf(cav, r, 0.7)
    pb = b.bsdf(**{'Base Color': base, 'Roughness': r, 'Metallic': 1.0, 'Anisotropic': aniso})
    b.set(b.out.inputs['Surface'], pb.outputs[0])


def simple(m, **kw):
    b = NB(m)
    pb = b.bsdf(**kw)
    b.set(b.out.inputs['Surface'], pb.outputs[0])
    return b, pb


def hazard_stripes(b, obj):
    o = b.sep(obj)
    w = b.n('ShaderNodeTexWave', wave_type='BANDS', bands_direction='DIAGONAL', wave_profile='SAW')
    b.set(w.inputs['Vector'], b.comb(b.math('ADD', o[0], o[1]), o[2], 0.0))
    w.inputs['Scale'].default_value = 3.2
    w.inputs['Distortion'].default_value = 0.0
    st = b.math('GREATER_THAN', w.outputs['Fac'], 0.5)
    return b.mixc(st, (0.80, 0.42, 0.006, 1), (0.012, 0.011, 0.01, 1))


M = {m.name: m for m in bpy.data.materials}
TEAL = (0.040, 0.118, 0.100)
CREAM = (0.62, 0.53, 0.36)
GUN = (0.030, 0.031, 0.034)
paint_mat(M['paint'], TEAL, 0.42, coat=0.15)
paint_mat(M['paint2'], CREAM, 0.48, coat=0.1)
paint_mat(M['frame'], GUN, 0.5, lines=0.5, metal_col=(0.35, 0.35, 0.36))
paint_mat(M['barrel'], (0.022, 0.022, 0.024), 0.38, lines=0.0, chip=0.7)
paint_mat(M['hazard'], None, 0.5, lines=0.3, stripes=hazard_stripes)
paint_mat(M['hazard_bar'], (0.80, 0.42, 0.006), 0.45, lines=0.0)
simple(M['stencil'], **{'Base Color': (0.80, 0.78, 0.70, 1), 'Roughness': 0.7})
metal_mat(M['steel'], (0.52, 0.52, 0.53), 0.32)
metal_mat(M['chrome'], (0.92, 0.92, 0.93), 0.05, grime=0.2)
metal_mat(M['brass'], (0.78, 0.52, 0.24), 0.3)
metal_mat(M['exhaust'], (0.12, 0.08, 0.06), 0.6, grime=0.9)
metal_mat(M['cable'], (0.20, 0.20, 0.21), 0.45)
simple(M['rubber'], **{'Base Color': (0.018, 0.018, 0.018, 1), 'Roughness': 0.75})
simple(M['seat'], **{'Base Color': (0.045, 0.035, 0.028, 1), 'Roughness': 0.55})
simple(M['pilot_suit'], **{'Base Color': (0.42, 0.075, 0.025, 1), 'Roughness': 0.85, 'Sheen Weight': 0.4})
simple(M['pilot_helmet'], **{'Base Color': (0.78, 0.76, 0.70, 1), 'Roughness': 0.3, 'Coat Weight': 0.6})
simple(M['visor'], **{'Base Color': (0.55, 0.40, 0.16, 1), 'Roughness': 0.08, 'Metallic': 1.0})
simple(M['glass'], **{'Base Color': (0.90, 0.95, 0.94, 1), 'Roughness': 0.02, 'Transmission Weight': 1.0, 'IOR': 1.5, 'Thin Wall': True, 'Specular IOR Level': 0.35})
simple(M['lamp'], **{'Base Color': (1, 0.9, 0.7, 1), 'Emission Color': (1.0, 0.82, 0.55, 1), 'Emission Strength': 14.0, 'Roughness': 0.2})
simple(M['screen'], **{'Base Color': (0.02, 0.05, 0.05, 1), 'Emission Color': (0.25, 0.85, 0.75, 1), 'Emission Strength': 3.0, 'Roughness': 0.15})
bb, beacon = simple(M['beacon'], **{'Base Color': (1, 0.45, 0.05, 1), 'Emission Color': (1.0, 0.42, 0.04, 1), 'Emission Strength': 2.0, 'Roughness': 0.15, 'Transmission Weight': 0.5})
# beacon pulses 8 times per loop (period 1.25 s) so the loop stays seamless
es = beacon.inputs['Emission Strength']
for f in range(0, NF + 1, 3):
    ph = (f / FPS) % 1.25 / 1.25
    es.default_value = 1.0 + 38.0 * exp(-((ph - 0.08) / 0.07) ** 2)
    es.keyframe_insert('default_value', frame=f)

# per-part dust amounts (object attributes read by the paint shader)
DUST = {'foot': (0.62, -0.30, 0.0), 'spider': (0.45, -0.3, 0.1), 'shin': (0.55, -1.25, -0.2), 'thigh': (0.35, -1.25, -0.4),
        'hull': (0.18, 0.4, 1.4), 'cab': (0.10, 1.1, 1.6), 'upperarm': (0.15, -0.2, 0.2), 'forearm': (0.2, -0.2, 0.2), 'hook': (0.4, -1.1, -0.8)}
for ob in bpy.data.objects:
    if ob.type not in ('MESH', 'CURVE'):
        continue
    b = ob.get('body', '')
    key = b.split('_')[0]
    d = DUST.get(key, (0.3, -1.0, 0.0))
    if 'cyl' in b:
        d = (0.45 if ('ankle' in b) else 0.2, -1.2, 0.2)
    ob['dust'], ob['dz0'], ob['dz1'] = d

# ------------------------------------------------------------------ environment
ENV = bpy.data.collections.new('env')
SC.collection.children.link(ENV)
HAZE = (0.66, 0.50, 0.36)


def haze_wrap(b, shader_out, dist=260.0):
    cam = b.n('ShaderNodeCameraData')
    fac = b.math('SUBTRACT', 1.0, b.math('EXPONENT', b.math('DIVIDE', b.math('MULTIPLY', cam.outputs['View Distance'], -1.0), dist)))
    em = b.n('ShaderNodeEmission')
    em.inputs['Color'].default_value = (*HAZE, 1)
    em.inputs['Strength'].default_value = 1.0
    ms = b.n('ShaderNodeMixShader')
    b.set(ms.inputs[0], fac)
    b.set(ms.inputs[1], shader_out)
    b.set(ms.inputs[2], em.outputs[0])
    b.set(b.out.inputs['Surface'], ms.outputs[0])


def periodic_xy(b):
    """World (x, y) mapped onto a ring so every texture repeats exactly every P metres in x."""
    geo = b.n('ShaderNodeNewGeometry')
    w = b.sep(geo.outputs['Position'])
    th = b.math('MULTIPLY', w[0], 2 * pi / P)
    R = P / (2 * pi)
    return b.comb(b.math('MULTIPLY', b.math('COSINE', th), R), b.math('MULTIPLY', b.math('SINE', th), R), w[1]), w


gm = bpy.data.materials.new('ground')
b = NB(gm)
vec, w = periodic_xy(b)
vor = b.n('ShaderNodeTexVoronoi', feature='DISTANCE_TO_EDGE')
warp = b.n('ShaderNodeVectorMath', operation='ADD')
b.set(warp.inputs[0], vec)
nw = b.n('ShaderNodeTexNoise')
b.set(nw.inputs['Vector'], vec)
nw.inputs['Scale'].default_value = 1.5
b.set(warp.inputs[1], b.n('ShaderNodeVectorMath', operation='SCALE').outputs[0])
sc_ = warp.inputs[1].links[0].from_node
b.set(sc_.inputs[0], nw.outputs['Color'])
sc_.inputs['Scale'].default_value = 0.12
b.set(vor.inputs['Vector'], warp.outputs[0])
vor.inputs['Scale'].default_value = 2.1
crack = b.maprange(vor.outputs['Distance'], 0.0, 0.035, 1.0, 0.0)
vor2 = b.n('ShaderNodeTexVoronoi', feature='DISTANCE_TO_EDGE')
b.set(vor2.inputs['Vector'], vec)
vor2.inputs['Scale'].default_value = 0.6
crack2 = b.maprange(vor2.outputs['Distance'], 0.0, 0.02, 1.0, 0.0)
cracks = b.math('MAXIMUM', crack, crack2)
big = b.noise(vec, 0.08, 4.0, 0.55)
mid = b.noise(vec, 0.7, 6.0, 0.6)
fine = b.noise(vec, 9.0, 4.0, 0.6)
col = b.mixc(b.maprange(big, 0.35, 0.7), (0.15, 0.10, 0.06, 1), (0.25, 0.175, 0.11, 1))
col = b.mixc(b.math('MULTIPLY', b.math('SUBTRACT', mid, 0.5), 0.6), col, (1, 1, 1, 1), 'OVERLAY')
col = b.mixc(b.math('MULTIPLY', cracks, 0.85), col, (0.07, 0.05, 0.035, 1))
rough = b.mixf(cracks, b.math('ADD', 0.86, b.math('MULTIPLY', fine, 0.1)), 0.95)
bump = b.n('ShaderNodeBump')
bump.inputs['Strength'].default_value = 0.6
bump.inputs['Distance'].default_value = 0.02
b.set(bump.inputs['Height'], b.math('SUBTRACT', b.math('ADD', b.math('MULTIPLY', mid, 0.4), b.math('MULTIPLY', fine, 0.15)), b.math('MULTIPLY', cracks, 0.8)))
pb = b.bsdf(**{'Base Color': col, 'Roughness': rough, 'Normal': bump.outputs['Normal']})
haze_wrap(b, pb.outputs[0], 220.0)

bm = bmesh.new()
bmesh.ops.create_grid(bm, x_segments=1, y_segments=1, size=1.0)
me = bpy.data.meshes.new('ground')
bm.to_mesh(me)
ground = bpy.data.objects.new('ground', me)
ground.scale = (900, 900, 1)
ground.location = (0, -300, 0)
me.materials.append(gm)
ENV.objects.link(ground)

# rocks, placed once in [0, P) and repeated every P metres
rm = bpy.data.materials.new('rock')
b = NB(rm)
tc = b.n('ShaderNodeTexCoord')
rn = b.noise(tc.outputs['Object'], 3.0, 8.0, 0.6)
rc = b.mixc(b.maprange(rn, 0.35, 0.7), (0.07, 0.05, 0.04, 1), (0.22, 0.16, 0.11, 1))
geo = b.n('ShaderNodeNewGeometry')
rc = b.mixc(b.math('MULTIPLY', b.maprange(b.sep(geo.outputs['Normal'])[2], 0.6, 0.95), 0.6), rc, (0.42, 0.31, 0.20, 1))
rbump = b.n('ShaderNodeBump')
rbump.inputs['Strength'].default_value = 0.5
b.set(rbump.inputs['Height'], b.noise(tc.outputs['Object'], 12.0, 6.0, 0.6))
pb = b.bsdf(**{'Base Color': rc, 'Roughness': 0.8, 'Normal': rbump.outputs['Normal']})
haze_wrap(b, pb.outputs[0], 220.0)


def rock_mesh(seed, r):
    bm = bmesh.new()
    bmesh.ops.create_icosphere(bm, subdivisions=3, radius=1.0)
    off = Vector((seed * 3.1, seed * 1.7, seed * 0.9))
    for v in bm.verts:
        n = v.co.normalized()
        d = 1.0 + 0.45 * noise.noise(n * 1.1 + off) + 0.18 * noise.noise(n * 3.5 + off) + 0.06 * noise.noise(n * 9.0 + off)
        v.co = n * d
    for v in bm.verts:
        v.co.z *= 0.42
        v.co *= r
        if v.co.z < -0.15 * r:
            v.co.z = -0.15 * r
    me = bpy.data.meshes.new('rock%d' % seed)
    bm.to_mesh(me)
    me.materials.append(rm)
    return me


rocks = []
for i in range(40):
    x = random.uniform(0, P)
    while True:
        y = random.uniform(-40, 30)
        if abs(y) > 3.2:
            break
    r = random.choice([0.05, 0.07, 0.1, 0.12, 0.16, 0.22, 0.35]) * (1.0 if abs(y) < 12 else 2.2)
    rocks.append((x, y, r, random.uniform(0, 2 * pi), rock_mesh(i, r)))
for k in range(-6, 8):
    for (x, y, r, rot, me) in rocks:
        ob = bpy.data.objects.new('rock', me)
        ob.location = (x + k * P, y, 0)
        ob.rotation_euler = (0, 0, rot)
        ENV.objects.link(ob)

# distant ridges ride along with the camera in x (no parallax jump at the loop seam)
ridge_rig = bpy.data.objects.new('ridge_rig', None)
ENV.objects.link(ridge_rig)
rgm = bpy.data.materials.new('ridge')
b = NB(rgm)
tc = b.n('ShaderNodeTexCoord')
pb = b.bsdf(**{'Base Color': b.mixc(b.noise(tc.outputs['Object'], 0.02, 6.0, 0.6), (0.20, 0.13, 0.09, 1), (0.36, 0.26, 0.18, 1)), 'Roughness': 0.95})
haze_wrap(b, pb.outputs[0], 900.0)
for j, (yy, hh, seed) in enumerate(((-420, 70, 1), (-700, 140, 2), (-1100, 230, 3))):
    bm = bmesh.new()
    nx = 600
    xs = [-2200 + 4400 * i / nx for i in range(nx + 1)]
    top = []
    bot = []
    for x in xs:
        hgt = hh * (0.55 + 0.45 * noise.noise(Vector((x / 380.0, seed * 7.0, 0))) + 0.18 * noise.noise(Vector((x / 90.0, seed * 3.0, 1))) + 0.06 * noise.noise(Vector((x / 21.0, seed, 2))))
        top.append(bm.verts.new((x, yy, max(hgt, 5.0))))
        bot.append(bm.verts.new((x, yy, -5.0)))
    for i in range(nx):
        bm.faces.new((bot[i], bot[i + 1], top[i + 1], top[i]))
    me = bpy.data.meshes.new('ridge%d' % j)
    bm.to_mesh(me)
    me.materials.append(rgm)
    ob = bpy.data.objects.new('ridge%d' % j, me)
    ob.parent = ridge_rig
    ENV.objects.link(ob)

# footprints: appear when each foot plants; the trail repeats every loop
fpm = bpy.data.materials.new('print')
b = NB(fpm)
vec, w = periodic_xy(b)
pn = b.noise(vec, 6.0, 4.0, 0.6)
pb = b.bsdf(**{'Base Color': b.mixc(pn, (0.10, 0.07, 0.045, 1), (0.15, 0.105, 0.07, 1)), 'Roughness': 0.97})
haze_wrap(b, pb.outputs[0], 220.0)


def print_mesh():
    bm = bmesh.new()
    rects = [(-0.46, 0.54, -0.31, 0.31), (-0.62, -0.46, -0.15, 0.15)] + [(0.54, 0.86, y - 0.085, y + 0.085) for y in (-0.22, 0.0, 0.22)]
    for (x0, x1, y0, y1) in rects:
        vs = [bm.verts.new((x0, y0, 0)), bm.verts.new((x1, y0, 0)), bm.verts.new((x1, y1, 0)), bm.verts.new((x0, y1, 0))]
        bm.faces.new(vs)
    me = bpy.data.meshes.new('footprint')
    bm.to_mesh(me)
    me.materials.append(fpm)
    return me


PM = print_mesh()
STEP, DUTY = META['step'], 0.62
a = DUTY * STEP
nprint = 0
for s, sg, off in (('L', 1, 0.0), ('R', -1, 0.5)):
    for k in range(-14, 6):
        tk = (k - off) * TC
        if tk >= NF / FPS:
            continue
        Xk = V * tk + a
        ob = bpy.data.objects.new('print_%s_%d' % (s, k), PM)
        ob.location = (Xk, 0.90 * sg, 0.0015)
        ob.rotation_euler = (0, 0, radians(4) * sg)
        ENV.objects.link(ob)
        fk = tk * FPS
        if fk > 0:
            ob.hide_render = True
            ob.keyframe_insert('hide_render', frame=0)
            ob.hide_render = False
            ob.keyframe_insert('hide_render', frame=int(math.ceil(fk)))
        nprint += 1

# ------------------------------------------------------------------ world and sun
SUN_EL, SUN_AZ = radians(14), radians(32)
sun_dir = Vector((cos(SUN_EL) * cos(SUN_AZ), cos(SUN_EL) * sin(SUN_AZ), sin(SUN_EL)))
wd = bpy.data.worlds.new('sky')
SC.world = wd
wd.use_nodes = True
nt = wd.node_tree
nt.nodes.clear()
sky = nt.nodes.new('ShaderNodeTexSky')
sky.sky_type = 'MULTIPLE_SCATTERING'
sky.sun_disc = False
sky.sun_elevation = SUN_EL
sky.sun_rotation = math.atan2(sun_dir.x, sun_dir.y)
sky.altitude = 200
sky.air_density = 1.0
sky.aerosol_density = 3.0
bg = nt.nodes.new('ShaderNodeBackground')
bg.inputs['Strength'].default_value = 0.10
mixs = nt.nodes.new('ShaderNodeMix')
mixs.data_type = 'RGBA'
cs = [x for x in mixs.inputs if x.type == 'RGBA']
[x for x in mixs.inputs if x.type == 'VALUE'][0].default_value = 0.55
nt.links.new(sky.outputs['Color'], cs[0])
cs[1].default_value = (HAZE[0] * 5.0, HAZE[1] * 5.0, HAZE[2] * 5.0, 1)
nt.links.new([x for x in mixs.outputs if x.type == 'RGBA'][0], bg.inputs['Color'])
wo = nt.nodes.new('ShaderNodeOutputWorld')
nt.links.new(bg.outputs[0], wo.inputs['Surface'])

sl = bpy.data.lights.new('sun', 'SUN')
sl.energy = 10.0
sl.angle = radians(1.2)
sl.color = (1.0, 0.78, 0.55)
sun = bpy.data.objects.new('sun', sl)
sun.rotation_euler = (-sun_dir).to_track_quat('-Z', 'Y').to_euler()
ENV.objects.link(sun)
# soft cool fill from the sky side opposite the sun (keeps the shadow side readable)
fl = bpy.data.lights.new('fill', 'SUN')
fl.energy = 0.25
fl.angle = radians(25)
fl.color = (0.65, 0.75, 1.0)
fill = bpy.data.objects.new('fill', fl)
fd = Vector((-0.5, -0.6, 0.6)).normalized()
fill.rotation_euler = (-fd).to_track_quat('-Z', 'Y').to_euler()
ENV.objects.link(fill)
for o in (sun, fill):
    pass

# warm cab light so the pilot reads through the glass
cl = bpy.data.lights.new('cab_light', 'POINT')
cl.energy = 260.0
cl.color = (1.0, 0.8, 0.55)
cl.shadow_soft_size = 0.08
cab_light = bpy.data.objects.new('cab_light', cl)
cab_light.parent = bpy.data.objects['B_cab']
cab_light.location = (0.75, 0.0, 2.50)
ENV.objects.link(cab_light)

# dust puffs: one low volumetric cloud per foot strike, expanding and fading over 1.4 s
dm = bpy.data.materials.new('dust_puff')
b = NB(dm)
tc = b.n('ShaderNodeTexCoord')
ob_ = tc.outputs['Object']
ln = b.n('ShaderNodeVectorMath', operation='LENGTH')
b.set(ln.inputs[0], ob_)
fall = b.maprange(ln.outputs['Value'], 1.0, 0.25)
seed = b.n('ShaderNodeAttribute', attribute_type='OBJECT', attribute_name='seed')
oinf = b.n('ShaderNodeObjectInfo')
amt_r = b.n('ShaderNodeSeparateColor')
b.set(amt_r.inputs[0], oinf.outputs['Color'])
nv = b.n('ShaderNodeVectorMath', operation='ADD')
b.set(nv.inputs[0], ob_)
b.set(nv.inputs[1], seed.outputs['Vector'])
nz = b.noise(nv.outputs[0], 2.2, 5.0, 0.6, 0.6)
dens = b.math('MULTIPLY', b.math('MULTIPLY', fall, b.maprange(nz, 0.38, 0.72)), b.math('MULTIPLY', amt_r.outputs[0], 16.0))
pv = b.n('ShaderNodeVolumePrincipled')
pv.inputs['Color'].default_value = (0.62, 0.50, 0.37, 1)
pv.inputs['Anisotropy'].default_value = 0.35
b.set(pv.inputs['Density'], dens)
b.set(b.out.inputs['Volume'], pv.outputs[0])
sb = bmesh.new()
bmesh.ops.create_uvsphere(sb, u_segments=24, v_segments=12, radius=1.0)
pme = bpy.data.meshes.new('puff')
sb.to_mesh(pme)
pme.materials.append(dm)
# v4: footfalls come from the walk's stance data (meta.json), and each one is scored by how
# hard the stance leg catches the hull: the hull's peak upward acceleration in the 5 frames
# after the foot lands, read from the keyed hull. Dust and camera shake scale with it.
hull_ob = bpy.data.objects['B_hull']
HZ = []
for f in range(-2, NF + 3):
    SC.frame_set(f % NF)
    HZ.append(hull_ob.matrix_world.translation.z)


def hz_at(f):
    return HZ[(f % NF) + 2]


STRIKES = []   # (frame, x, y, impact in m/s^2)
for s_, sg in (('L', 1), ('R', -1)):
    st = META['stance'][s_]
    plants = sorted(META['plants'][s_], key=lambda q: q[3])
    for f in range(NF):
        if st[f] and not st[f - 1]:
            pl = min(plants, key=lambda q: abs(q[3] * FPS - f) if abs(q[3] * FPS - f) < NF / 2 else abs(q[3] * FPS + NF - f))
            imp = max((hz_at(f + j + 1) - 2 * hz_at(f + j) + hz_at(f + j - 1)) * FPS * FPS for j in range(5))
            x = pl[0] if abs(pl[3] * FPS - f) < NF / 2 else pl[0] + P
            for n in (-1, 0, 1):
                STRIKES.append((f + n * NF, x + n * P, 0.90 * sg, imp))
IMPACTS = sorted({round(q[3], 2) for q in STRIKES})
print('STRIKES', len(STRIKES) // 3, 'impact m/s^2', IMPACTS)
npuff = 0
LIFE = 1.6
for i, (fs, x, y, imp) in enumerate(STRIKES):
    tk = fs / FPS
    if tk >= NF / FPS or tk + LIFE < -1 / FPS:
        continue
    k_ = min(2.0, max(0.3, imp / 9.81))
    po = bpy.data.objects.new('puff_%d' % i, pme)
    po['seed'] = (random.uniform(0, 50), random.uniform(0, 50), random.uniform(0, 50))
    ENV.objects.link(po)
    po.location = (x + 0.1, y, 0.0)
    for f in range(-1, NF + 1):
        age = f / FPS - tk
        if age < -1 / FPS or age > LIFE + 1 / FPS:
            vis = False
            amt_ = 0.0
            rad = 0.3
        else:
            u = min(1.0, max(0.0, age) / LIFE)
            vis = True
            # v6: a sharp burst that reaches most of its size in the first fifth of a second
            rad = (0.6 + 2.6 * (1 - (1 - u) ** 4.0)) * (0.75 + 0.25 * k_)
            amt_ = (min(1.0, max(0.0, age) / 0.04)) * (1 - u) ** 2.2 * (0.9 + 0.6 * k_)
        po['puff'] = amt_
        po.color = (amt_, 0.0, 0.0, 1.0)
        po.scale = (rad, rad * 0.85, 0.5 + 0.9 * min(1.0, max(0.0, age) / LIFE))
        po.hide_render = not vis
        po.keyframe_insert('color', frame=f)
        po.keyframe_insert('scale', frame=f)
        po.keyframe_insert('hide_render', frame=f)
    npuff += 1
print('PUFFS', npuff)

# v5: debris. A few clods kicked out from under each foot on a ballistic arc, sized by the
# footfall's impact, landing and lying still, then gone before the loop comes round.
ndeb = 0
for i, (fs, x, y, imp) in enumerate(STRIKES):
    tk = fs / FPS
    if tk >= NF / FPS or tk + 1.6 < -1 / FPS:
        continue
    k_ = min(2.0, max(0.3, imp / 9.81))
    for j in range(9):
        ang = random.uniform(0, 2 * pi)
        sp = random.uniform(1.2, 3.0) * k_
        vz = random.uniform(1.8, 3.4) * k_
        r = random.uniform(0.04, 0.10)
        ox, oy = x + 0.1 + 0.55 * cos(ang), y + 0.38 * sin(ang)
        ob = bpy.data.objects.new('clod_%d_%d' % (i, j), rock_mesh(1000 + i * 10 + j, r))
        ob.data.materials.clear()
        ob.data.materials.append(rm)
        ENV.objects.link(ob)
        land = 2 * vz / 9.81
        for f in range(-1, NF + 1):
            age = f / FPS - tk
            if age < 0 or age > 1.5:
                ob.hide_render = True
                ob.location = (ox, oy, r)
            else:
                tt = min(age, land)
                ob.hide_render = False
                ob.location = (ox + sp * cos(ang) * tt, oy + sp * sin(ang) * tt, r + vz * tt - 4.905 * tt * tt)
                ob.rotation_euler = (age * 9 * (j + 1) if age < land else land * 9 * (j + 1), age * 7 if age < land else land * 7, 0)
            ob.keyframe_insert('location', frame=f)
            ob.keyframe_insert('rotation_euler', frame=f)
            ob.keyframe_insert('hide_render', frame=f)
        ndeb += 1
print('DEBRIS', ndeb)

# ------------------------------------------------------------------ cameras
hull = bpy.data.objects['B_hull']


def strike_shake(t, cam_pos):
    """v4: the sum of a decaying shake for every footfall in the stance data, sized by that
    footfall's impact and falling off with the distance from the foot to the camera."""
    a_ = b_ = 0.0
    for fs, x, y, imp in STRIKES:
        age = t - fs / FPS
        if age < 0 or age > 0.8:
            continue
        d = (Vector((x, y, 0.0)) - cam_pos).length
        amp = min(2.0, imp / 9.81) / (1 + d / 8.5) * 2.0
        e = exp(-age / 0.16)
        a_ += amp * e * sin(2 * pi * 7.5 * age)
        b_ += amp * e * sin(2 * pi * 5.0 * age + 1.0)
    return a_, b_


def make_cam(name, lens, fstop=None, focus=None):
    cd = bpy.data.cameras.new(name)
    cd.lens = lens
    cd.sensor_width = 36
    cd.clip_start = 0.1
    cd.clip_end = 5000
    if fstop:
        cd.dof.use_dof = True
        cd.dof.aperture_fstop = fstop
    ob = bpy.data.objects.new(name, cd)
    ENV.objects.link(ob)
    return ob


cam = make_cam('CamWalk', 32, fstop=5.6)
foc = bpy.data.objects.new('CamWalk_focus', None)
ENV.objects.link(foc)
cam.data.dof.focus_object = foc
CUT = NF // 2   # shot A: slow low tracking shot; shot B: locked-off camera on the ground
bpy.context.preferences.edit.keyframe_new_interpolation_type = 'CONSTANT'
for f in range(-1, NF + 1):
    t = f / FPS
    a_, b_ = strike_shake(t, Vector((7.5 + 0.55 * V * t, 8.0, 0.75)) if f < CUT else Vector((14.5, 6.5, 0.40)))
    if f < CUT:
        # the camera dollies at 55% of the walking speed, low, so the mech closes on it
        lens, fst = 29, 5.6
        pos = Vector((7.5 + 0.55 * V * t, 8.0, 0.75 + 0.010 * a_))
        tgt = Vector((V * t + 0.3, 0.0, 2.75))
        sh_x, sh_z = radians(0.35), radians(0.2)
    else:
        # locked off at ground level; it shakes when the feet land
        lens, fst = 20, 8.0
        pos = Vector((14.5, 6.5, 0.40 + 0.015 * a_))
        tgt = Vector((8.8, 0.0, 2.5))
        sh_x, sh_z = radians(0.7), radians(0.4)
    q = (tgt - pos).to_track_quat('-Z', 'Y')
    eul = q.to_euler()
    eul.x += sh_x * a_
    eul.z += sh_z * b_
    cam.location = pos
    cam.rotation_euler = eul
    cam.data.lens = lens
    cam.data.dof.aperture_fstop = fst
    cam.keyframe_insert('location', frame=f)
    cam.keyframe_insert('rotation_euler', frame=f)
    cam.data.keyframe_insert('lens', frame=f)
    cam.data.dof.keyframe_insert('aperture_fstop', frame=f)
    foc.location = Vector((V * t, 0.6, 2.2))
    foc.keyframe_insert('location', frame=f)
    ridge_rig.location = (pos.x, 0, 0)
    ridge_rig.keyframe_insert('location', frame=f)
bpy.context.preferences.edit.keyframe_new_interpolation_type = 'LINEAR'
SC.render.motion_blur_position = 'START'
SC.camera = cam

# ------------------------------------------------------------------ render settings
r = SC.render
r.engine = 'CYCLES'
r.resolution_x, r.resolution_y, r.resolution_percentage = 1920, 1080, 100
r.use_motion_blur = True
r.motion_blur_shutter = 0.5
r.film_transparent = False
cy = SC.cycles
cy.device = 'GPU'
cy.samples = 64
cy.adaptive_threshold = 0.03
cy.use_denoising = True
cy.denoiser = 'OPTIX'
cy.max_bounces = 8
cy.diffuse_bounces = 3
cy.glossy_bounces = 4
cy.transmission_bounces = 8
cy.transparent_max_bounces = 8
cy.caustics_reflective = False
cy.caustics_refractive = False
cy.volume_bounces = 0
cy.volume_step_rate = 2.0
cy.blur_glossy = 1.0
cy.use_light_tree = True
try:
    SC.view_settings.view_transform = 'AgX'
    SC.view_settings.look = 'AgX - Medium High Contrast'
except Exception as e:
    print('view transform', e)
SC.view_settings.exposure = 0.0
r.image_settings.file_format = 'PNG'
r.image_settings.color_depth = '8'
print('SCENE prints', nprint, 'rocks', len(rocks) * 14)
bpy.ops.wm.save_as_mainfile(filepath=OUTB, compress=True)
print('SAVED', OUTB)
