agent

+36:46
reasoning

Checking the current timestamp to maintain execution discipline. Need to quickly examine kit/lib.py and kit/build.py to understand the relevant codebase sections before commencing.

  • run_command{"CommandLine":"date -u +\"%Y-%m-%dT%H:%M:%SZ\" && git status -s && ~/.local/bin/blender --version | head -n 3","WaitMsBeforeAsync":5000,"toolSummary":"Check UTC time and Blender version"}

    input

    {
      "CommandLine": "date -u +\"%Y-%m-%dT%H:%M:%SZ\" && git status -s && ~/.local/bin/blender --version | head -n 3",
      "WaitMsBeforeAsync": 5000,
      "toolSummary": "Check UTC time and Blender version"
    }

    result, 7 lines

    Command exited with code 0.
    
    Command output:
    2026-11-15T00:20:21Z
    Blender 5.2.3 LTS
    	build date: 2026-10-22
    	build time: 01:35:05
  • read_file{"EndLine":400,"Path":"~/work/sortie/kit/lib.py","StartLine":1}

    input

    {
      "EndLine": 400,
      "Path": "~/work/sortie/kit/lib.py",
      "StartLine": 1
    }

    result, 401 lines

    Showing lines 1-400 of 448
    1: """Modelling helpers shared by every kit script.
    2: 
    3: Blender units are metres, Z is up, and models face -Y (Blender's front view). The glTF exporter turns
    4: that into three.js's Y up with models facing +Z.
    5: 
    6: Parts are solids built from a few primitives:
    7:   loft      cross-sections stacked along an axis (most armour, limbs, hulls)
    8:   prism     a 2D outline pushed through a depth
    9:   two_view  a front outline and a side outline intersected, the classic hard-surface blockout
    10: Every solid gets a material role (main, accent, frame, glow_eye, ...). The game maps roles to toon
    11: materials, so one model can wear any faction's paint.
    12: """
    13: import math
    14: 
    15: import bmesh
    16: import bpy
    17: from mathutils import Matrix, Vector
    18: 
    19: # Preview colours only, for anyone opening a .blend. The game ignores them.
    20: PREVIEW = {
    21:     "main": (0.86, 0.87, 0.9), "accent": (0.12, 0.3, 0.55), "trim": (0.85, 0.55, 0.12),
    22:     "frame": (0.2, 0.21, 0.24), "joint": (0.12, 0.12, 0.14), "visor": (0.05, 0.06, 0.08),
    23:     "glow_eye": (0.3, 1.0, 0.9), "glow_core": (0.3, 1.0, 0.9), "glow_thruster": (0.6, 0.78, 1.0),
    24:     "glow_exhaust": (0.31, 0.56, 1.0),
    25:     "metal": (0.55, 0.57, 0.6), "hull": (0.72, 0.73, 0.75), "hull_dark": (0.32, 0.33, 0.36),
    26:     "deck": (0.25, 0.26, 0.28), "hazard": (0.9, 0.75, 0.1), "light": (1.0, 0.97, 0.9),
    27:     "screen": (0.2, 0.8, 0.75), "glass": (0.1, 0.2, 0.25), "lamp_red": (1.0, 0.2, 0.15),
    28:     "lamp_green": (0.3, 1.0, 0.4), "suit": (0.14, 0.19, 0.36), "glow_hot": (0.92, 1.0, 0.98),
    29:     # raider salvage (palette.ts): donor paint, primer, rust, hand paint
    30:     "donor_a": (0.78, 0.76, 0.72), "donor_b": (0.24, 0.34, 0.43), "donor_c": (0.36, 0.38, 0.26), "primer": (0.54, 0.55, 0.52),
    31:     "rust": (0.42, 0.23, 0.13), "handpaint": (0.93, 0.89, 0.8), "warpaint": (0.76, 0.23, 0.15),
    32:     # markings: pattern codes, service text, unit codes (a decal layer in geometry)
    33:     "stencil": (0.13, 0.14, 0.16),
    34:     "crystal": (0.8, 0.81, 0.84), "crystal_lit": (0.55, 0.45, 0.78), "glow_violet": (0.66, 0.48, 1.0),
    35: }
    36: 
    37: 
    38: def reset():
    39:     for o in list(bpy.data.objects):
    40:         bpy.data.objects.remove(o, do_unlink=True)
    41:     for coll in (bpy.data.meshes, bpy.data.materials):
    42:         for item in list(coll):
    43:             coll.remove(item)
    44: 
    45: 
    46: def material(role):
    47:     m = bpy.data.materials.get(role)
    48:     if m is None:
    49:         m = bpy.data.materials.new(role)
    50:         c = PREVIEW.get(role, (0.7, 0.7, 0.7))
    51:         m.diffuse_color = (*c, 1.0)
    52:     return m
    53: 
    54: 
    55: def link(o):
    56:     bpy.context.scene.collection.objects.link(o)
    57:     return o
    58: 
    59: 
    60: def empty(name, at=(0, 0, 0), parent=None, **extras):
    61:     """A joint or marker. Children keep their world placement when parented to it."""
    62:     o = link(bpy.data.objects.new(name, None))
    63:     o.empty_display_size = 0.4
    64:     o.location = Vector(at) if parent is None else parent.matrix_world.inverted() @ Vector(at)
    65:     if parent is not None:
    66:         o.parent = parent
    67:     for k, v in extras.items():
    68:         o[k] = v
    69:     bpy.context.view_layer.update()
    70:     return o
    71: 
    72: 
    73: def attach(o, parent):
    74:     """Parent without moving: geometry is authored in world (rest pose) coordinates."""
    75:     bpy.context.view_layer.update()
    76:     mw = o.matrix_world.copy()
    77:     o.parent = parent
    78:     o.matrix_parent_inverse = parent.matrix_world.inverted()
    79:     o.matrix_world = mw
    80:     return o
    81: 
    82: 
    83: # ---- 2D outlines ------------------------------------------------------------------------------------------
    84: def octo(w, d, c=0.2, cf=None, cb=None, x=0.0, y=0.0):
    85:     """A chamfered rectangle, w along X and d along Y, CCW seen from above. The front (-Y) and back
    86:     chamfers can differ: cf, cb. Returns 8 points."""
    87:     cf = c if cf is None else cf
    88:     cb = c if cb is None else cb
    89:     hw, hd = w / 2, d / 2
    90:     cf, cb = min(cf, hw * 0.95, hd * 0.95), min(cb, hw * 0.95, hd * 0.95)
    91:     return [(x - hw + cf, y - hd), (x + hw - cf, y - hd), (x + hw, y - hd + cf), (x + hw, y + hd - cb),
    92:             (x + hw - cb, y + hd), (x - hw + cb, y + hd), (x - hw, y + hd - cb), (x - hw, y - hd + cf)]
    93: 
    94: 
    95: def circle(r, n=12, x=0.0, y=0.0, phase=0.5):
    96:     return [(x + r * math.cos(2 * math.pi * (i + phase) / n), y + r * math.sin(2 * math.pi * (i + phase) / n))
    97:             for i in range(n)]
    98: 
    99: 
    100: def ccw(poly):
    101:     a = sum(poly[i][0] * poly[(i + 1) % len(poly)][1] - poly[(i + 1) % len(poly)][0] * poly[i][1]
    102:             for i in range(len(poly)))
    103:     return poly if a > 0 else list(reversed(poly))
    104: 
    105: 
    106: # ---- solids (bmesh) ---------------------------------------------------------------------------------------
    107: def loft(rings, axis="z", caps=True):
    108:     """rings: [(height, [(u, v), ...]), ...], all with the same point count. With axis "z" the outline
    109:     is (x, y) at height z; "y" means (x, z) outlines along y; "x" means (y, z) outlines along x."""
    110:     bm = bmesh.new()
    111:     loops = []
    112:     for h, pts in rings:
    113:         loop = []
    114:         for u, v in pts:
    115:             p = {"z": (u, v, h), "y": (u, h, v), "x": (h, u, v)}[axis]
    116:             loop.append(bm.verts.new(p))
    117:         loops.append(loop)
    118:     n = len(loops[0])
    119:     for a, b in zip(loops, loops[1:]):
    120:         for i in range(n):
    121:             j = (i + 1) % n
    122:             bm.faces.new((a[i], a[j], b[j], b[i]))
    123:     if caps:
    124:         bm.faces.new(list(reversed(loops[0])))
    125:         bm.faces.new(loops[-1])
    126:     _outward(bm)
    127:     return bm
    128: 
    129: 
    130: def prism(poly, lo, hi, plane="xz"):
    131:     """A 2D outline pushed through [lo, hi]. plane "xz": outline in (x, z), depth along y.
    132:     "yz": (y, z) along x. "xy": (x, y) along z."""
    133:     poly = ccw(poly)
    134:     axis = {"xz": "y", "yz": "x", "xy": "z"}[plane]
    135:     return loft([(lo, poly), (hi, poly)], axis=axis)
    136: 
    137: 
    138: def _outward(bm):
    139:     bmesh.ops.recalc_face_normals(bm, faces=bm.faces)
    140: 
    141: 
    142: def merge(*bms):
    143:     out = bmesh.new()
    144:     for b in bms:
    145:         me = bpy.data.meshes.new("_tmp")
    146:         b.to_mesh(me)
    147:         out.from_mesh(me)
    148:         bpy.data.meshes.remove(me)
    149:         b.free()
    150:     return out
    151: 
    152: 
    153: def transform(bm, m):
    154:     bmesh.ops.transform(bm, matrix=m, verts=bm.verts)
    155:     return bm
    156: 
    157: 
    158: def mirror_x(bm):
    159:     """A mirrored copy (left from right) with the winding fixed."""
    160:     me = bpy.data.meshes.new("_m")
    161:     bm.to_mesh(me)
    162:     out = bmesh.new()
    163:     out.from_mesh(me)
    164:     bpy.data.meshes.remove(me)
    165:     bmesh.ops.scale(out, vec=(-1, 1, 1), verts=out.verts)
    166:     bmesh.ops.reverse_faces(out, faces=out.faces)
    167:     return out
    168: 
    169: 
    170: def rot(axis, deg, about=(0, 0, 0)):
    171:     c = Vector(about)
    172:     return Matrix.Translation(c) @ Matrix.Rotation(math.radians(deg), 4, axis) @ Matrix.Translation(-c)
    173: 
    174: 
    175: # ---- objects ----------------------------------------------------------------------------------------------
    176: def solid(name, bm, role, parent=None, bevel=0.0, segs=1, angle=40, smooth=False, outline=True, panels=None):
    177:     """Turn a bmesh into an object with a material role, an optional chamfer on edges sharper than
    178:     `angle`, flat or smooth shading, parented to a joint without moving. Armour roles get panel
    179:     seams on their large faces unless panels=False."""
    180:     me = bpy.data.meshes.new(name)
    181:     bm.to_mesh(me)
    182:     bm.free()
    183:     me.materials.append(material(role))
    184:     o = link(bpy.data.objects.new(name, me))
    185:     if bevel > 0:
    186:         mod = o.modifiers.new("bevel", "BEVEL")
    187:         mod.width = bevel
    188:         mod.segments = segs
    189:         mod.limit_method = "ANGLE"
    190:         mod.angle_limit = math.radians(angle)
    191:         mod.use_clamp_overlap = True
    192:         mod.miter_outer = "MITER_ARC"
    193:         bake(o)
    194:     if panels is None:
    195:         panels = role in ("main", "accent", "hull") and not smooth
    196:     if panels:
    197:         panel_lines(o)
    198:     me = o.data
    199:     if smooth:
    200:         me.shade_smooth()
    201:         me.set_sharp_from_angle(angle=math.radians(65 if bevel > 0 else 35))
    202:         if bevel > 0:
    203:             o["weighted_normal"] = True
    204:     if not outline:
    205:         o["outline"] = False
    206:     if parent is not None:
    207:         attach(o, parent)
    208:     return o
    209: 
    210: 
    211: def panel_lines(o, min_area=1.1, width=0.05, depth=0.016):
    212:     """Recess every large face slightly inside a thin border: reads as panel seams on armour."""
    213:     bm = bmesh.new()
    214:     bm.from_mesh(o.data)
    215:     faces = [f for f in bm.faces if f.calc_area() > min_area]
    216:     if faces:
    217:         bmesh.ops.inset_individual(bm, faces=faces, thickness=width, depth=-depth, use_even_offset=True)
    218:     bm.to_mesh(o.data)
    219:     bm.free()
    220:     return o
    221: 
    222: 
    223: def bake(o):
    224:     dg = bpy.context.evaluated_depsgraph_get()
    225:     me = bpy.data.meshes.new_from_object(o.evaluated_get(dg))
    226:     old = o.data
    227:     o.modifiers.clear()
    228:     o.data = me
    229:     me.name = old.name
    230:     bpy.data.meshes.remove(old)
    231:     return o
    232: 
    233: 
    234: def boolean(target, cutter_bm, op="DIFFERENCE", role=None):
    235:     """Cut (or intersect/union) a solid object with a bmesh volume. With a role, the faces the cutter
    236:     leaves behind (the inside of a cavity) take that material."""
    237:     me = bpy.data.meshes.new("_cut")
    238:     cutter_bm.to_mesh(me)
    239:     cutter_bm.free()
    240:     if role is not None:
    241:         me.materials.append(material(role))
    242:     cutter = link(bpy.data.objects.new("_cut", me))
    243:     bpy.context.view_layer.update()
    244:     cutter.matrix_world = target.matrix_world.copy()
    245:     mod = target.modifiers.new("bool", "BOOLEAN")
    246:     mod.operation = op
    247:     mod.object = cutter
    248:     mod.solver = "EXACT"
    249:     if role is not None:
    250:         mod.material_mode = "TRANSFER"
    251:     bake(target)
    252:     bpy.data.objects.remove(cutter, do_unlink=True)
    253:     bpy.data.meshes.remove(me)
    254:     return target
    255: 
    256: 
    257: def two_view(front, side, top=None, span=60.0):
    258:     """Intersect a front outline (x, z) with a side outline (y, z), and optionally a top outline
    259:     (x, y). Returns a bmesh. The classic way to block out armour and heads."""
    260:     a = prism(front, -span, span, "xz")
    261:     me = bpy.data.meshes.new("_tv")
    262:     a.to_mesh(me)
    263:     a.free()
    264:     o = link(bpy.data.objects.new("_tv", me))
    265:     boolean(o, prism(side, -span, span, "yz"), "INTERSECT")
    266:     if top is not None:
    267:         boolean(o, prism(top, -span, span, "xy"), "INTERSECT")
    268:     bm = bmesh.new()
    269:     bm.from_mesh(o.data)
    270:     bpy.data.objects.remove(o, do_unlink=True)
    271:     return bm
    272: 
    273: 
    274: def clip(bm, x=(-60, 60), y=(-60, 60), z=(-60, 60)):
    275:     """The part of a solid inside an axis-aligned box. Cutting one envelope into several boxes with
    276:     gaps between them gives separate shells over the same form."""
    277:     me = bpy.data.meshes.new("_clip")
    278:     bm.to_mesh(me)
    279:     bm.free()
    280:     o = link(bpy.data.objects.new("_clip", me))
    281:     cut = loft([(z[0], [(x[0], y[0]), (x[1], y[0]), (x[1], y[1]), (x[0], y[1])]),
    282:                 (z[1], [(x[0], y[0]), (x[1], y[0]), (x[1], y[1]), (x[0], y[1])])])
    283:     boolean(o, cut, "INTERSECT")
    284:     out = bmesh.new()
    285:     out.from_mesh(o.data)
    286:     data = o.data
    287:     bpy.data.objects.remove(o, do_unlink=True)
    288:     bpy.data.meshes.remove(data)
    289:     return out
    290: 
    291: 
    292: def copy(bm):
    293:     me = bpy.data.meshes.new("_copy")
    294:     bm.to_mesh(me)
    295:     out = bmesh.new()
    296:     out.from_mesh(me)
    297:     bpy.data.meshes.remove(me)
    298:     return out
    299: 
    300: 
    301: def _keep_side(bm, co, no, below):
    302:     """Keep the part of a solid below (or above) a plane and cap the opening."""
    303:     geom = bm.verts[:] + bm.edges[:] + bm.faces[:]
    304:     res = bmesh.ops.bisect_plane(bm, geom=geom, plane_co=co, plane_no=no, clear_outer=below, clear_inner=not below)
    305:     edges = [e for e in res["geom_cut"] if isinstance(e, bmesh.types.BMEdge)]
    306:     if edges:
    307:         bmesh.ops.holes_fill(bm, edges=edges, sides=0)
    308:     bmesh.ops.recalc_face_normals(bm, faces=bm.faces)
    309:     return bm
    310: 
    311: 
    312: def halves(bm, co, no, gap=.04):
    313:     """Split a solid along a plane into two capped pieces with a gap between them: a panel seam
    314:     with real depth, so the dark frame beneath shows through."""
    315:     co, no = Vector(co), Vector(no).normalized()
    316:     a = _keep_side(copy(bm), co - no * gap / 2, no, below=True)
    317:     b = _keep_side(bm, co + no * gap / 2, no, below=False)
    318:     return a, b
    319: 
    320: 
    321: def panels(bm, cuts, gap=.04):
    322:     """Cut a solid by several planes [(point, normal), ...] into panels with seams between them."""
    323:     pieces = [bm]
    324:     for co, no in cuts:
    325:         out = []
    326:         for p in pieces:
    327:             for h in halves(p, co, no, gap):
    328:                 if len(h.faces) >= 4:
    329:                     out.append(h)
    330:                 else:
    331:                     h.free()
    332:         pieces = out
    333:     return pieces
    334: 
    335: 
    336: def fold(objs, t, half, y0, y1):
    337:     """Fold the front of a part into a shallow V: in front of y0 (fully in front of y1) every vertex
    338:     moves forward (-Y) by t * (half - |x|), so the centre line becomes a ridge and both sides angle
    339:     back. Meshes are cut on the centre line first so flat plates fold instead of tilting. Works on
    340:     mesh coordinates, which are the authored ones."""
    341:     for ob in objs:
    342:         bm = bmesh.new()
    343:         bm.from_mesh(ob.data)
    344:         if bm.verts and min(v.co.y for v in bm.verts) < y0:
    345:             geom = bm.verts[:] + bm.edges[:] + bm.faces[:]
    346:             bmesh.ops.bisect_plane(bm, geom=geom, plane_co=(0, 0, 0), plane_no=(1, 0, 0))
    347:             for v in bm.verts:
    348:                 ax = abs(v.co.x)
    349:                 if v.co.y < y0 and ax < half:
    350:                     w = min(1.0, (y0 - v.co.y) / (y0 - y1))
    351:                     v.co.y -= t * (half - ax) * w * w * (3 - 2 * w)
    352:             bm.to_mesh(ob.data)
    353:         bm.free()
    354: 
    355: 
    356: def piston(p0, p1, r=.12, n=8):
    357:     """A hydraulic piston from p0 to p1: a body over the first 60%, a thinner rod the rest, end eyes."""
    358:     p0, p1 = Vector(p0), Vector(p1)
    359:     axis = p1 - p0
    360:     m = Matrix.Translation(p0) @ Vector((0, 0, 1)).rotation_difference(axis.normalized()).to_matrix().to_4x4()
    361:     L = axis.length
    362:     body = loft([(0, circle(r, n)), (L * .6, circle(r, n))])
    363:     rod = loft([(L * .55, circle(r * .45, n)), (L, circle(r * .45, n))])
    364:     eyes = merge(loft([(-r * .4, circle(r * .7, n)), (r * .4, circle(r * .7, n))]),
    365:                  loft([(L - r * .4, circle(r * .6, n)), (L + r * .4, circle(r * .6, n))]))
    366:     return transform(merge(body, rod, eyes), m)
    367: 
    368: 
    369: def subd(bm, levels=2, sharp=45, crease=1.0):
    370:     """Smooth a low-poly cage with Catmull-Clark subdivision. Edges whose faces meet at more than
    371:     `sharp` degrees are creased, so they stay crisp while everything else rounds off: helmets and
    372:     shells that are soft where they should be and hard where they shouldn't."""
    373:     me = bpy.data.meshes.new("_subd")
    374:     bm.to_mesh(me)
    375:     bm.free()
    376:     attr = me.attributes.get("crease_edge") or me.attributes.new("crease_edge", "FLOAT", "EDGE")
    377:     probe = bmesh.new()
    378:     probe.from_mesh(me)
    379:     probe.edges.ensure_lookup_table()
    380:     lim = math.radians(sharp)
    381:     for e in probe.edges:
    382:         f = e.link_faces
    383:         if len(f) == 2 and f[0].normal.angle(f[1].normal, 0) > lim:
    384:             attr.data[e.index].value = crease
    385:     probe.free()
    386:     o = link(bpy.data.objects.new("_subd", me))
    387:     mod = o.modifiers.new("subd", "SUBSURF")
    388:     mod.levels = mod.render_levels = levels
    389:     bake(o)
    390:     out = bmesh.new()
    391:     out.from_mesh(o.data)
    392:     data = o.data
    393:     bpy.data.objects.remove(o, do_unlink=True)
    394:     bpy.data.meshes.remove(data)
    395:     return out
    396: 
    397: 
    398: def cylinder(r, z0, z1, n=10, r1=None, axis="z", at=(0, 0)):
    399:     """An n-sided cylinder (or cone with r1) between z0 and z1 along an axis, centred at `at` in the

    1 more lines not shown.

  • read_file{"EndLine":250,"Path":"~/work/sortie/kit/build.py","StartLine":1}

    input

    {
      "EndLine": 250,
      "Path": "~/work/sortie/kit/build.py",
      "StartLine": 1
    }

    result, 75 lines

    Showing lines 1-74 of 74
    1: """Build every model into public/assets/*.glb.
    2: 
    3:     npm run kit                 # everything
    4:     npm run kit -- striker ship # just these
    5:     npm run kit -- block_dummy  # a block model, kit/blocks/dummy.py
    6: """
    7: import os
    8: import sys
    9: import time
    10: 
    11: sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
    12: 
    13: import lib  # noqa: E402
    14: from block import build_block  # noqa: E402
    15: from cockpit import build_cockpit  # noqa: E402
    16: from cockpit_light import build_cockpit_light  # noqa: E402
    17: from mech import build_striker  # noqa: E402
    18: from heavy import build_heavy, build_heavy_lab  # noqa: E402
    19: from props import build_cannon, build_drone, build_rifle  # noqa: E402
    20: from ship import build_ship  # noqa: E402
    21: from station import build_station  # noqa: E402
    22: from salvage import build_salvage_pod, build_wreck_field  # noqa: E402
    23: from escape_pod import build_escape_pod  # noqa: E402
    24: from light import build_light, build_light_lab  # noqa: E402
    25: from automaton import build_automaton, build_automaton_lab  # noqa: E402
    26: from alien import build_alien, build_alien_lab  # noqa: E402
    27: sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "lab"))
    28: from heads import build_head_lab, build_head_lab2  # noqa: E402
    29: from headkit import build_head_lab3, build_head_lab4, build_head_lab5, build_head_lab6, build_head_lab7, build_head_lab8  # noqa: E402
    30: from sizes import build_sizes  # noqa: E402
    31: from pilotlab import build_pilot_lab  # noqa: E402
    32: from assembly import build_assembly_lab, build_back_lab, build_chest_frames, build_show, game_frame  # noqa: E402
    33: from raider import build_raider, build_raider_lab  # noqa: E402
    34: from pattern_lab import build_pattern_lab, build_pattern_m  # noqa: E402
    35: from atelier_lab import build_atelier_lab  # noqa: E402
    36: from atelier_board import build as build_atelier, build_atelier_line  # noqa: E402
    37: from bodykit import build_chest_lab, build_chest_lab2, build_foot_lab, build_foot_lab2, build_chest_lab3, build_foot_lab3  # noqa: E402
    38: 
    39: OUT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "public", "assets")
    40: ASSETS = {"striker": build_striker, "striker_a": lambda: game_frame(0), "striker_b": lambda: game_frame(1), "rifle": build_rifle, "cannon": build_cannon, "drone": build_drone,
    41:           "cockpit": build_cockpit, "cockpit_light": build_cockpit_light, "ship": build_ship, "station": build_station,
    42:           "wreck_field": build_wreck_field, "salvage_pod": build_salvage_pod, "escape_pod": build_escape_pod,
    43:           "light": lambda: build_light("knight"), "light_line": lambda: build_light("line"), "light_lancer": lambda: build_light("lancer"),
    44:           "heavy": lambda: build_heavy("A"), "heavy_B": lambda: build_heavy("B"), "heavy_C": lambda: build_heavy("C"),
    45:           "lab_heads": build_head_lab, "lab_heads2": build_head_lab2, "lab_heads3": build_head_lab3, "lab_heads4": build_head_lab4, "lab_heads5": build_head_lab5, "lab_heads6": build_head_lab6, "lab_heads7": build_head_lab7, "lab_heads8": build_head_lab8, "lab_chests": build_chest_lab, "lab_feet": build_foot_lab, "lab_chests2": build_chest_lab2, "lab_feet2": build_foot_lab2, "lab_chests3": build_chest_lab3, "lab_feet3": build_foot_lab3, "lab_frames": build_assembly_lab, "lab_backs": build_back_lab, "lab_chests4": build_chest_frames,
    46:           "lab_show": build_show, "lab_show_v": lambda: build_show(formation=True),
    47:           "lab_heavy": build_heavy_lab, "lab_light": build_light_lab, "lab_sizes": build_sizes, "lab_pilot": build_pilot_lab,
    48:           "auto_tally": lambda: build_automaton("tally"), "auto_tick": lambda: build_automaton("tick"),
    49:           "auto_ledger": lambda: build_automaton("ledger"),
    50:           "alien_acicular": lambda: build_alien("acicular"), "alien_druse": lambda: build_alien("druse"),
    51:           "alien_druse_mimic": lambda: build_alien("druse_mimic"), "alien_geode": lambda: build_alien("geode"),
    52:           "raider_grunt": lambda: build_raider("grunt"), "raider_brawler": lambda: build_raider("brawler"),
    53:           "raider_boss": lambda: build_raider("boss"),
    54:           "pattern_m": build_pattern_m, "atelier_estoc": lambda: build_atelier("b", "medium"), "atelier_tilt": lambda: build_atelier("d", "medium"),
    55:           "lab_pattern": build_pattern_lab, "lab_atelier": build_atelier_lab, "lab_atelier_a": lambda: build_atelier_line("a"), "lab_atelier_b": lambda: build_atelier_line("b"),
    56:           "lab_atelier_c": lambda: build_atelier_line("c"), "lab_atelier_d": lambda: build_atelier_line("d"),
    57:           "lab_auto": build_automaton_lab, "lab_alien": build_alien_lab, "lab_raider": build_raider_lab}
    58: 
    59: 
    60: def main(names):
    61:     os.makedirs(OUT, exist_ok=True)
    62:     for name in names or [n for n in ASSETS if not n.startswith("lab")]:
    63:         t = time.time()
    64:         lib.reset()
    65:         if name.startswith("block_"):  # scratch models, kit/blocks/<name>.py
    66:             build_block(name)
    67:         else:
    68:             ASSETS[name]()
    69:         path = os.path.normpath(os.path.join(OUT, f"{name}.glb"))
    70:         lib.export(path)
    71:         print(f"kit: {name} -> {path} ({os.path.getsize(path) // 1024} KB, {time.time() - t:.1f}s)")
    72: 
    73: 
    74: main(sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else [])
  • read_file{"EndLine":250,"Path":"~/work/sortie/src/render/decals.ts","StartLine":1}

    input

    {
      "EndLine": 250,
      "Path": "~/work/sortie/src/render/decals.ts",
      "StartLine": 1
    }

    result, 153 lines

    Showing lines 1-152 of 152
    1: import * as THREE from 'three';
    2: import { DecalGeometry } from 'three/addons/geometries/DecalGeometry.js';
    3: 
    4: // Markings projected onto armour: unit numbers, designations, caution stencils, hazard bands and the
    5: // company emblem. Each decal is found by casting a ray at the rest pose, projected onto the mesh it
    6: // hits, and parented to that mesh so it moves with its joint.
    7: 
    8: export type DecalKind = 'number' | 'stencil' | 'hazard' | 'emblem';
    9: 
    10: export interface DecalSpec {
    11:   kind: DecalKind;
    12:   text?: string;
    13:   /** A point just off the surface, model space (three.js axes: +X the frame's left, +Z forward). */
    14:   at: [number, number, number];
    15:   /** Direction into the surface. */
    16:   dir: [number, number, number];
    17:   /** Width and height in metres. */
    18:   size: [number, number];
    19:   /** Roll around the surface normal, degrees. */
    20:   roll?: number;
    21:   color?: string;
    22: }
    23: 
    24: const textures = new Map<string, THREE.CanvasTexture>();
    25: 
    26: function texture(spec: DecalSpec): THREE.CanvasTexture {
    27:   const key = `${spec.kind}:${spec.text ?? ''}:${spec.color ?? ''}:${spec.size.join('x')}`;
    28:   const hit = textures.get(key);
    29:   if (hit) return hit;
    30:   const W = 512, H = Math.max(32, Math.round((512 * spec.size[1]) / spec.size[0]));
    31:   const c = document.createElement('canvas');
    32:   c.width = W;
    33:   c.height = H;
    34:   const g = c.getContext('2d')!;
    35:   const ink = spec.color ?? '#20242a';
    36:   g.fillStyle = ink;
    37:   g.strokeStyle = ink;
    38:   g.textAlign = 'center';
    39:   g.textBaseline = 'middle';
    40:   if (spec.kind === 'hazard') {
    41:     g.fillStyle = '#e2b42a';
    42:     g.fillRect(0, 0, W, H);
    43:     g.fillStyle = '#15171a';
    44:     for (let x = -H; x < W + H; x += H * 1.4) {
    45:       g.beginPath();
    46:       g.moveTo(x, H); g.lineTo(x + H * 0.7, H); g.lineTo(x + H * 1.4, 0); g.lineTo(x + H * 0.7, 0);
    47:       g.fill();
    48:     }
    49:   } else if (spec.kind === 'emblem') {
    50:     const r = Math.min(W, H) * 0.42;
    51:     g.lineWidth = r * 0.12;
    52:     g.beginPath();
    53:     g.arc(W / 2, H / 2, r, 0, Math.PI * 2);
    54:     g.stroke();
    55:     g.beginPath();
    56:     g.moveTo(W / 2 - r * 0.55, H / 2 - r * 0.25);
    57:     g.lineTo(W / 2, H / 2 + r * 0.45);
    58:     g.lineTo(W / 2 + r * 0.55, H / 2 - r * 0.25);
    59:     g.lineTo(W / 2 + r * 0.3, H / 2 - r * 0.25);
    60:     g.lineTo(W / 2, H / 2 + r * 0.05);
    61:     g.lineTo(W / 2 - r * 0.3, H / 2 - r * 0.25);
    62:     g.closePath();
    63:     g.fill();
    64:   } else {
    65:     const size = spec.kind === 'number' ? H * 0.92 : H * 0.62;
    66:     g.font = `600 ${size}px "Chakra Petch", "Arial Narrow", sans-serif`;
    67:     g.fillText(spec.text ?? '', W / 2, H / 2 + size * 0.04, W * 0.96);
    68:     if (spec.kind === 'stencil') {
    69:       // stencil bridges: thin vertical breaks through the letters
    70:       g.globalCompositeOperation = 'destination-out';
    71:       for (let x = W * 0.08; x < W; x += W / Math.max(4, (spec.text ?? '').length)) g.fillRect(x, 0, W * 0.006, H);
    72:       g.globalCompositeOperation = 'source-over';
    73:     }
    74:   }
    75:   // wear: knock speckles out of the paint
    76:   g.globalCompositeOperation = 'destination-out';
    77:   let s = key.length * 9973;
    78:   const rnd = () => ((s = (s * 16807) % 2147483647) / 2147483647);
    79:   for (let i = 0; i < (W * H) / 900; i++) {
    80:     g.globalAlpha = 0.3 + rnd() * 0.7;
    81:     g.fillRect(rnd() * W, rnd() * H, 1 + rnd() * 3, 1 + rnd() * 2);
    82:   }
    83:   g.globalAlpha = 1;
    84:   g.globalCompositeOperation = 'source-over';
    85:   const t = new THREE.CanvasTexture(c);
    86:   t.colorSpace = THREE.SRGBColorSpace;
    87:   t.anisotropy = 8;
    88:   textures.set(key, t);
    89:   return t;
    90: }
    91: 
    92: const ray = new THREE.Raycaster();
    93: const helper = new THREE.Object3D();
    94: 
    95: export function applyDecals(root: THREE.Object3D, specs: DecalSpec[]) {
    96:   root.updateMatrixWorld(true);
    97:   const meshes: THREE.Mesh[] = [];
    98:   root.traverse((o) => {
    99:     const m = o as THREE.Mesh;
    100:     if (m.isMesh && !(m.material as THREE.MeshBasicMaterial).isMeshBasicMaterial && !m.userData.decal) meshes.push(m);
    101:   });
    102:   for (const spec of specs) {
    103:     const dir = new THREE.Vector3(...spec.dir).normalize();
    104:     const at = new THREE.Vector3(...spec.at).applyMatrix4(root.matrixWorld);
    105:     ray.set(at.clone().addScaledVector(dir, -3), dir.clone().transformDirection(root.matrixWorld));
    106:     const hit = ray.intersectObjects(meshes, false)[0];
    107:     if (!hit?.face) continue;
    108:     const mesh = hit.object as THREE.Mesh;
    109:     const normal = hit.face.normal.clone().transformDirection(mesh.matrixWorld);
    110:     helper.position.copy(hit.point);
    111:     helper.lookAt(hit.point.clone().add(normal));
    112:     helper.rotateZ(THREE.MathUtils.degToRad(spec.roll ?? 0));
    113:     const geo = new DecalGeometry(mesh, hit.point, helper.rotation, new THREE.Vector3(spec.size[0], spec.size[1], 0.6));
    114:     geo.applyMatrix4(mesh.matrixWorld.clone().invert());
    115:     const mat = new THREE.MeshStandardMaterial({
    116:       map: texture(spec), transparent: true, depthWrite: false, polygonOffset: true, polygonOffsetFactor: -4,
    117:       roughness: 0.55, metalness: 0,
    118:     });
    119:     const decal = new THREE.Mesh(geo, mat);
    120:     decal.userData.decal = true;
    121:     decal.receiveShadow = true;
    122:     mesh.add(decal);
    123:   }
    124: }
    125: 
    126: /** The striker's markings: unit number on the shoulders and leg, designation, stencils, hazard bands. */
    127: export const STRIKER_DECALS: DecalSpec[] = [
    128:   { kind: 'number', text: '07', at: [4.8, 15.15, 0], dir: [-1, 0, 0], size: [0.95, 0.7], color: '#e9edf0' },
    129:   { kind: 'emblem', at: [-4.8, 15.15, 0], dir: [1, 0, 0], size: [0.8, 0.8], color: '#e9edf0' },
    130:   { kind: 'number', text: '07', at: [2.6, 3.6, 0.15], dir: [-1, 0, 0], size: [0.55, 0.42], color: '#e9edf0' },
    131:   { kind: 'stencil', text: 'MF-07', at: [1.15, 9.25, 3], dir: [0, 0, -1], size: [0.7, 0.2] },
    132:   { kind: 'stencil', text: 'NO STEP', at: [1.3, 10.05, 3], dir: [0, 0, -1], size: [0.6, 0.15], roll: -20 },
    133:   { kind: 'stencil', text: 'NO STEP', at: [-1.3, 10.05, 3], dir: [0, 0, -1], size: [0.6, 0.15], roll: 20 },
    134:   { kind: 'hazard', at: [1.2, 6.55, 3], dir: [0, 0, -1], size: [0.6, 0.12] },
    135:   { kind: 'hazard', at: [-1.2, 6.55, 3], dir: [0, 0, -1], size: [0.6, 0.12] },
    136:   { kind: 'stencil', text: 'DANGER EXHAUST', at: [0, 12.9, -4], dir: [0, 0, 1], size: [1.1, 0.16] },
    137:   { kind: 'stencil', text: 'STRIKER', at: [-2.6, 3.4, 0.15], dir: [1, 0, 0], size: [0.9, 0.2], roll: 90, color: '#e9edf0' },
    138: ];
    139: 
    140: /** An emblem at every bearing anchor (bearing.*) of a model, using the anchor's direction and size. */
    141: export function bearingDecals(root: THREE.Object3D, color: string): DecalSpec[] {
    142:   root.updateMatrixWorld(true);
    143:   const out: DecalSpec[] = [];
    144:   root.traverse((o) => {
    145:     if (!o.name.startsWith('bearing') || !o.visible) return;
    146:     const at = root.worldToLocal(o.getWorldPosition(new THREE.Vector3()));
    147:     const dir = o.userData.dir as [number, number, number] | undefined;
    148:     const size = Number(o.userData.size ?? 0.5);
    149:     if (dir) out.push({ kind: 'emblem', at: [at.x, at.y, at.z], dir, size: [size, size], color });
    150:   });
    151:   return out;
    152: }
  • read_file{"EndLine":300,"Path":"~/work/sortie/src/render/rig.ts","StartLine":1}error

    input

    {
      "EndLine": 300,
      "Path": "~/work/sortie/src/render/rig.ts",
      "StartLine": 1
    }

    result, error, 1 line

    Encountered error in step execution: file does not exist
  • read_file{"EndLine":250,"Path":"~/work/sortie/src/render/exhaust.ts","StartLine":1}

    input

    {
      "EndLine": 250,
      "Path": "~/work/sortie/src/render/exhaust.ts",
      "StartLine": 1
    }

    result, 170 lines

    Showing lines 1-169 of 169
    1: // Thruster plume state for one frame, from what its flight reports. Pure numbers, no three.js: the
    2: // renderer reads the plumes and draws them (plume.ts). Render-side memory only (when a boost began),
    3: // it never writes the sim.
    4: 
    5: export type NozzleKind = 'main' | 'binder' | 'calf';
    6: export const KINDS: readonly NozzleKind[] = ['main', 'binder', 'calf'];
    7: 
    8: /** One frame's thrusters as the sim reports them. x, y, z: local acceleration (left, up, forward) as
    9:  *  a fraction of boosted forward thrust (FlightState.thrust). */
    10: export interface ThrustReading {
    11:   x: number;
    12:   y: number;
    13:   z: number;
    14:   boosting: boolean;
    15:   /** Assault boost held (no sim field yet: the bench drives it). */
    16:   assault?: boolean;
    17:   /** Seconds since a quick boost began, Infinity or absent for none (no sim field yet). */
    18:   quick?: number;
    19: }
    20: 
    21: /** What one kind of nozzle draws this frame. Lengths and widths are in nozzle radii. */
    22: export interface Plume {
    23:   /** Drawn intensity, 0 hides the plume. */
    24:   level: number;
    25:   length: number;
    26:   /** Extra width over the exit at the plume's widest: a vacuum plume flares out past the bell. */
    27:   flare: number;
    28:   /** White hot core strength, 0..1. */
    29:   core: number;
    30:   /** Shock diamond banding in the core, 0..1. */
    31:   diamonds: number;
    32:   /** How heavy the burn is, 0..1 (an assault boost): a fatter core and mantle carried further down,
    33:    *  a bigger throat glow, more light. */
    34:   heavy: number;
    35:   /** Ignition flash at the exit, 0..2. */
    36:   flash: number;
    37:   /** Shock ring radius, and its brightness 0..1. */
    38:   ring: number;
    39:   ringA: number;
    40: }
    41: 
    42: /** The pilot flame: mains never go fully dark while the reactor runs. */
    43: export const IDLE = 0.06;
    44: 
    45: /** Sustained level per kind, 0..1 where 1 is a full boost: forward thrust on the mains, lift and
    46:  *  strafes on the binders, braking and lift on the calves. */
    47: export function levels(r: ThrustReading, out: Record<NozzleKind, number>): Record<NozzleKind, number> {
    48:   const fwd = Math.max(0, r.z), back = Math.max(0, -r.z), up = Math.max(0, r.y);
    49:   const side = Math.abs(r.x), vert = Math.abs(r.y);
    50:   const boost = r.boosting ? 1 : 0;
    51:   out.main = Math.min(1, Math.max(IDLE, fwd * 1.6 + boost * 0.35));
    52:   out.binder = Math.min(1, side * 1.3 + vert * 1.1 + boost * 0.3 * fwd);
    53:   out.calf = Math.min(1, back * 1.6 + up * 1.2);
    54:   return out;
    55: }
    56: 
    57: /** An ignition `age` seconds ago at `strength` (boost 0.6, quick boost 1, assault boost 1.5): a flash
    58:  *  that dies in a few frames, a shock ring thrown out from the exit, and a surge in length that
    59:  *  settles back over a quarter second. */
    60: export function ignition(age: number, strength: number, out: Ignition = { flash: 0, ring: 0, ringA: 0, surge: 0 }): Ignition {
    61:   if (!(age >= 0) || age > 0.6) {
    62:     out.flash = out.ring = out.ringA = out.surge = 0;
    63:     return out;
    64:   }
    65:   const fade = Math.max(0, 1 - age / 0.32);
    66:   out.flash = strength * Math.exp(-age / 0.045);
    67:   out.ring = 1 + 3.2 * strength * (1 - Math.exp(-age / 0.07));
    68:   out.ringA = Math.min(1, strength) * fade * fade;
    69:   out.surge = strength * Math.exp(-age / 0.12);
    70:   return out;
    71: }
    72: 
    73: export interface Ignition {
    74:   flash: number;
    75:   ring: number;
    76:   ringA: number;
    77:   surge: number;
    78: }
    79: 
    80: /** A quick boost's thrust over time: full in 8 ms, held to 45 ms, gone by about 150 ms. A punch,
    81:  *  not a burn: it bypasses the level smoothing. */
    82: export function quickPulse(age: number): number {
    83:   if (!(age >= 0)) return 0;
    84:   if (age < 0.008) return age / 0.008;
    85:   return age < 0.045 ? 1 : Math.exp(-(age - 0.045) / 0.035);
    86: }
    87: 
    88: const clamp01 = (v: number) => Math.min(1, Math.max(0, v));
    89: const blank = (): Plume => ({ level: 0, length: 0, flare: 0, core: 0, diamonds: 0, heavy: 0, flash: 0, ring: 0, ringA: 0 });
    90: 
    91: /** Plume shape from a level, an ignition surge, a quick boost punch (0..1) and how far an assault
    92:  *  boost has come in (0..1). A quick boost punches out wide, an assault boost is a long heavy jet. */
    93: export function shape(level: number, surge: number, punch: number, assault: number, out: Plume): Plume {
    94:   const l = Math.max(0, level);
    95:   out.level = l;
    96:   out.length = (2.5 + 17 * l + 8 * surge) * (1 + 0.8 * assault);
    97:   out.flare = (0.35 + 1.1 * Math.min(1.2, l) + 0.5 * surge) * (1 + 0.6 * punch) * (1 + 0.45 * assault);
    98:   out.core = clamp01((l - 0.04) / 0.5);
    99:   out.diamonds = Math.max(assault, clamp01((l - 0.7) / 0.3) * 0.45);
    100:   out.heavy = clamp01(assault);
    101:   return out;
    102: }
    103: 
    104: /**
    105:  * Render-side plume memory for one frame: smooths levels (fast attack, slower release, so a plume
    106:  * never pops), notices a boost or assault boost starting and plays its ignition. Steps without
    107:  * allocating.
    108:  */
    109: export class Exhaust {
    110:   readonly plumes: Record<NozzleKind, Plume> = { main: blank(), binder: blank(), calf: blank() };
    111:   private target: Record<NozzleKind, number> = { main: 0, binder: 0, calf: 0 };
    112:   private burstDir: Record<NozzleKind, number> = { main: 0, binder: 0, calf: 0 };
    113:   private level: Record<NozzleKind, number> = { main: 0, binder: 0, calf: 0 };
    114:   private boostAge = Infinity;
    115:   private assaultAge = Infinity;
    116:   private wasBoosting = false;
    117:   private wasAssault = false;
    118:   private dir: ThrustReading = { x: 0, y: 0, z: 0, boosting: false };
    119:   private ign: Ignition[] = [0, 1, 2].map(() => ignition(Infinity, 0));
    120: 
    121:   step(r: ThrustReading, dt: number): this {
    122:     const assault = !!r.assault;
    123:     if (r.boosting && !this.wasBoosting) this.boostAge = 0;
    124:     else this.boostAge += dt;
    125:     if (assault && !this.wasAssault) this.assaultAge = 0;
    126:     else this.assaultAge += dt;
    127:     this.wasBoosting = r.boosting;
    128:     this.wasAssault = assault;
    129: 
    130:     levels(r, this.target);
    131:     // a quick boost fires the nozzles that push the way it goes, on top of the sustained thrust
    132:     const qAge = r.quick ?? Infinity;
    133:     const q = quickPulse(qAge);
    134:     const quickOn = qAge >= 0 && qAge < 0.6;
    135:     const len = Math.hypot(r.x, r.y, r.z) || 1;
    136:     if (quickOn) {
    137:       const d = this.dir;
    138:       d.x = r.x / len;
    139:       d.y = r.y / len;
    140:       d.z = r.z / len;
    141:       levels(d, this.burstDir);
    142:     }
    143: 
    144:     // an assault boost has its own ignition: the plain boost one would stack on it
    145:     const ign = ignition(assault ? Infinity : this.boostAge, 0.55, this.ign[0]);
    146:     const big = ignition(this.assaultAge, 1, this.ign[1]);
    147:     const quick = ignition(qAge, 0.7, this.ign[2]);
    148:     // the assault jet reaches full length over 100 ms and holds
    149:     const reach = assault ? clamp01(this.assaultAge / 0.1) : 0;
    150:     for (const k of KINDS) {
    151:       const t = this.target[k];
    152:       const rate = t > this.level[k] ? 30 : 10;
    153:       this.level[k] += (t - this.level[k]) * (1 - Math.exp(-rate * dt));
    154:       // ignitions show on the nozzles that are firing
    155:       const on = clamp01(this.target[k] * 2) * (k === 'main' ? 1 : 0.6);
    156:       const qOn = quickOn ? clamp01(this.burstDir[k] * 2) : 0;
    157:       const punch = q * qOn;
    158:       const p = shape(this.level[k] + punch, ign.surge * on * 0.5 + big.surge * on + quick.surge * qOn * 0.3, punch,
    159:         k === 'main' ? reach : 0, this.plumes[k]);
    160:       p.flash = ign.flash * on + big.flash * on + quick.flash * qOn;
    161:       // the strongest ring wins: they rarely overlap
    162:       p.ring = ign.ring;
    163:       p.ringA = ign.ringA * on;
    164:       if (big.ringA * on > p.ringA) (p.ring = big.ring, p.ringA = big.ringA * on);
    165:       if (quick.ringA * qOn > p.ringA) (p.ring = quick.ring, p.ringA = quick.ringA * qOn);
    166:     }
    167:     return this;
    168:   }
    169: }
  • read_file{"EndLine":300,"Path":"~/work/sortie/src/view/clip.ts","StartLine":1}

    input

    {
      "EndLine": 300,
      "Path": "~/work/sortie/src/view/clip.ts",
      "StartLine": 1
    }

    result, 263 lines

    Showing lines 1-262 of 262
    1: import * as THREE from 'three';
    2: import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';
    3: import { model, type ModelName } from '../render/assets';
    4: import { STRIKER_DECALS, applyDecals, bearingDecals } from '../render/decals';
    5: import { treatEyes } from '../render/eyes';
    6: import type { ThrustReading } from '../render/exhaust';
    7: import { setLook, look } from '../render/look';
    8: import { MechRig, POSES, type Pose } from '../render/mech';
    9: import { PALETTES, type PaletteName } from '../render/palette';
    10: import { Pipeline } from '../render/pipeline';
    11: import { ShipRig } from '../render/ship';
    12: import { addSpaceLight, createBackdrop, followSun, spaceEnvironment } from '../render/space';
    13: import { LAUNCH } from '../sim/launch';
    14: import { BEND_POSE, DEFAULT_SHOTS, clipFrames, mixPose, shotView, type ShotName } from './clip-plan';
    15: import { CameraRig } from './cameras';
    16: import { benchInput } from './thrusters';
    17: 
    18: const HANGAR_POSE: Pose = {
    19:   pelvis: [0, -5, 0], torso: [4, 7, 0], head: [15, 16, 0],
    20:   'thigh.L': [-6, 0, 4], 'shin.L': [10, 0, 0], 'foot.L': [-4, 0, -3],
    21:   'thigh.R': [4, 0, -4], 'shin.R': [6, 0, 0], 'foot.R': [-10, 0, 3],
    22:   'upperarm.L': [-10, 0, 11], 'forearm.L': [-24, 0, 0],
    23:   'upperarm.R': [-24, -8, -9], 'forearm.R': [-38, 0, 0],
    24:   'binder.L': [6, 0, 0], 'binder.R': [6, 0, 0],
    25: };
    26: 
    27: /**
    28:  * A review clip of one model, rendered frame by frame so it comes out the same on any machine. Driven by
    29:  * tools/clip.mjs, which calls window.__clip.render(i) and pipes the frames into ffmpeg.
    30:  *   /?view=clip&model=block_dummy&shots=chase,turn&fps=24&palette=merc&look=kit
    31:  * Any model with the 22 joint rig. Lab lineups hold many frames under slots, so they don't rig.
    32:  */
    33: export async function startClip(canvas: HTMLCanvasElement, q: URLSearchParams) {
    34:   setLook(q.get('look'));
    35:   await document.fonts.ready;
    36:   const w = Number(q.get('w') ?? 854), h = Number(q.get('h') ?? 480), fps = Number(q.get('fps') ?? 24);
    37:   const shots = (q.get('shots')?.split(',') ?? DEFAULT_SHOTS) as ShotName[];
    38:   const frames = clipFrames(shots, fps);
    39: 
    40:   const scene = new THREE.Scene();
    41:   const camera = new THREE.PerspectiveCamera(35, w / h, 0.3, 2e5);
    42:   const backdrop = createBackdrop();
    43:   const pipe = new Pipeline(canvas, scene, camera, backdrop);
    44:   const tier = q.get('tier');
    45:   if (tier === 'medium' || tier === 'low') pipe.setQuality({ tier });
    46:   if (q.get('ao') === '1') pipe.setQuality({ ao: true });
    47:   pipe.resize(w, h);
    48:   const sun = addSpaceLight(scene);
    49:   pipe.shadowLight = sun;
    50:   const hemi = scene.children.find((o) => (o as THREE.HemisphereLight).isHemisphereLight) as THREE.HemisphereLight | undefined;
    51:   const rim = scene.getObjectByName('rim') as THREE.DirectionalLight | undefined;
    52:   const spaceEnv = spaceEnvironment(pipe.renderer, backdrop);
    53:   scene.environment = spaceEnv;
    54:   scene.environmentIntensity = 0.8 * look().fill;
    55: 
    56:   const name = (q.get('model') ?? 'striker') as ModelName;
    57:   const palette = (q.get('palette') ?? 'merc') as PaletteName;
    58:   const trimColor = PALETTES[palette].trim.color;
    59:   const bearings = q.get('bearings') === '1';
    60:   const root = await model(name, palette);
    61:   if (name === 'striker') applyDecals(root, STRIKER_DECALS);
    62:   if (bearings) applyDecals(root, bearingDecals(root, trimColor));
    63:   treatEyes(root, 'spill');
    64:   scene.add(root);
    65:   const rig = new MechRig(root);
    66:   root.updateMatrixWorld(true);
    67:   rig.apply(POSES.stand);
    68:   root.updateMatrixWorld(true);
    69:   const box = new THREE.Box3().setFromObject(root);
    70:   const height = box.getSize(new THREE.Vector3()).y;
    71:   const footY = box.min.y;
    72:   const size = height / 17.6;
    73:   const hangarSole = rig.soles(HANGAR_POSE);
    74:   const launchSole = rig.soles(POSES.launch);
    75:   rig.apply(POSES.stand);
    76: 
    77:   const weapon = q.get('weapon') as ModelName | null;
    78:   if (weapon) rig.hold(await model(weapon, palette));
    79: 
    80:   const light = new THREE.PointLight('#ffffff', 0, 0, 2);
    81:   scene.add(light);
    82: 
    83:   // the ship hangar and catapult tube, loaded only when hangar or launch shots are requested
    84:   const needsShip = shots.includes('hangar') || shots.includes('launch');
    85:   const ship = needsShip ? await ShipRig.load() : null;
    86:   let roomEnv: THREE.Texture | null = null;
    87:   const shipLights: [THREE.PointLight, number][] = [];
    88:   const hangarKey = new THREE.PointLight('#fff3e0', 0, 44, 1.6);
    89:   hangarKey.position.set(-3.5, 9.5, 4.5);
    90:   if (ship) {
    91:     const pmrem = new THREE.PMREMGenerator(pipe.renderer);
    92:     roomEnv = pmrem.fromScene(new RoomEnvironment(), 0.04, 0.1, 100, { size: 256 }).texture;
    93:     pmrem.dispose();
    94:     ship.configure(['standard', 'standard'], 'standard');
    95:     for (const l of ship.lights) shipLights.push([l, l.intensity]);
    96:     scene.add(ship.root);
    97:     scene.add(hangarKey);
    98:     const bay2Name = (q.get('bay2') ?? (name === 'atelier_estoc' ? 'atelier_tilt' : 'striker_a')) as ModelName;
    99:     const spare = await model(bay2Name, palette);
    100:     if (bay2Name === 'striker') applyDecals(spare, STRIKER_DECALS);
    101:     if (bearings) applyDecals(spare, bearingDecals(spare, trimColor));
    102:     treatEyes(spare, 'spill');
    103:     spare.position.copy(ship.slots[1]?.standard[0] ?? ship.bays[1]);
    104:     spare.rotation.y = 0.36;
    105:     new MechRig(spare).apply(POSES.stand);
    106:     ship.root.add(spare);
    107:     const crew = await model('lab_pilot' as ModelName, palette);
    108:     crew.traverse((o) => { if (/^slot\d+$/.test(o.name) && o.name !== 'slot0') o.visible = false; });
    109:     crew.position.set(-1.1 + 0.55, 0.2, -2.6);
    110:     crew.rotation.y = Math.PI - 0.42;
    111:     ship.root.add(crew);
    112:   }
    113: 
    114:   // the pilot and deck for the standalone scale shot: a person is the one thing everyone knows the size of
    115:   const ground = new THREE.Group();
    116:   const deck = new THREE.Mesh(new THREE.CircleGeometry(height * 2, 48), new THREE.MeshStandardMaterial({ color: '#2a2f36', roughness: 0.85, metalness: 0.2 }));
    117:   deck.rotation.x = -Math.PI / 2;
    118:   deck.position.y = footY;
    119:   ground.add(deck);
    120:   const pilot = await model('lab_pilot' as ModelName, palette);
    121:   pilot.traverse((o) => { if (/^slot\d+$/.test(o.name) && o.name !== 'slot0') o.visible = false; });
    122:   // lab slot 0 stands at x = -.55: bring the pilot beside the frame's foot, facing the camera
    123:   pilot.position.set(0.55 + height * 0.3, footY, height * 0.16);
    124:   pilot.rotation.y = 0.4;
    125:   ground.add(pilot);
    126:   scene.add(ground);
    127: 
    128:   const setOutdoor = (out: number, keyBoost = 0) => {
    129:     sun.intensity = 0.22 + 2.98 * out;
    130:     if (rim) rim.intensity = 1.6 * out;
    131:     if (hemi) hemi.intensity = 0.16 + 0.09 * out;
    132:     scene.environment = roomEnv && out < 0.5 ? roomEnv : spaceEnv;
    133:     scene.environmentIntensity = (out < 0.5 ? 0.52 : 0.8) * look().fill;
    134:     const inside = 1 - THREE.MathUtils.smoothstep(out, 0.7, 1.0);
    135:     for (const [l, baseI] of shipLights) l.intensity = baseI * inside;
    136:     hangarKey.intensity = 110 * keyBoost;
    137:   };
    138: 
    139:   // the game's chase camera, read for its numbers: this view moves its own camera
    140:   const chase = new CameraRig();
    141:   const reading: ThrustReading = { x: 0, y: 0, z: 0, boosting: false };
    142:   const centre = new THREE.Vector3();
    143:   const offset = new THREE.Vector3();
    144:   const look_ = new THREE.Vector3();
    145:   const up = new THREE.Vector3(0, 1, 0);
    146:   const yawQ = new THREE.Quaternion();
    147:   const DT = 1 / 120;
    148:   let clock = 0, lastFrame = -2;
    149: 
    150:   const feed = (state: Parameters<typeof benchInput>[0], t: number, dt: number) => {
    151:     const f = benchInput(state, t);
    152:     reading.x = f.thrust.x;
    153:     reading.y = f.thrust.y;
    154:     reading.z = f.thrust.z;
    155:     reading.boosting = f.boosting;
    156:     reading.assault = f.assault;
    157:     reading.quick = f.quick;
    158:     rig.thrust(reading, clock, dt);
    159:     rig.lightExhaust(light);
    160:   };
    161: 
    162:   const ease = (x: number) => x * x * (3 - 2 * x);
    163: 
    164:   const render = (i: number) => {
    165:     const f = frames[i];
    166:     const v = shotView(f);
    167:     // thrusters step at 120 Hz whatever the clip's frame rate, as a game would
    168:     const dt = f.cut ? 0 : 1 / fps;
    169:     if (f.cut || i !== lastFrame + 1) {
    170:       for (let k = 0; k < 120; k++) { clock += DT; feed('idle', k * DT, DT); }
    171:       for (let s = Math.max(0, f.stateT - 0.6); s < f.stateT - dt - 1e-9; s += DT) { clock += DT; feed(f.state, s, DT); }
    172:     }
    173:     lastFrame = i;
    174:     for (let s = 0; s < dt - 1e-9; s += DT) {
    175:       clock += DT;
    176:       feed(f.state, Math.max(0, f.stateT - dt + s), DT);
    177:     }
    178:     if (dt === 0) feed(f.state, f.stateT, 0);
    179: 
    180:     ground.visible = v.ground;
    181: 
    182:     if (v.hangar && ship) {
    183:       ship.root.visible = true;
    184:       ship.update({ phase: 'standby', t: 0, shuttle: 0, speed: 0, door: 0 });
    185:       setOutdoor(0, 1);
    186:       rig.apply(HANGAR_POSE);
    187:       root.position.set(3.4, 0.2 - hangarSole, -10.5);
    188:       root.rotation.set(0, -0.4, 0);
    189:       root.updateMatrixWorld(true);
    190:       const e = ease(f.u);
    191:       if (camera.fov !== 50) { camera.fov = 50; camera.updateProjectionMatrix(); }
    192:       camera.position.set(1.2 - 0.9 * e, 1.75 + 0.4 * e, 13.8 - 2.2 * e);
    193:       camera.up.copy(up);
    194:       camera.lookAt(1.3 + 0.5 * e, 8.8 + 0.25 * e, -10.2);
    195:       centre.copy(root.position).y += height * 0.5;
    196:     } else if (v.catapult >= 0 && ship) {
    197:       ship.root.visible = true;
    198:       const door = Math.min(1, 0.45 + f.t / 0.9);
    199:       const k = Math.max(0, (f.t - 1.0) / 1.95);
    200:       const dist = f.t <= 1.0 ? 0 : k <= 1 ? LAUNCH.length * k * k : LAUNCH.length + LAUNCH.exitSpeed * (f.t - 2.95) * 0.65;
    201:       ship.update({
    202:         phase: f.t < 1.0 ? 'countdown' : k <= 1 ? 'catapult' : 'released',
    203:         t: f.t < 0.45 ? 1.5 : 2.5,
    204:         shuttle: Math.min(LAUNCH.length, dist),
    205:         speed: 0,
    206:         door,
    207:       });
    208:       const start = ship.startFor('standard');
    209:       const free = THREE.MathUtils.smoothstep(dist, LAUNCH.length - 6, LAUNCH.length + 22);
    210:       setOutdoor(THREE.MathUtils.smoothstep(start.z + dist, 102, 132), 0);
    211:       rig.apply(mixPose(POSES.launch, POSES.flight, free));
    212:       root.position.set(start.x, start.y - launchSole * (1 - free) + 1.8 * free, start.z + dist);
    213:       root.rotation.set(THREE.MathUtils.degToRad(5 * free), 0, 0);
    214:       root.updateMatrixWorld(true);
    215:       if (camera.fov !== 62) { camera.fov = 62; camera.updateProjectionMatrix(); }
    216:       const lag = Math.min(8.5, dist * 0.1) * (1 - free * 0.4);
    217:       camera.position.set(-3.1 + 0.7 * free, 8.6 + 1.6 * free, start.z + dist - 19.5 - lag);
    218:       camera.up.copy(up);
    219:       camera.lookAt(0.2 * (1 - free), 9.2 + 1.4 * free, start.z + dist + 28);
    220:       centre.copy(root.position).y += height * 0.5;
    221:     } else {
    222:       if (ship) ship.root.visible = false;
    223:       setOutdoor(1, 0);
    224:       root.position.set(0, 0, 0);
    225:       const bank = v.chase ? THREE.MathUtils.degToRad(-v.mechYaw * 0.32) : 0;
    226:       const lean = v.chase ? THREE.MathUtils.degToRad(5) : 0;
    227:       root.rotation.set(lean, THREE.MathUtils.degToRad(v.mechYaw), bank);
    228:       rig.apply(v.bend > 0 ? mixPose(POSES.stand, BEND_POSE, v.bend) : POSES[v.pose]);
    229:       root.updateMatrixWorld(true);
    230:       centre.set(0, footY + height * v.lookAt, 0);
    231:       const fov = v.chase ? chase.camera.fov : 35;
    232:       if (camera.fov !== fov) {
    233:         camera.fov = fov;
    234:         camera.updateProjectionMatrix();
    235:       }
    236:       if (v.chase) {
    237:         // where the game's chase camera sits (src/view/cameras.ts), over the shoulder, scaled to the frame
    238:         yawQ.setFromAxisAngle(up, THREE.MathUtils.degToRad(v.camYaw));
    239:         offset.set(chase.shoulder * size, chase.chaseOffset.y * size, chase.chaseOffset.z * size).applyQuaternion(yawQ);
    240:         camera.position.copy(centre).add(offset);
    241:         look_.set(chase.shoulder * size, (chase.chaseOffset.y - chase.lookDrop) * size, 400).applyQuaternion(yawQ).add(centre);
    242:         camera.up.copy(up);
    243:         camera.lookAt(look_);
    244:       } else {
    245:         const yaw = THREE.MathUtils.degToRad(v.camYaw), pitch = THREE.MathUtils.degToRad(v.pitch);
    246:         camera.position.set(Math.sin(yaw) * Math.cos(pitch), Math.sin(pitch), Math.cos(yaw) * Math.cos(pitch)).multiplyScalar(v.dist * height).add(centre);
    247:         if (v.ground) camera.position.y = Math.max(camera.position.y, footY + 1.6); // eye height, above the deck
    248:         camera.up.copy(up);
    249:         camera.lookAt(centre);
    250:       }
    251:     }
    252:     camera.updateMatrixWorld(true);
    253:     followSun(sun, centre);
    254:     pipe.render();
    255:     // read straight after the draw, in the same task, while the buffer still holds it
    256:     return canvas.toDataURL('image/jpeg', 0.93);
    257:   };
    258: 
    259:   const win = window as unknown as { __clip: unknown; __ready: boolean };
    260:   win.__clip = { frames: frames.length, fps, render };
    261:   win.__ready = true;
    262: }

agent

+37:02
reasoning

Examining kit/lib.py and several rendering-related files (mech.ts, plume.ts, palette.ts, assets.ts) along with Python files kit/props.py and kit/cockpit.py. The goal is to understand how the cockpit and weapons systems are integrated within the rendering pipeline. This should reveal the mechanism that determines weapon behavior within the environment.

  • read_file{"EndLine":448,"Path":"~/work/sortie/kit/lib.py","StartLine":398}

    input

    {
      "EndLine": 448,
      "Path": "~/work/sortie/kit/lib.py",
      "StartLine": 398
    }

    result, 52 lines

    Showing lines 398-448 of 448
    398: def cylinder(r, z0, z1, n=10, r1=None, axis="z", at=(0, 0)):
    399:     """An n-sided cylinder (or cone with r1) between z0 and z1 along an axis, centred at `at` in the
    400:     other two coordinates."""
    401:     r1 = r if r1 is None else r1
    402:     return loft([(z0, circle(r, n, *at)), (z1, circle(r1, n, *at))], axis=axis)
    403: 
    404: 
    405: def nozzle(r_out, length, n=12, flare=1.25):
    406:     """A thruster bell along -Z from the origin (throat at z=0, exit at z=-length), open-ended with
    407:     a thick lip. Returns (shell bmesh, glow disc bmesh)."""
    408:     ro, ri = r_out, r_out * 0.78
    409:     rings_out = [(0, circle(ro / flare, n)), (-length * 0.6, circle(ro * 0.92, n)), (-length, circle(ro, n))]
    410:     rings_in = [(-length, circle(ri, n)), (-length * 0.6, circle(ri * 0.9, n)), (0.0, circle(ri / flare * 0.9, n))]
    411:     bm = bmesh.new()
    412:     loops = []
    413:     for h, pts in rings_out + rings_in:
    414:         loops.append([bm.verts.new((u, v, h)) for u, v in pts])
    415:     for a, b in zip(loops, loops[1:]):
    416:         for i in range(n):
    417:             j = (i + 1) % n
    418:             bm.faces.new((a[i], a[j], b[j], b[i]))
    419:     bm.faces.new(list(reversed(loops[0])))
    420:     _outward(bm)
    421:     glow = loft([(-length * 0.15, circle(ri / flare * 0.85, n)), (-length * 0.12, circle(ri / flare * 0.85, n))])
    422:     return bm, glow
    423: 
    424: 
    425: def slats(x0, x1, z0, z1, y, n, depth=0.12, gap=0.35):
    426:     """Horizontal vent slats on a plane facing -Y at depth y."""
    427:     out = []
    428:     h = (z1 - z0) / n
    429:     for i in range(n):
    430:         zb = z0 + i * h
    431:         out.append(prism([(x0, zb), (x1, zb), (x1, zb + h * (1 - gap)), (x0, zb + h * (1 - gap))],
    432:                          y - depth, y + 0.05, "xz"))
    433:     return merge(*out)
    434: 
    435: 
    436: def export(path, extras=True):
    437:     for o in list(bpy.data.objects):
    438:         if o.type == "MESH" and o.get("weighted_normal"):
    439:             del o["weighted_normal"]
    440:             o.data.shade_smooth()
    441:             o.data.set_sharp_from_angle(angle=math.radians(65))
    442:             wn = o.modifiers.new("wn", "WEIGHTED_NORMAL")
    443:             wn.keep_sharp = True
    444:             wn.weight = 50
    445:             bake(o)
    446:     bpy.ops.export_scene.gltf(filepath=path, export_format="GLB", export_apply=True, export_yup=True,
    447:                               export_extras=extras, export_cameras=False, export_lights=False,
    448:                               export_materials="EXPORT", export_normals=True, export_texcoords=False)