agent

+10:18
reasoning

I'm thinking through how to approach this.

  • read_file{"Path":"~/context/brief-sortie-full.md"}

    input

    {
      "Path": "~/context/brief-sortie-full.md"
    }

    result, 33 lines

    Showing lines 1-32 of 32
    1: You are running as Gemini 4 Carbon (gemini-4-carbon) at effort high, in a session of your own. The owner, severian (they/them), asked to see what Gemini 4 Carbon would do with one of their lines of work, sortie, and to see one visual artifact you can make with what the project already has. The project's own session runs on a different model and is not to be touched; you are a separate, parallel look.
    2: 
    3: ## What sortie is
    4: The owner's long-held dream: an original browser mech game (influences: Gundam 00's look, Lancer's frames and mounts, Front Mission's part swapping, Code Geass's knightmare traits for the light class). Mechs are built by Blender scripts. The look should be sleek and realistic, or a stylised sketch look, never toon robots; shape was always the real problem. On 11-08 the owner decided to restart with one mech from scratch, to find a faster, better way of working together; they haven't started yet.
    5: 
    6: Read, in this order:
    7: 1. `docs/handbook.md` in your worktree (entry point: each rule marked earned or guessed; guessed rules don't bind the restart)
    8: 2. `~/context/reflect/sortie.html` (the 11-08 reflection; the box at the top is the restart plan)
    9: 3. `~/context/project_sortie_mech_game.md` (history of the owner's reactions and decisions)
    10: 4. Whatever else in the repo you judge useful (docs/heads.md, docs/sizes.md, docs/lore.md, the kit, the tools the handbook lists).
    11: 
    12: ## Your workspace
    13: - Your current folder is the git worktree `~/work/sortie` (branch `carbon`, made for you from main c257287). Work only here; you may commit here.
    14: - `node_modules` in your worktree is a copy of the main checkout's: use it read-only (no installs).
    15: - Blender 5.2.3 is at `~/.local/bin/blender`; only with `-b`.
    16: - Output folder: `~/out/` (copied to the owner's review route afterwards).
    17: - Keep designs original: no Gundam names or lookalikes. The Phantom Brigade study notes are learning only; nothing from its data goes into the work.
    18: 
    19: ## Rules
    20: - Headless only: no windows on the owner's desktop. Never run anything that drives Windows programs (no tools/winvroid, no powershell.exe, cmd.exe or anything under /mnt/c). Browser rendering via headless Chromium only (Playwright is at `~/work/sortie/node_modules/playwright`; page-side code compiled by tsx can throw "__name is not defined", so keep page-side code as plain .js evaluated as text). Blender only with `-b`.
    21: - Don't install packages. Don't run the full test suite (a test run once ate 36 GB); targeted checks only.
    22: - Nothing runs on the C1 machine; no ssh. No network uploads, no publishing anywhere. Never push.
    23: - Edit files only in your worktree and your output folder. Never push.
    24: 
    25: ## Deliverable
    26: One self-contained HTML page, `index.html` in your output folder, with its images (or a short clip) beside it. The owner finds wordy interfaces tiring: organise, don't narrate; short labelled sections, plain words, no em dashes. At the top: "Gemini 4 Carbon (gemini-4-carbon), effort high" and the date.
    27: 1. **Your read of this line of work:** what's working, what isn't, what you'd keep and drop, and what you would do differently in the restart. Give opinions plainly; disagree with the reflection page where you do.
    28: 2. **What you'd do next** if you ran the restart's first session: a short, concrete sequence.
    29: 3. **The one visual:** a single visual artifact made with what the project already has (its tools, kits, renderers, models, data). Your choice of what it is; pick the thing that best shows what you'd do with this work. Show it large, then say in a few lines how it was made (the commands, wall time) and what you'd change next.
    30: Keep it to one visual; don't build a gallery. Aim to be done in roughly 90 minutes of work.
    31: 
    32: When done, end your turn with: the page path, a 5-line summary, and any commits on your branch. If something only the owner can decide blocks you, say so and stop rather than guessing.
  • read_file{"Path":"~/work/sortie/kit/lib.py"}

    input

    {
      "Path": "~/work/sortie/kit/lib.py"
    }

    result, 438 lines

    Showing lines 1-437 of 437
    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(35))
    202:     if not outline:
    203:         o["outline"] = False
    204:     if parent is not None:
    205:         attach(o, parent)
    206:     return o
    207: 
    208: 
    209: def panel_lines(o, min_area=1.1, width=0.05, depth=0.016):
    210:     """Recess every large face slightly inside a thin border: reads as panel seams on armour."""
    211:     bm = bmesh.new()
    212:     bm.from_mesh(o.data)
    213:     faces = [f for f in bm.faces if f.calc_area() > min_area]
    214:     if faces:
    215:         bmesh.ops.inset_individual(bm, faces=faces, thickness=width, depth=-depth, use_even_offset=True)
    216:     bm.to_mesh(o.data)
    217:     bm.free()
    218:     return o
    219: 
    220: 
    221: def bake(o):
    222:     dg = bpy.context.evaluated_depsgraph_get()
    223:     me = bpy.data.meshes.new_from_object(o.evaluated_get(dg))
    224:     old = o.data
    225:     o.modifiers.clear()
    226:     o.data = me
    227:     me.name = old.name
    228:     bpy.data.meshes.remove(old)
    229:     return o
    230: 
    231: 
    232: def boolean(target, cutter_bm, op="DIFFERENCE", role=None):
    233:     """Cut (or intersect/union) a solid object with a bmesh volume. With a role, the faces the cutter
    234:     leaves behind (the inside of a cavity) take that material."""
    235:     me = bpy.data.meshes.new("_cut")
    236:     cutter_bm.to_mesh(me)
    237:     cutter_bm.free()
    238:     if role is not None:
    239:         me.materials.append(material(role))
    240:     cutter = link(bpy.data.objects.new("_cut", me))
    241:     bpy.context.view_layer.update()
    242:     cutter.matrix_world = target.matrix_world.copy()
    243:     mod = target.modifiers.new("bool", "BOOLEAN")
    244:     mod.operation = op
    245:     mod.object = cutter
    246:     mod.solver = "EXACT"
    247:     if role is not None:
    248:         mod.material_mode = "TRANSFER"
    249:     bake(target)
    250:     bpy.data.objects.remove(cutter, do_unlink=True)
    251:     bpy.data.meshes.remove(me)
    252:     return target
    253: 
    254: 
    255: def two_view(front, side, top=None, span=60.0):
    256:     """Intersect a front outline (x, z) with a side outline (y, z), and optionally a top outline
    257:     (x, y). Returns a bmesh. The classic way to block out armour and heads."""
    258:     a = prism(front, -span, span, "xz")
    259:     me = bpy.data.meshes.new("_tv")
    260:     a.to_mesh(me)
    261:     a.free()
    262:     o = link(bpy.data.objects.new("_tv", me))
    263:     boolean(o, prism(side, -span, span, "yz"), "INTERSECT")
    264:     if top is not None:
    265:         boolean(o, prism(top, -span, span, "xy"), "INTERSECT")
    266:     bm = bmesh.new()
    267:     bm.from_mesh(o.data)
    268:     bpy.data.objects.remove(o, do_unlink=True)
    269:     return bm
    270: 
    271: 
    272: def clip(bm, x=(-60, 60), y=(-60, 60), z=(-60, 60)):
    273:     """The part of a solid inside an axis-aligned box. Cutting one envelope into several boxes with
    274:     gaps between them gives separate shells over the same form."""
    275:     me = bpy.data.meshes.new("_clip")
    276:     bm.to_mesh(me)
    277:     bm.free()
    278:     o = link(bpy.data.objects.new("_clip", me))
    279:     cut = loft([(z[0], [(x[0], y[0]), (x[1], y[0]), (x[1], y[1]), (x[0], y[1])]),
    280:                 (z[1], [(x[0], y[0]), (x[1], y[0]), (x[1], y[1]), (x[0], y[1])])])
    281:     boolean(o, cut, "INTERSECT")
    282:     out = bmesh.new()
    283:     out.from_mesh(o.data)
    284:     data = o.data
    285:     bpy.data.objects.remove(o, do_unlink=True)
    286:     bpy.data.meshes.remove(data)
    287:     return out
    288: 
    289: 
    290: def copy(bm):
    291:     me = bpy.data.meshes.new("_copy")
    292:     bm.to_mesh(me)
    293:     out = bmesh.new()
    294:     out.from_mesh(me)
    295:     bpy.data.meshes.remove(me)
    296:     return out
    297: 
    298: 
    299: def _keep_side(bm, co, no, below):
    300:     """Keep the part of a solid below (or above) a plane and cap the opening."""
    301:     geom = bm.verts[:] + bm.edges[:] + bm.faces[:]
    302:     res = bmesh.ops.bisect_plane(bm, geom=geom, plane_co=co, plane_no=no, clear_outer=below, clear_inner=not below)
    303:     edges = [e for e in res["geom_cut"] if isinstance(e, bmesh.types.BMEdge)]
    304:     if edges:
    305:         bmesh.ops.holes_fill(bm, edges=edges, sides=0)
    306:     bmesh.ops.recalc_face_normals(bm, faces=bm.faces)
    307:     return bm
    308: 
    309: 
    310: def halves(bm, co, no, gap=.04):
    311:     """Split a solid along a plane into two capped pieces with a gap between them: a panel seam
    312:     with real depth, so the dark frame beneath shows through."""
    313:     co, no = Vector(co), Vector(no).normalized()
    314:     a = _keep_side(copy(bm), co - no * gap / 2, no, below=True)
    315:     b = _keep_side(bm, co + no * gap / 2, no, below=False)
    316:     return a, b
    317: 
    318: 
    319: def panels(bm, cuts, gap=.04):
    320:     """Cut a solid by several planes [(point, normal), ...] into panels with seams between them."""
    321:     pieces = [bm]
    322:     for co, no in cuts:
    323:         out = []
    324:         for p in pieces:
    325:             for h in halves(p, co, no, gap):
    326:                 if len(h.faces) >= 4:
    327:                     out.append(h)
    328:                 else:
    329:                     h.free()
    330:         pieces = out
    331:     return pieces
    332: 
    333: 
    334: def fold(objs, t, half, y0, y1):
    335:     """Fold the front of a part into a shallow V: in front of y0 (fully in front of y1) every vertex
    336:     moves forward (-Y) by t * (half - |x|), so the centre line becomes a ridge and both sides angle
    337:     back. Meshes are cut on the centre line first so flat plates fold instead of tilting. Works on
    338:     mesh coordinates, which are the authored ones."""
    339:     for ob in objs:
    340:         bm = bmesh.new()
    341:         bm.from_mesh(ob.data)
    342:         if bm.verts and min(v.co.y for v in bm.verts) < y0:
    343:             geom = bm.verts[:] + bm.edges[:] + bm.faces[:]
    344:             bmesh.ops.bisect_plane(bm, geom=geom, plane_co=(0, 0, 0), plane_no=(1, 0, 0))
    345:             for v in bm.verts:
    346:                 ax = abs(v.co.x)
    347:                 if v.co.y < y0 and ax < half:
    348:                     w = min(1.0, (y0 - v.co.y) / (y0 - y1))
    349:                     v.co.y -= t * (half - ax) * w * w * (3 - 2 * w)
    350:             bm.to_mesh(ob.data)
    351:         bm.free()
    352: 
    353: 
    354: def piston(p0, p1, r=.12, n=8):
    355:     """A hydraulic piston from p0 to p1: a body over the first 60%, a thinner rod the rest, end eyes."""
    356:     p0, p1 = Vector(p0), Vector(p1)
    357:     axis = p1 - p0
    358:     m = Matrix.Translation(p0) @ Vector((0, 0, 1)).rotation_difference(axis.normalized()).to_matrix().to_4x4()
    359:     L = axis.length
    360:     body = loft([(0, circle(r, n)), (L * .6, circle(r, n))])
    361:     rod = loft([(L * .55, circle(r * .45, n)), (L, circle(r * .45, n))])
    362:     eyes = merge(loft([(-r * .4, circle(r * .7, n)), (r * .4, circle(r * .7, n))]),
    363:                  loft([(L - r * .4, circle(r * .6, n)), (L + r * .4, circle(r * .6, n))]))
    364:     return transform(merge(body, rod, eyes), m)
    365: 
    366: 
    367: def subd(bm, levels=2, sharp=45, crease=1.0):
    368:     """Smooth a low-poly cage with Catmull-Clark subdivision. Edges whose faces meet at more than
    369:     `sharp` degrees are creased, so they stay crisp while everything else rounds off: helmets and
    370:     shells that are soft where they should be and hard where they shouldn't."""
    371:     me = bpy.data.meshes.new("_subd")
    372:     bm.to_mesh(me)
    373:     bm.free()
    374:     attr = me.attributes.get("crease_edge") or me.attributes.new("crease_edge", "FLOAT", "EDGE")
    375:     probe = bmesh.new()
    376:     probe.from_mesh(me)
    377:     probe.edges.ensure_lookup_table()
    378:     lim = math.radians(sharp)
    379:     for e in probe.edges:
    380:         f = e.link_faces
    381:         if len(f) == 2 and f[0].normal.angle(f[1].normal, 0) > lim:
    382:             attr.data[e.index].value = crease
    383:     probe.free()
    384:     o = link(bpy.data.objects.new("_subd", me))
    385:     mod = o.modifiers.new("subd", "SUBSURF")
    386:     mod.levels = mod.render_levels = levels
    387:     bake(o)
    388:     out = bmesh.new()
    389:     out.from_mesh(o.data)
    390:     data = o.data
    391:     bpy.data.objects.remove(o, do_unlink=True)
    392:     bpy.data.meshes.remove(data)
    393:     return out
    394: 
    395: 
    396: def cylinder(r, z0, z1, n=10, r1=None, axis="z", at=(0, 0)):
    397:     """An n-sided cylinder (or cone with r1) between z0 and z1 along an axis, centred at `at` in the
    398:     other two coordinates."""
    399:     r1 = r if r1 is None else r1

    38 more lines not shown.

  • read_file{"Path":"~/work/sortie/kit/build.py"}

    input

    {
      "Path": "~/work/sortie/kit/build.py"
    }

    result, 74 lines

    Showing lines 1-73 of 73
    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_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, "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"),
    55:           "lab_atelier_c": lambda: build_atelier_line("c"), "lab_atelier_d": lambda: build_atelier_line("d"),
    56:           "lab_auto": build_automaton_lab, "lab_alien": build_alien_lab, "lab_raider": build_raider_lab}
    57: 
    58: 
    59: def main(names):
    60:     os.makedirs(OUT, exist_ok=True)
    61:     for name in names or [n for n in ASSETS if not n.startswith("lab")]:
    62:         t = time.time()
    63:         lib.reset()
    64:         if name.startswith("block_"):  # scratch models, kit/blocks/<name>.py
    65:             build_block(name)
    66:         else:
    67:             ASSETS[name]()
    68:         path = os.path.normpath(os.path.join(OUT, f"{name}.glb"))
    69:         lib.export(path)
    70:         print(f"kit: {name} -> {path} ({os.path.getsize(path) // 1024} KB, {time.time() - t:.1f}s)")
    71: 
    72: 
    73: main(sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else [])
  • read_file{"Path":"~/work/sortie/kit/lab/atelier_board.py"}

    input

    {
      "Path": "~/work/sortie/kit/lab/atelier_board.py"
    }

    result, 65 lines

    Showing lines 1-64 of 64
    1: """The atelier's four house lines, each in three grades, one lab per line (docs/study-atelier.md):
    2: 
    3:   lab_atelier_a  Harness  plate armour taken seriously     (board_plate)
    4:   lab_atelier_b  Estoc    sleek, few shapes, sharp points  (board_sleek)
    5:   lab_atelier_c  Blazon   bold heraldic, per pale          (board_heraldic)
    6:   lab_atelier_d  Tilt     lopsided tourney harness         (board_tourney)
    7: 
    8: Slots along X: slot1 light, slot2 medium, slot3 heavy. Round 1's medium for reference is lab_atelier's
    9: slot2 (kit/lab/atelier_lab.py). In the houses' livery:
    10: 
    11:     /?view=lab_atelier_c&only=slot2&tx=20&palette=houses&bg=studio
    12: 
    13: ATELIER_SLOTS=1,2 builds only those slots.
    14: """
    15: import os
    16: 
    17: import bpy
    18: from mathutils import Matrix
    19: 
    20: import board_heraldic
    21: import board_plate
    22: import board_sleek
    23: import board_tourney
    24: import frame_std
    25: from lib import attach, empty
    26: from makers import atelier
    27: from makers.shell import Plates
    28: 
    29: SPACING = 10.0
    30: GRADES = ("light", "medium", "heavy")
    31: KNEE = {"light": .41, "medium": .40, "heavy": .39}  # round 1's .43 left a tenth of a metre of thigh
    32: LINES = {"a": ("Harness", board_plate.plates), "b": ("Estoc", board_sleek.plates), "c": ("Blazon", board_heraldic.plates),
    33:          "d": ("Tilt", board_tourney.plates)}
    34: 
    35: 
    36: def _place(frame, slot):
    37:     attach(frame, slot)
    38:     frame.matrix_parent_inverse = Matrix.Identity(4)
    39:     frame.location = (0, 0, 0)
    40:     bpy.context.view_layer.update()
    41: 
    42: 
    43: def stance(J, knee):
    44:     frame_std.bend_knees(J, splay=atelier.SPLAY)
    45:     frame_std.proportion(J, atelier.crown_z(J), knee=knee, crotch=atelier.CROTCH_AT, crown=atelier.CROWN, shoulders=atelier.SHOULDER_OUT)
    46: 
    47: 
    48: def build(line, g):
    49:     name, plates = LINES[line]
    50:     J = frame_std.build_frame(f"atelier_{name.lower()}_{g}")
    51:     plates(J, Plates(f"k{line}", atelier.CHAMFER, smooth=True), g)
    52:     stance(J, KNEE[g])
    53:     return J["frame"]
    54: 
    55: 
    56: def build_atelier_line(line):
    57:     only = os.environ.get("ATELIER_SLOTS")
    58:     root = empty("lab", (0, 0, 0))
    59:     for i, g in enumerate(GRADES, 1):
    60:         if only and str(i) not in only.split(","):
    61:             continue
    62:         slot = empty(f"slot{i}", (i * SPACING, 0, 0), root, label=f"{LINES[line][0]} {g}")
    63:         _place(build(line, g), slot)
    64:     return root
  • read_file{"Path":"~/work/sortie/src/render/look.ts"}

    input

    {
      "Path": "~/work/sortie/src/render/look.ts"
    }

    result, 214 lines

    Showing lines 1-213 of 213
    1: import * as THREE from 'three';
    2: 
    3: // The rendering style: how much edge wear, recess grime, ink lining, paint variation and film grain.
    4: // Two candidates under review: a weathered "field" machine and a clean "kit" (a painted model kit).
    5: 
    6: export interface Look {
    7:   name: 'field' | 'kit' | 'service' | 'sketch';
    8:   /** Convex edges lightened (worn paint catching light), 0..1. */
    9:   ridge: number;
    10:   /** Recesses and seams darkened (grime), 0..1. */
    11:   valley: number;
    12:   /** Dark lining at creases, seams and silhouettes, 0..1. */
    13:   ink: number;
    14:   /** Paint variation across surfaces (albedo and roughness noise), 0..1. */
    15:   grime: number;
    16:   /** Film grain and vignette strength, 0..1. */
    17:   grain: number;
    18:   vignette: number;
    19:   /** Paint finish: roughness for armour paint and whether it has a clear coat. */
    20:   paintRough: number;
    21:   gloss: boolean;
    22:   /** Edges chip to bare metal in a broken pattern (field) instead of a clean highlight (kit). */
    23:   chipped: boolean;
    24:   /** How far paint colours are pulled toward grey (weathered field paint). */
    25:   desaturate: number;
    26:   /** Soft fill from the environment, as a multiplier: low for hard field light, high for a studio look. */
    27:   fill: number;
    28:   /** Cel-banded lighting, pencil hatching in shadow, and a paper tone (the sketch look). */
    29:   toon?: boolean;
    30:   hatch?: number;
    31:   paper?: number;
    32: }
    33: 
    34: export const LOOKS: Record<Look['name'], Look> = {
    35:   field: { name: 'field', ridge: 0.85, valley: 0.7, ink: 0.15, grime: 1, grain: 0.045, vignette: 0.35, paintRough: 0.66, gloss: false,
    36:     chipped: true, desaturate: 0.28, fill: 0.5 },
    37:   kit: { name: 'kit', ridge: 0.22, valley: 0.2, ink: 0.95, grime: 0, grain: 0, vignette: 0.12, paintRough: 0.32, gloss: true,
    38:     chipped: false, desaturate: 0, fill: 1.15 },
    39:   // between field and kit: kit's lining at two-thirds, field's wear at a lighter touch, semi-matte
    40:   service: { name: 'service', ridge: 0.5, valley: 0.45, ink: 0.6, grime: 0.5, grain: 0.025, vignette: 0.25, paintRough: 0.48, gloss: false,
    41:     chipped: true, desaturate: 0.12, fill: 0.85 },
    42:   sketch: { name: 'sketch', ridge: 0.1, valley: 0.25, ink: 1, grime: 0, grain: 0.02, vignette: 0.2, paintRough: 0.55, gloss: false,
    43:     chipped: false, desaturate: 0.12, fill: 0.85, toon: true, hatch: 1, paper: 1 },
    44: };
    45: 
    46: let current: Look = LOOKS.field;
    47: export const look = () => current;
    48: export function setLook(name: string | null) {
    49:   current = LOOKS[(name as Look['name']) ?? 'field'] ?? LOOKS.field;
    50:   return current;
    51: }
    52: 
    53: /** Screen-space surface detail from the normal/depth pre-pass: [redacted: secret] wear, grime, ink. */
    54: export const DetailShader = {
    55:   uniforms: {
    56:     tDiffuse: { value: null },
    57:     tNormal: { value: null },
    58:     tDepth: { value: null },
    59:     px: { value: new THREE.Vector2(1, 1) },
    60:     near: { value: 0.5 },
    61:     far: { value: 60000 },
    62:     ridgeK: { value: 0.5 },
    63:     valleyK: { value: 0.5 },
    64:     inkK: { value: 0.2 },
    65:     chipped: { value: 0 },
    66:     hatch: { value: 0 },
    67:     projInv: { value: new THREE.Matrix4() },
    68:     viewInv: { value: new THREE.Matrix4() },
    69:   },
    70:   vertexShader: 'varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); }',
    71:   fragmentShader: /* glsl */ `
    72:     #include <packing>
    73:     uniform sampler2D tDiffuse, tNormal, tDepth;
    74:     uniform vec2 px;
    75:     uniform float near, far, ridgeK, valleyK, inkK, chipped, hatch;
    76:     uniform mat4 projInv, viewInv;
    77:     varying vec2 vUv;
    78:     float hash3(vec3 p) { return fract(sin(dot(p, vec3(7.1, 157.3, 113.7))) * 43758.5); }
    79:     float vnoise(vec3 p) { vec3 i = floor(p), f = fract(p); f = f * f * (3.0 - 2.0 * f);
    80:       return mix(mix(mix(hash3(i), hash3(i + vec3(1,0,0)), f.x), mix(hash3(i + vec3(0,1,0)), hash3(i + vec3(1,1,0)), f.x), f.y),
    81:                  mix(mix(hash3(i + vec3(0,0,1)), hash3(i + vec3(1,0,1)), f.x), mix(hash3(i + vec3(0,1,1)), hash3(i + vec3(1,1,1)), f.x), f.y), f.z); }
    82:     vec3 worldAt(vec2 uv) {
    83:       float d = texture2D(tDepth, uv).x;
    84:       vec4 v = projInv * vec4(uv * 2.0 - 1.0, d * 2.0 - 1.0, 1.0);
    85:       return (viewInv * vec4(v.xyz / v.w, 1.0)).xyz;
    86:     }
    87:     vec4 N(vec2 uv) { vec4 n = texture2D(tNormal, uv); return vec4(n.xyz * 2.0 - 1.0, n.a); }
    88:     float Z(vec2 uv) { return -perspectiveDepthToViewZ(texture2D(tDepth, uv).x, near, far); }
    89:     void main() {
    90:       vec4 c = texture2D(tDiffuse, vUv);
    91:       vec4 n0 = N(vUv);
    92:       if (n0.a < 0.5) { gl_FragColor = c; return; }
    93:       vec4 l = N(vUv - vec2(px.x, 0.0)), r = N(vUv + vec2(px.x, 0.0)), d = N(vUv - vec2(0.0, px.y)), u = N(vUv + vec2(0.0, px.y));
    94:       float z0 = Z(vUv);
    95:       // convex where neighbouring normals spread apart, concave where they close in
    96:       float curv = ((r.x - l.x) * r.a * l.a + (u.y - d.y) * u.a * d.a) * 0.5;
    97:       float ridge = smoothstep(0.08, 0.45, curv);
    98:       float valley = smoothstep(0.08, 0.45, -curv);
    99:       // ink at creases and wherever depth steps (seams, overlaps, silhouettes)
    100:       float turn = max(max(1.0 - dot(n0.xyz, l.xyz), 1.0 - dot(n0.xyz, r.xyz)), max(1.0 - dot(n0.xyz, u.xyz), 1.0 - dot(n0.xyz, d.xyz)));
    101:       float zs = max(max(abs(Z(vUv - vec2(px.x, 0.0)) - z0), abs(Z(vUv + vec2(px.x, 0.0)) - z0)),
    102:                      max(abs(Z(vUv - vec2(0.0, px.y)) - z0), abs(Z(vUv + vec2(0.0, px.y)) - z0)));
    103:       float edge = max(smoothstep(0.35, 0.7, turn), smoothstep(0.015, 0.04, zs / z0));
    104:       edge = max(edge, 1.0 - min(min(l.a, r.a), min(u.a, d.a)));
    105:       // detail fades with distance so far-off ships don't turn to noise
    106:       float near_ = 1.0 - smoothstep(60.0, 600.0, z0);
    107:       vec3 col = c.rgb;
    108:       // grime settles in recesses: darker and a little brown
    109:       col = mix(col, col * vec3(0.55, 0.5, 0.45), valley * valleyK * near_);
    110:       if (chipped > 0.5) {
    111:         // chipped paint on convex edges shows the metal beneath, in a broken pattern fixed to the surface
    112:         vec3 wp = worldAt(vUv);
    113:         float n = vnoise(wp * 3.1) * 0.65 + vnoise(wp * 11.0) * 0.35;
    114:         float chip = ridge * smoothstep(0.42, 0.62, n) * ridgeK * near_;
    115:         col = mix(col, vec3(0.32, 0.33, 0.35) * (0.6 + 0.8 * vnoise(wp * 23.0)), chip);
    116:       } else {
    117:         col += (vec3(1.0) - col) * ridge * ridgeK * 0.45 * near_ * clamp(dot(col, vec3(0.33)) * 2.0, 0.3, 1.0);
    118:       }
    119:       if (hatch > 0.0) {
    120:         // pencil hatching in shadow: one direction in half shade, crossed in deep shade
    121:         float lum = dot(col, vec3(0.3, 0.59, 0.11));
    122:         vec2 fc = gl_FragCoord.xy;
    123:         float h1 = step(0.55, fract((fc.x + fc.y) / 6.0));
    124:         float h2 = step(0.55, fract((fc.x - fc.y) / 6.0));
    125:         float shade1 = 1.0 - smoothstep(0.18, 0.32, lum), shade2 = 1.0 - smoothstep(0.08, 0.18, lum);
    126:         col *= 1.0 - hatch * 0.35 * (h1 * shade1 + h2 * shade2);
    127:       }
    128:       col = mix(col, col * 0.18, edge * inkK * mix(0.4, 1.0, near_));
    129:       gl_FragColor = vec4(col, c.a);
    130:     }`,
    131: };
    132: 
    133: /** After tone mapping: vignette and fine grain. */
    134: export const GradeShader = {
    135:   uniforms: { tDiffuse: { value: null }, grain: { value: 0 }, vignette: { value: 0 }, time: { value: 0 }, paper: { value: 0 } },
    136:   vertexShader: 'varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); }',
    137:   fragmentShader: /* glsl */ `
    138:     uniform sampler2D tDiffuse; uniform float grain, vignette, time, paper; varying vec2 vUv;
    139:     float h(vec2 p) { return fract(sin(dot(p, vec2(12.9898, 78.233)) + time) * 43758.5453); }
    140:     void main() {
    141:       vec4 c = texture2D(tDiffuse, vUv);
    142:       vec2 q = vUv - 0.5;
    143:       c.rgb *= 1.0 - vignette * smoothstep(0.25, 0.85, dot(q, q) * 2.2);
    144:       c.rgb += (h(vUv * 1000.0) - 0.5) * grain;
    145:       if (paper > 0.0) {
    146:         // a warm paper tone and its fibre, multiplied under the picture
    147:         float fib = fract(sin(dot(floor(gl_FragCoord.xy / 2.0), vec2(12.9898, 78.233))) * 43758.5453);
    148:         vec3 tone = vec3(1.0, 0.97, 0.9) * (0.94 + 0.06 * fib);
    149:         c.rgb = mix(c.rgb, c.rgb * tone + vec3(0.03, 0.025, 0.015), paper);
    150:       }
    151:       gl_FragColor = c;
    152:     }`,
    153: };
    154: 
    155: /** World-space paint variation: blotches in albedo and roughness so large panels aren't uniform. */
    156: export function addPaintVariation(m: THREE.MeshStandardMaterial, amount: number) {
    157:   if (amount <= 0) return;
    158:   const prev = m.onBeforeCompile;
    159:   m.onBeforeCompile = (shader, r) => {
    160:     prev?.call(m, shader, r);
    161:     shader.vertexShader = shader.vertexShader
    162:       .replace('#include <common>', '#include <common>\nvarying vec3 vPaintPos;')
    163:       .replace('#include <worldpos_vertex>', '#include <worldpos_vertex>\nvPaintPos = (modelMatrix * vec4(transformed, 1.0)).xyz;');
    164:     shader.fragmentShader = shader.fragmentShader
    165:       .replace('#include <common>', `#include <common>
    166:         varying vec3 vPaintPos;
    167:         float pn(vec3 p) { vec3 i = floor(p), f = fract(p); f = f * f * (3.0 - 2.0 * f);
    168:           float a = fract(sin(dot(i, vec3(7.1, 157.3, 113.7))) * 43758.5);
    169:           float b = fract(sin(dot(i + vec3(1,0,0), vec3(7.1, 157.3, 113.7))) * 43758.5);
    170:           float c2 = fract(sin(dot(i + vec3(0,1,0), vec3(7.1, 157.3, 113.7))) * 43758.5);
    171:           float d = fract(sin(dot(i + vec3(1,1,0), vec3(7.1, 157.3, 113.7))) * 43758.5);
    172:           float e = fract(sin(dot(i + vec3(0,0,1), vec3(7.1, 157.3, 113.7))) * 43758.5);
    173:           float f2 = fract(sin(dot(i + vec3(1,0,1), vec3(7.1, 157.3, 113.7))) * 43758.5);
    174:           float g = fract(sin(dot(i + vec3(0,1,1), vec3(7.1, 157.3, 113.7))) * 43758.5);
    175:           float hh = fract(sin(dot(i + vec3(1,1,1), vec3(7.1, 157.3, 113.7))) * 43758.5);
    176:           return mix(mix(mix(a, b, f.x), mix(c2, d, f.x), f.y), mix(mix(e, f2, f.x), mix(g, hh, f.x), f.y), f.z); }
    177:         #ifdef PAINT_LITE
    178:         float paintN(vec3 p) { return pn(p * 0.7); }
    179:         #else
    180:         float paintN(vec3 p) { return pn(p * 0.7) * 0.5 + pn(p * 2.3) * 0.3 + pn(p * 9.0) * 0.2; }
    181:         #endif`)
    182:       .replace('#include <color_fragment>', `#include <color_fragment>
    183:         float pv = paintN(vPaintPos);
    184:         // blotches, plus dirt streaks running down the surfaces (the low tier keeps the broad blotches only)
    185:         #ifdef PAINT_LITE
    186:         float streak = 0.0;
    187:         #else
    188:         float streak = pn(vec3(vPaintPos.x * 3.0, vPaintPos.y * 0.25, vPaintPos.z * 3.0));
    189:         #endif
    190:         diffuseColor.rgb *= 1.0 - ${(0.14 * amount).toFixed(3)} * smoothstep(0.3, 0.8, pv) - ${(0.1 * amount).toFixed(3)} * smoothstep(0.55, 0.9, streak);`)
    191:       .replace('#include <roughnessmap_fragment>', `#include <roughnessmap_fragment>
    192:         roughnessFactor = clamp(roughnessFactor + ${(0.12 * amount).toFixed(3)} * (paintN(vPaintPos * 1.7) - 0.5), 0.05, 1.0);`);
    193:   };
    194:   const key = m.customProgramCacheKey?.bind(m);
    195:   m.customProgramCacheKey = () => `${key ? key() : ''}paint${amount}`;
    196:   painted.add(m);
    197:   setLite(m, paintLite);
    198: }
    199: 
    200: /** Paint variation's fine noise is dear per pixel on a weak GPU: the low tier keeps one octave. */
    201: const painted = new Set<THREE.Material>();
    202: let paintLite = false;
    203: function setLite(m: THREE.Material, on: boolean) {
    204:   m.defines ??= {};
    205:   if (on === 'PAINT_LITE' in m.defines) return;
    206:   if (on) m.defines.PAINT_LITE = '';
    207:   else delete m.defines.PAINT_LITE;
    208:   m.needsUpdate = true;
    209: }
    210: export function setPaintLite(on: boolean) {
    211:   paintLite = on;
    212:   for (const m of painted) setLite(m, on);
    213: }
  • read_file{"Path":"~/work/sortie/src/view/clip.ts"}

    input

    {
      "Path": "~/work/sortie/src/view/clip.ts"
    }

    result, 140 lines

    Showing lines 1-139 of 139
    1: import * as THREE from 'three';
    2: import { model, type ModelName } from '../render/assets';
    3: import { STRIKER_DECALS, applyDecals } from '../render/decals';
    4: import { treatEyes } from '../render/eyes';
    5: import type { ThrustReading } from '../render/exhaust';
    6: import { setLook, look } from '../render/look';
    7: import { MechRig, POSES } from '../render/mech';
    8: import type { PaletteName } from '../render/palette';
    9: import { Pipeline } from '../render/pipeline';
    10: import { addSpaceLight, createBackdrop, followSun, spaceEnvironment } from '../render/space';
    11: import { BEND_POSE, SHOT_NAMES, clipFrames, mixPose, shotView, type ShotName } from './clip-plan';
    12: import { CameraRig } from './cameras';
    13: import { benchInput } from './thrusters';
    14: 
    15: /**
    16:  * A review clip of one model, rendered frame by frame so it comes out the same on any machine. Driven by
    17:  * tools/clip.mjs, which calls window.__clip.render(i) and pipes the frames into ffmpeg.
    18:  *   /?view=clip&model=block_dummy&shots=chase,turn&fps=24&palette=merc&look=kit
    19:  * Any model with the 22 joint rig. Lab lineups hold many frames under slots, so they don't rig.
    20:  */
    21: export async function startClip(canvas: HTMLCanvasElement, q: URLSearchParams) {
    22:   setLook(q.get('look'));
    23:   await document.fonts.ready;
    24:   const w = Number(q.get('w') ?? 854), h = Number(q.get('h') ?? 480), fps = Number(q.get('fps') ?? 24);
    25:   const shots = (q.get('shots')?.split(',') ?? SHOT_NAMES) as ShotName[];
    26:   const frames = clipFrames(shots, fps);
    27: 
    28:   const scene = new THREE.Scene();
    29:   const camera = new THREE.PerspectiveCamera(35, w / h, 0.3, 2e5);
    30:   const backdrop = createBackdrop();
    31:   const pipe = new Pipeline(canvas, scene, camera, backdrop);
    32:   pipe.resize(w, h);
    33:   const sun = addSpaceLight(scene);
    34:   scene.environment = spaceEnvironment(pipe.renderer, backdrop);
    35:   scene.environmentIntensity = 0.8 * look().fill;
    36: 
    37:   const name = (q.get('model') ?? 'striker') as ModelName;
    38:   const palette = (q.get('palette') ?? 'merc') as PaletteName;
    39:   const root = await model(name, palette);
    40:   if (name === 'striker') applyDecals(root, STRIKER_DECALS);
    41:   treatEyes(root, 'spill');
    42:   scene.add(root);
    43:   const rig = new MechRig(root);
    44:   root.updateMatrixWorld(true);
    45:   rig.apply(POSES.stand);
    46:   root.updateMatrixWorld(true);
    47:   const box = new THREE.Box3().setFromObject(root);
    48:   const height = box.getSize(new THREE.Vector3()).y;
    49:   const footY = box.min.y;
    50:   const size = height / 17.6;
    51: 
    52:   const light = new THREE.PointLight('#ffffff', 0, 0, 2);
    53:   scene.add(light);
    54: 
    55:   // the pilot and deck for the scale shot: a person is the one thing everyone knows the size of
    56:   const ground = new THREE.Group();
    57:   const deck = new THREE.Mesh(new THREE.CircleGeometry(height * 2, 48), new THREE.MeshStandardMaterial({ color: '#2a2f36', roughness: 0.85, metalness: 0.2 }));
    58:   deck.rotation.x = -Math.PI / 2;
    59:   deck.position.y = footY;
    60:   ground.add(deck);
    61:   const pilot = await model('lab_pilot' as ModelName, palette);
    62:   pilot.traverse((o) => { if (/^slot\d+$/.test(o.name) && o.name !== 'slot0') o.visible = false; });
    63:   // lab slot 0 stands at x = -.55: bring the pilot beside the frame's foot, facing the camera
    64:   pilot.position.set(0.55 + height * 0.3, footY, height * 0.16);
    65:   pilot.rotation.y = 0.4;
    66:   ground.add(pilot);
    67:   scene.add(ground);
    68: 
    69:   // the game's chase camera, read for its numbers: this view moves its own camera
    70:   const chase = new CameraRig();
    71:   const reading: ThrustReading = { x: 0, y: 0, z: 0, boosting: false };
    72:   const centre = new THREE.Vector3();
    73:   const offset = new THREE.Vector3();
    74:   const look_ = new THREE.Vector3();
    75:   const up = new THREE.Vector3(0, 1, 0);
    76:   const yawQ = new THREE.Quaternion();
    77:   const DT = 1 / 120;
    78:   let clock = 0;
    79: 
    80:   const feed = (state: Parameters<typeof benchInput>[0], t: number, dt: number) => {
    81:     const f = benchInput(state, t);
    82:     reading.x = f.thrust.x;
    83:     reading.y = f.thrust.y;
    84:     reading.z = f.thrust.z;
    85:     reading.boosting = f.boosting;
    86:     reading.assault = f.assault;
    87:     reading.quick = f.quick;
    88:     rig.thrust(reading, clock, dt);
    89:     rig.lightExhaust(light);
    90:   };
    91: 
    92:   const render = (i: number) => {
    93:     const f = frames[i];
    94:     const v = shotView(f);
    95:     // thrusters step at 120 Hz whatever the clip's frame rate, as a game would
    96:     const dt = f.cut ? 0 : 1 / fps;
    97:     if (f.cut) for (let k = 0; k < 120; k++) { clock += DT; feed('idle', k * DT, DT); }
    98:     for (let s = 0; s < dt - 1e-9; s += DT) {
    99:       clock += DT;
    100:       feed(f.state, Math.max(0, f.stateT - dt + s), DT);
    101:     }
    102:     if (dt === 0) feed(f.state, f.stateT, 0);
    103: 
    104:     root.rotation.y = THREE.MathUtils.degToRad(v.mechYaw);
    105:     rig.apply(v.bend > 0 ? mixPose(POSES.stand, BEND_POSE, v.bend) : POSES[v.pose]);
    106:     root.updateMatrixWorld(true);
    107:     ground.visible = v.ground;
    108:     centre.set(0, footY + height * v.lookAt, 0);
    109:     const fov = v.chase ? chase.camera.fov : 35;
    110:     if (camera.fov !== fov) {
    111:       camera.fov = fov;
    112:       camera.updateProjectionMatrix();
    113:     }
    114:     if (v.chase) {
    115:       // where the game's chase camera sits (src/view/cameras.ts), over the shoulder, scaled to the frame
    116:       yawQ.setFromAxisAngle(up, THREE.MathUtils.degToRad(v.camYaw));
    117:       offset.set(chase.shoulder * size, chase.chaseOffset.y * size, chase.chaseOffset.z * size).applyQuaternion(yawQ);
    118:       camera.position.copy(centre).add(offset);
    119:       look_.set(chase.shoulder * size, (chase.chaseOffset.y - chase.lookDrop) * size, 400).applyQuaternion(yawQ).add(centre);
    120:       camera.up.copy(up);
    121:       camera.lookAt(look_);
    122:     } else {
    123:       const yaw = THREE.MathUtils.degToRad(v.camYaw), pitch = THREE.MathUtils.degToRad(v.pitch);
    124:       camera.position.set(Math.sin(yaw) * Math.cos(pitch), Math.sin(pitch), Math.cos(yaw) * Math.cos(pitch)).multiplyScalar(v.dist * height).add(centre);
    125:       if (v.ground) camera.position.y = Math.max(camera.position.y, footY + 1.6); // eye height, above the deck
    126:       camera.up.copy(up);
    127:       camera.lookAt(centre);
    128:     }
    129:     camera.updateMatrixWorld(true);
    130:     followSun(sun, centre);
    131:     pipe.render();
    132:     // read straight after the draw, in the same task, while the buffer still holds it
    133:     return canvas.toDataURL('image/jpeg', 0.93);
    134:   };
    135: 
    136:   const win = window as unknown as { __clip: unknown; __ready: boolean };
    137:   win.__clip = { frames: frames.length, fps, render };
    138:   win.__ready = true;
    139: }
  • read_file{"Path":"~/work/sortie/tools/clip.mjs"}

    input

    {
      "Path": "~/work/sortie/tools/clip.mjs"
    }

    result, 69 lines

    Showing lines 1-68 of 68
    1: // A review clip of one model: chase camera, orbit, turntable, range of motion, next to a pilot.
    2: //   node tools/clip.mjs <model> [--quick] [--shots chase,turn] [--fps 24] [--size 854x480] [--palette merc] [--look kit] [--out file.mp4]
    3: // --quick is for the loop: chase and turntable only, 12 fps, 640x360.
    4: // Starts its own dev server on a free port and always stops it. Frames are rendered one at a time, so
    5: // the clip is smooth however slow the machine (src/view/clip.ts). Writes the mp4 and, because a reader
    6: // that can't watch video still has to judge it, a contact sheet of frames beside it. Headless only.
    7: import { spawn, spawnSync } from 'node:child_process';
    8: import { mkdirSync } from 'node:fs';
    9: import { dirname, resolve } from 'node:path';
    10: import { chromium } from 'playwright';
    11: import { createServer } from 'vite';
    12: 
    13: const args = process.argv.slice(2);
    14: const flag = (name, fallback) => {
    15:   const i = args.indexOf(`--${name}`);
    16:   return i >= 0 ? args[i + 1] : fallback;
    17: };
    18: const name = args[0];
    19: if (!name || name.startsWith('--')) {
    20:   console.error('usage: node tools/clip.mjs <model> [--quick] [--shots chase,orbit,turn,bend,scale] [--fps 24] [--size 854x480] [--palette merc] [--look kit] [--out file.mp4]');
    21:   process.exit(2);
    22: }
    23: const quick = args.includes('--quick');
    24: const [w, h] = flag('size', quick ? '640x360' : '854x480').split('x').map(Number);
    25: const fps = Number(flag('fps', quick ? 12 : 24));
    26: const out = resolve(flag('out', `review/out/one-mech/clips/${name}.mp4`));
    27: const params = new URLSearchParams({ view: 'clip', model: name, w, h, fps, palette: flag('palette', 'merc') });
    28: for (const k of ['shots', 'look']) if (flag(k)) params.set(k, flag(k));
    29: if (quick && !flag('shots')) params.set('shots', 'chase,turn');
    30: mkdirSync(dirname(out), { recursive: true });
    31: 
    32: const started = Date.now();
    33: const server = await createServer({ server: { host: '127.0.0.1', port: 5230, strictPort: false }, logLevel: 'error' });
    34: await server.listen();
    35: const browser = await chromium.launch({ args: ['--use-angle=swiftshader', '--enable-unsafe-swiftshader', '--ignore-gpu-blocklist'] });
    36: let failed = false;
    37: try {
    38:   const page = await browser.newPage({ viewport: { width: w, height: h } });
    39:   page.setDefaultTimeout(300000);
    40:   page.on('pageerror', (e) => { failed = true; console.error('[pageerror]', e.message); });
    41:   page.on('console', (m) => { if (m.type() === 'error') console.error('[console]', m.text().slice(0, 300)); });
    42:   await page.goto(`${server.resolvedUrls.local[0]}?${params}`);
    43:   await page.waitForFunction(() => window.__ready === true);
    44:   const frames = await page.evaluate(() => window.__clip.frames);
    45:   const loaded = Date.now();
    46:   const ffmpeg = spawn('ffmpeg', ['-loglevel', 'error', '-y', '-f', 'image2pipe', '-c:v', 'mjpeg', '-framerate', String(fps), '-i', '-',
    47:     '-c:v', 'libx264', '-crf', '20', '-pix_fmt', 'yuv420p', '-movflags', '+faststart', out], { stdio: ['pipe', 'inherit', 'inherit'] });
    48:   const ended = new Promise((ok) => ffmpeg.on('close', ok));
    49:   for (let i = 0; i < frames; i++) {
    50:     const url = await page.evaluate((n) => window.__clip.render(n), i);
    51:     const jpeg = Buffer.from(url.slice(url.indexOf(',') + 1), 'base64');
    52:     if (!ffmpeg.stdin.write(jpeg)) await new Promise((ok) => ffmpeg.stdin.once('drain', ok));
    53:   }
    54:   ffmpeg.stdin.end();
    55:   const code = await ended;
    56:   if (code !== 0) throw new Error(`ffmpeg exited ${code}`);
    57:   const every = Math.max(1, Math.floor(frames / 12));
    58:   const sheet = out.replace(/\.mp4$/, '.sheet.jpg');
    59:   spawnSync('ffmpeg', ['-loglevel', 'error', '-y', '-i', out, '-vf', `select=not(mod(n\\,${every})),scale=480:-1,tile=4x3`, '-frames:v', '1', '-q:v', '4', sheet], { stdio: 'inherit' });
    60:   const secs = (Date.now() - started) / 1000;
    61:   console.log(`clip: ${out}`);
    62:   console.log(`clip: ${sheet}`);
    63:   console.log(`clip: ${frames} frames, ${(frames / fps).toFixed(1)} s of video, ${secs.toFixed(0)} s to make (${((Date.now() - loaded) / frames).toFixed(0)} ms a frame)`);
    64: } finally {
    65:   await browser.close();
    66:   await server.close();
    67: }
    68: process.exit(failed ? 1 : 0);

agent

+10:26
reasoning

Analyzing rendering-related files to understand the asset pipeline and any potential rendering bottlenecks or inefficiencies. Checking for any discrepancies in how assets are handled across different rendering components and tools used for generating assets. This includes checking asset management, pipeline stages, and specific decal/ship rendering.