agent (cont.)

+0:51
  • 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/makers/shell.py"}

    input

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

    result, 298 lines

    Showing lines 1-297 of 297
    1: """Plate building blocks every maker family shares (docs/visual-language.md, Plates).
    2: 
    3: A plate is a slab on one face of a segment. A Face maps 2D outline coordinates (u across, v up) and
    4: a depth w (outward) to world space, so outlines are written in plain world numbers:
    5: 
    6:   front(y)   the face at y, facing -Y   u = x       v = z
    7:   back(y)    facing +Y                  u = x       v = z
    8:   outer(x)   facing +X (the left side)  u = -y      v = z    (u grows toward the front)
    9:   inner(x)   facing -X                  u = -y      v = z
    10:   top(z)     facing up                  u = x       v = -y   (v grows toward the front)
    11: 
    12: Most plates are shells (below): closed blocks from a front and a side outline. Every plate is
    13: closed, none is hollow with its inside showing. Every plate is authored on the left (+X) and
    14: mirrored for the right unless it straddles the centre line. A maker family decides its outlines,
    15: its band, its chamfer and how each grade sizes and adds to them.
    16: """
    17: import bmesh
    18: import bpy
    19: from mathutils import Matrix, Vector
    20: 
    21: from lib import boolean, ccw, clip, copy, empty, link, loft, merge, mirror_x, solid, transform, two_view
    22: from mech import gltf_dir
    23: 
    24: 
    25: class Face:
    26:     def __init__(self, origin, u, v, w):
    27:         self.o, self.u, self.v, self.w = Vector(origin), Vector(u), Vector(v), Vector(w)
    28:         self.m = Matrix((self.u, self.v, self.w)).transposed().to_4x4()
    29:         self.m.translation = self.o
    30: 
    31:     def at(self, u, v, d=0.0):
    32:         return self.o + self.u * u + self.v * v + self.w * d
    33: 
    34:     def slab(self, outline, d0, d1):
    35:         """The outline pushed out from depth d0 to d1."""
    36:         poly = ccw(list(outline))
    37:         return transform(loft([(d0, poly), (d1, poly)]), self.m)
    38: 
    39: 
    40: def front(y):
    41:     return Face((0, y, 0), (1, 0, 0), (0, 0, 1), (0, -1, 0))
    42: 
    43: 
    44: def back(y):
    45:     return Face((0, y, 0), (1, 0, 0), (0, 0, 1), (0, 1, 0))
    46: 
    47: 
    48: def outer(x):
    49:     return Face((x, 0, 0), (0, -1, 0), (0, 0, 1), (1, 0, 0))
    50: 
    51: 
    52: def inner(x):
    53:     return Face((x, 0, 0), (0, -1, 0), (0, 0, 1), (-1, 0, 0))
    54: 
    55: 
    56: def top(z):
    57:     return Face((0, 0, z), (1, 0, 0), (0, -1, 0), (0, 0, 1))
    58: 
    59: 
    60: def bottom(z):
    61:     return Face((0, 0, z), (1, 0, 0), (0, 1, 0), (0, 0, -1))
    62: 
    63: 
    64: def clipped(u0, u1, v0, v1, c, taper=(0.0, 0.0), corner="tr"):
    65:     """A rectangle with one 45 degree clip of size c. `taper` insets the bottom edge from the left and
    66:     right. `corner`: tr (top right, the usual outboard top), tl, or both."""
    67:     tl, tr = taper
    68:     c = min(c, (u1 - u0) * .6, (v1 - v0) * .6)
    69:     pts = [(u0 + tl, v0), (u1 - tr, v0)]
    70:     pts += [(u1, v1 - c), (u1 - c, v1)] if corner in ("tr", "both") else [(u1, v1)]
    71:     pts += [(u0 + c, v1), (u0, v1 - c)] if corner in ("tl", "both") else [(u0, v1)]
    72:     return pts
    73: 
    74: 
    75: def clip_v(poly, lo, hi):
    76:     """The part of a polygon with lo <= v <= hi (Sutherland-Hodgman on two edges)."""
    77:     def cut(pts, keep, edge):
    78:         out = []
    79:         for i, a in enumerate(pts):
    80:             b = pts[(i + 1) % len(pts)]
    81:             ia, ib = keep(a), keep(b)
    82:             if ia:
    83:                 out.append(a)
    84:             if ia != ib:
    85:                 t = (edge - a[1]) / (b[1] - a[1])
    86:                 out.append((a[0] + (b[0] - a[0]) * t, edge))
    87:         return out
    88:     pts = cut(list(poly), lambda p: p[1] >= lo, lo)
    89:     return cut(pts, lambda p: p[1] <= hi, hi) if pts else []
    90: 
    91: 
    92: def clip_u(poly, lo, hi):
    93:     swap = [(v, u) for u, v in poly]
    94:     return [(u, v) for v, u in clip_v(swap, lo, hi)]
    95: 
    96: 
    97: class Plates:
    98:     """Collects one family's plates for a frame and writes them as solids on the joints."""
    99: 
    100:     def __init__(self, n, chamfer, roles=("main", "accent"), smooth=False):
    101:         """smooth: shade plates smooth with sharp rims, for families whose plates are curved."""
    102:         self.n, self.ch = n, chamfer
    103:         self.main, self.band_role = roles
    104:         self.smooth = smooth
    105: 
    106:     def _put(self, name, bm, role, jl, jr, bevel):
    107:         kw = dict(bevel=bevel, panels=False, smooth=self.smooth)
    108:         if jr is None:
    109:             return solid(f"{self.n}_{name}", bm, role, jl, **kw)
    110:         right = mirror_x(bm)
    111:         solid(f"{self.n}_{name}.L", bm, role, jl, **kw)
    112:         solid(f"{self.n}_{name}.R", right, role, jr, **kw)
    113: 
    114:     def plate(self, name, face, outline, t, jl, jr=None, band=None, recess=None, role=None, d0=0.0, lean=None):
    115:         """A slab of thickness t on a face, standing d0 off it. With band=(v0, v1) the slab is cut into
    116:         upper and lower pieces and a recessed band between them in the band role. `lean` (a matrix,
    117:         see shear) tilts the plate."""
    118:         role = role or self.main
    119:         slab = (lambda poly, a, b: face.slab(poly, a, b)) if lean is None else (lambda poly, a, b: transform(face.slab(poly, a, b), lean))
    120:         if band is None:
    121:             self._put(name, slab(outline, d0, d0 + t), role, jl, jr, self.ch)
    122:             return
    123:         recess = recess if recess is not None else max(.04, t * .35)
    124:         b0, b1 = band
    125:         lo, mid, hi = clip_v(outline, -1e3, b0), clip_v(outline, b0, b1), clip_v(outline, b1, 1e3)
    126:         pieces = [(f"{name}_lo", lo, role, t), (f"{name}_hi", hi, role, t), (f"{name}_band", mid, self.band_role, t - recess)]
    127:         for nm, poly, r, tt in pieces:
    128:             if len(poly) >= 3:
    129:                 self._put(nm, slab(poly, d0, d0 + tt), r, jl, jr, self.ch if r == role else self.ch * .5)
    130: 
    131:     def solid(self, name, bm, role, jl, jr=None, bevel=None):
    132:         self._put(name, bm, role, jl, jr, self.ch if bevel is None else bevel)
    133: 
    134:     def marks(self, name, face, d, blocks, jl, jr=None, role="stencil", lean=None):
    135:         """Stencil markings: flat blocks [(u0, v0, u1, v1), ...] standing 0.012 off depth d."""
    136:         bms = [face.slab([(u0, v0), (u1, v0), (u1, v1), (u0, v1)], d - .01, d + .012) for u0, v0, u1, v1 in blocks]
    137:         if lean is not None:
    138:             bms = [transform(b, lean) for b in bms]
    139:         self._put(name, merge(*bms), role, jl, jr, 0)
    140: 
    141: 
    142: def text_row(u0, v0, h, widths, gap=.05):
    143:     """A line of stencil text as blocks: one block per word, `widths` in metres."""
    144:     out, u = [], u0
    145:     for w in widths:
    146:         out.append((u, v0, u + w, v0 + h))
    147:         u += w + gap
    148:     return out
    149: 
    150: 
    151: def shear(axis, k, zref):
    152:     """A lean: x or y moves by k per metre of height above zref. Tilts a plate without bending it."""
    153:     m = Matrix.Identity(4)
    154:     i = {"x": 0, "y": 1}[axis]
    155:     m[i][2] = k
    156:     m[i][3] = -k * zref
    157:     return m
    158: 
    159: 
    160: def bearing(name, face, u, v, d, parent, size, lean=None):
    161:     """An insignia anchor on a plate face: the decal layer looks these up by name."""
    162:     at = face.at(u, v, d + .02)
    163:     if lean is not None:
    164:         at = lean @ at
    165:     return empty(f"bearing.{name}", at, parent, dir=gltf_dir(-face.w), size=size)
    166: 
    167: 
    168: def mirror_face(face):
    169:     """The same face on the right side."""
    170:     f = lambda p: Vector((-p.x, p.y, p.z))
    171:     out = Face(f(face.o), f(face.u), f(face.v), f(face.w))
    172:     return out
    173: 
    174: 
    175: # ---- shells: plates with a volume ------------------------------------------------------------------------
    176: # A shell is the intersection of a front outline (x, z) and a side outline (y, z), the two_view block.
    177: # Every plate is closed: a whole block, or with keep = the outward faces a thin plate on those faces
    178: # only, the block minus a copy of itself moved inward by the thickness. Directions: -x +x -y +y -z +z
    179: # (front is -y).
    180: 
    181: def inset(poly, d):
    182:     """A polygon moved inward by d along every edge (outward for d < 0), corners mitred."""
    183:     poly = ccw(list(poly))
    184:     n = len(poly)
    185:     lines = []
    186:     for i in range(n):
    187:         (x0, y0), (x1, y1) = poly[i], poly[(i + 1) % n]
    188:         ex, ey = x1 - x0, y1 - y0
    189:         L = (ex * ex + ey * ey) ** .5 or 1.0
    190:         nx, ny = -ey / L, ex / L  # left of the edge is inside for a CCW polygon
    191:         lines.append(((x0 + nx * d, y0 + ny * d), (ex, ey)))
    192:     out = []
    193:     for i in range(n):
    194:         (p, e), (q, f) = lines[i - 1], lines[i]
    195:         den = e[0] * f[1] - e[1] * f[0]
    196:         if abs(den) < 1e-9:
    197:             out.append(q)
    198:             continue
    199:         t = ((q[0] - p[0]) * f[1] - (q[1] - p[1]) * f[0]) / den
    200:         out.append((p[0] + e[0] * t, p[1] + e[1] * t))
    201:     return out
    202: 
    203: 
    204: def _bool(a, b, op):
    205:     me = bpy.data.meshes.new("_sh")
    206:     a.to_mesh(me)
    207:     a.free()
    208:     o = link(bpy.data.objects.new("_sh", me))
    209:     boolean(o, b, op)
    210:     out = bmesh.new()
    211:     out.from_mesh(o.data)
    212:     data = o.data
    213:     bpy.data.objects.remove(o, do_unlink=True)
    214:     bpy.data.meshes.remove(data)
    215:     return out
    216: 
    217: 
    218: def subtract(a, b):
    219:     """a minus b, both bmeshes (both are used up)."""
    220:     return _bool(a, b, "DIFFERENCE")
    221: 
    222: 
    223: DIRS = {"-x": (-1, 0, 0), "+x": (1, 0, 0), "-y": (0, -1, 0), "+y": (0, 1, 0), "-z": (0, 0, -1), "+z": (0, 0, 1)}
    224: 
    225: 
    226: def behind(front, side, t, keep, top=None):
    227:     """The block moved inward by t from the `keep` faces: what is taken away to leave a thin plate.
    228:     It is grown across the other axes, so its side walls never lie in the plate's own side walls:
    229:     coplanar walls leave the boolean stray slivers there."""
    230:     v = Vector((0, 0, 0))
    231:     for d in keep:
    232:         v -= Vector(DIRS[d])
    233:     axes = {d[1] for d in keep}
    234:     g = .3
    235:     f = front if axes & {"x", "z"} else inset(front, -g)
    236:     s = side if axes & {"y", "z"} else inset(side, -g)
    237:     tp = top if top is None or "z" in axes else inset(top, -g)
    238:     return transform(two_view(f, s, tp), Matrix.Translation(v * t))
    239: 
    240: 
    241: def plan(front, side, cf=.2, cb=.12):
    242:     """A plan outline (x, y) over a front and a side outline, its corners chamfered: cf at the front,
    243:     cb at the back. Takes the box out of a two_view block."""
    244:     xs, ys = [p[0] for p in front], [p[0] for p in side]
    245:     x0, x1, y0, y1 = min(xs) - .01, max(xs) + .01, min(ys) - .01, max(ys) + .01
    246:     return [(x0 + cf, y0), (x1 - cf, y0), (x1, y0 + cf), (x1, y1 - cb), (x1 - cb, y1), (x0 + cb, y1), (x0, y1 - cb), (x0, y0 + cf)]
    247: 
    248: 
    249: def shell(front, side, t=0.0, keep=None, top=None):
    250:     """A closed plate with a volume: the whole block, or a plate of thickness t on the keep faces."""
    251:     bm = two_view(front, side, top)
    252:     if keep is None:
    253:         return bm
    254:     return _bool(bm, behind(front, side, t, keep, top), "DIFFERENCE")
    255: 
    256: 
    257: def banded(front, side, t, keep, band, recess=.06, top=None):
    258:     """A shell cut across by a recessed service band between heights band = (z0, z1). Returns
    259:     (pieces in the main role, band piece)."""
    260:     z0, z1 = band
    261:     whole = shell(front, side, t, keep, top)
    262:     lo, hi = clip(copy(whole), z=(-60, z0)), clip(whole, z=(z1, 60))
    263:     b = two_view(inset(front, recess), inset(side, recess), inset(top, recess) if top is not None else None)
    264:     if keep is not None:
    265:         b = _bool(b, behind(front, side, t, keep, top), "DIFFERENCE")
    266:     return [p for p in (lo, hi) if len(p.faces) >= 4], clip(b, z=(z0, z1))
    267: 
    268: 
    269: 
    270: def inset_panel(front, side, t, keep, box, recess=.06, top=None, cut_back=.02):
    271:     """A shell with a recessed panel let into its front face: box = (x0, x1, z0, z1). Returns (the
    272:     shell with the opening, the panel set back by `recess`)."""
    273:     x0, x1, z0, z1 = box
    274:     y = max(surface(side, z, 0, -1)[0] for z in (z0, (z0 + z1) / 2, z1))
    275:     whole = shell(front, side, t, keep, top)
    276:     hole = two_view([(x0, z0), (x1, z0), (x1, z1), (x0, z1)], [(-60, z0), (y + t + cut_back, z0), (y + t + cut_back, z1), (-60, z1)])
    277:     main = subtract(whole, hole)
    278:     p = two_view(inset(front, recess), inset(side, recess), inset(top, recess) if top is not None else None)
    279:     p = clip(p, x=(x0, x1), y=(-60, y + t + cut_back), z=(z0, z1))
    280:     if keep is not None:
    281:         p = subtract(p, behind(front, side, t, keep, top))
    282:     return main, p
    283: 
    284: 
    285: def surface(poly, z, axis=0, sign=-1):
    286:     """Where an outline is outermost at height z: poly in (u, z), the extreme u toward sign, and the
    287:     slope du/dz of the edge there. For a side outline (y, z) and sign -1 that is the front face."""
    288:     best = None
    289:     n = len(poly)
    290:     for i in range(n):
    291:         (u0, z0), (u1, z1) = poly[i], poly[(i + 1) % n]
    292:         if min(z0, z1) <= z <= max(z0, z1) and z1 != z0:
    293:             k = (u1 - u0) / (z1 - z0)
    294:             u = u0 + k * (z - z0)
    295:             if best is None or u * sign > best[0] * sign:
    296:                 best = (u, k)
    297:     return best
  • 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/tools/shoot.mjs"}

    input

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

    result, 49 lines

    Showing lines 1-48 of 48
    1: // Screenshots of the running dev server for review.
    2: //   node tools/shoot.mjs out/dir name=/?view=striker name2=/?view=ship ...
    3: // Waits for window.__ready, then a few frames. Needs `npm run dev` on :5199.
    4: // SORTIE_GPU=1 uses the GPU (see below).
    5: import { chromium } from 'playwright';
    6: import { mkdirSync } from 'node:fs';
    7: import { join } from 'node:path';
    8: 
    9: const [out, ...shots] = process.argv.slice(2);
    10: const base = process.env.SORTIE_URL ?? 'http://localhost:5199';
    11: const W = Number(process.env.W ?? 1280), H = Number(process.env.H ?? 720);
    12: mkdirSync(out, { recursive: true });
    13: // SORTIE_GPU=1 renders on the GPU through a headed window on the WSLg display. WSLg ignores the
    14: // off-screen position, so the window shows on that machine's Windows desktop: on the workstation only
    15: // when nobody minds, on C1 (tools/c1-render.sh with C1_GPU=1) it shows on C1's own display.
    16: // Headless Chromium only gets SwiftShader, which is slow and loads the CPU.
    17: const gpu = process.env.SORTIE_GPU === '1';
    18: const browser = await chromium.launch(gpu
    19:   ? { headless: false, args: ['--use-angle=gl', '--ignore-gpu-blocklist', '--window-position=-4000,0'],
    20:       env: { ...process.env, DISPLAY: ':0', WAYLAND_DISPLAY: 'wayland-0', XDG_RUNTIME_DIR: '/mnt/wslg/runtime-dir',
    21:       // Mesa may fall back to llvmpipe unless told to use its D3D12 driver (C1's Radeon needs this)
    22:       GALLIUM_DRIVER: 'd3d12', LD_LIBRARY_PATH: '/usr/lib/wsl/lib' } }
    23:   : { args: ['--use-angle=swiftshader', '--enable-unsafe-swiftshader', '--ignore-gpu-blocklist'] });
    24: const page = await browser.newPage({ viewport: { width: W, height: H } });
    25: // SHOOT_TIMEOUT (ms) for page loads and screenshots: software rendering under load needs more than the default
    26: page.setDefaultTimeout(Number(process.env.SHOOT_TIMEOUT ?? 30000));
    27: let failed = 0;
    28: page.on('console', (m) => { if (m.type() === 'error' || m.type() === 'warning') console.log(`[${m.type()}]`, m.text().slice(0, 300)); });
    29: page.on('pageerror', (e) => console.log('[pageerror]', e.message));
    30: for (const s of shots) {
    31:   const i = s.indexOf('=');
    32:   const name = s.slice(0, i), url = s.slice(i + 1);
    33:   const t = Date.now();
    34:   // one slow or broken shot is reported and skipped, the rest of the batch still runs
    35:   try {
    36:     await page.goto(base + url);
    37:     await page.waitForFunction(() => window.__ready === true, null, { timeout: 300000 });
    38:     const frames = Number(new URL(base + url).searchParams.get('frames') ?? 1);
    39:     await page.evaluate((n) => new Promise((r) => { let k = 0; const f = () => (++k >= n ? r() : requestAnimationFrame(f)); requestAnimationFrame(f); }), frames);
    40:     await page.screenshot({ path: join(out, `${name}.png`) });
    41:     console.log(`${name}: ${Date.now() - t} ms`);
    42:   } catch (e) {
    43:     failed++;
    44:     console.log(`${name}: FAILED ${e.message.split('\n')[0]}`);
    45:   }
    46: }
    47: await browser.close();
    48: process.exitCode = failed ? 1 : 0;
  • 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