Skip to content
1        10        20        30        40        50        60        70        80        90        1001"""Reusable procedural building blocks for Torment's authored heroine GLBs.23Each heroine script imports these helpers so bodies, faces, cloth, and weapons4are built from the same vocabulary and export through the same pipeline. Run a5heroine script under Blender, for example:67    blender -b --factory-startup -P tools/blender/finella.py -- \8      --out assets/models/finella.glb9"""1011import math1213import bmesh14import bpy15from mathutils import Vector161718def material(name, color, *, metallic=0.0, roughness=0.55, emission=None, emission_strength=0.0, alpha=1.0):19    mat = bpy.data.materials.new(name)20    mat.use_nodes = True21    bsdf = mat.node_tree.nodes["Principled BSDF"]22    bsdf.inputs["Base Color"].default_value = (*color, 1.0)23    bsdf.inputs["Metallic"].default_value = metallic24    bsdf.inputs["Roughness"].default_value = roughness25    if emission is not None:26        bsdf.inputs["Emission Color"].default_value = (*emission, 1.0)27        bsdf.inputs["Emission Strength"].default_value = emission_strength28    if alpha < 1.0:29        bsdf.inputs["Alpha"].default_value = alpha30        try:31            mat.blend_method = "BLEND"32        except Exception:  # Blender 5.2 renamed the property33            pass34        try:35            mat.surface_render_method = "BLENDED"36        except Exception:37            pass38    return mat394041def smooth(obj):42    for poly in obj.data.polygons:43        poly.use_smooth = True444546def sphere(name, location, radius, mat, *, scale=(1, 1, 1), segments=24, rings=16):47    bpy.ops.mesh.primitive_uv_sphere_add(48        segments=segments, ring_count=rings, radius=radius, location=location49    )50    obj = bpy.context.object51    obj.name = name52    obj.scale = scale53    bpy.ops.object.transform_apply(location=False, rotation=False, scale=True)54    obj.data.materials.append(mat)55    smooth(obj)56    return obj575859def cone(name, location, radius_bottom, radius_top, depth, mat, *, vertices=24, rotation=(0, 0, 0)):60    bpy.ops.mesh.primitive_cone_add(61        vertices=vertices,62        radius1=radius_bottom,63        radius2=radius_top,64        depth=depth,65        location=location,66        rotation=rotation,67    )68    obj = bpy.context.object69    obj.name = name70    obj.data.materials.append(mat)71    smooth(obj)72    return obj737475def box(name, location, size, mat, *, rotation=(0, 0, 0)):76    bpy.ops.mesh.primitive_cube_add(size=1, location=location, rotation=rotation)77    obj = bpy.context.object78    obj.name = name79    obj.scale = size80    bpy.ops.object.transform_apply(location=False, rotation=False, scale=True)81    obj.data.materials.append(mat)82    return obj838485def cylinder(name, location, radius, depth, mat, *, vertices=20):86    bpy.ops.mesh.primitive_cylinder_add(87        vertices=vertices, radius=radius, depth=depth, location=location88    )89    obj = bpy.context.object90    obj.name = name91    obj.data.materials.append(mat)92    smooth(obj)93    return obj949596def limb(name, start, end, radius_start, radius_end, mat, *, vertices=10):97    """A tapered capsule-ish limb running from start to end."""98    start = Vector(start)99    end = Vector(end)100    direction = end - start101    length = direction.length102    obj = cone(103        name,104        (start + end) / 2,105        radius_start,106        radius_end,107        length,108        mat,109        vertices=vertices,110    )111    obj.rotation_euler = direction.to_track_quat("Z", "Y").to_euler()112    return obj113114115def torus(name, location, major, minor, mat, *, rotation=(0, 0, 0), major_segments=40, minor_segments=8):116    bpy.ops.mesh.primitive_torus_add(117        major_radius=major,118        minor_radius=minor,119        major_segments=major_segments,120        minor_segments=minor_segments,121        location=location,122        rotation=rotation,123    )124    obj = bpy.context.object125    obj.name = name126    obj.data.materials.append(mat)127    smooth(obj)128    return obj129130131def mesh_object(name, verts, faces, mat, *, smooth_shading=True):132    mesh = bpy.data.meshes.new(name)133    mesh.from_pydata(verts, [], faces)134    mesh.update()135    bm = bmesh.new()136    bm.from_mesh(mesh)137    bmesh.ops.recalc_face_normals(bm, faces=bm.faces)138    bm.to_mesh(mesh)139    bm.free()140    obj = bpy.data.objects.new(name, mesh)141    bpy.context.collection.objects.link(obj)142    obj.data.materials.append(mat)143    if smooth_shading:144        smooth(obj)145    return obj146147148def tube(name, points, radii, mat, *, sides=8):149    """A smooth tapered tube through a polyline, used for hair and water."""150    pts = [Vector(point) for point in points]151    verts = []152    faces = []153    for index, point in enumerate(pts):154        if index == 0:155            tangent = pts[1] - pts[0]156        elif index == len(pts) - 1:157            tangent = pts[-1] - pts[-2]158        else:159            tangent = pts[index + 1] - pts[index - 1]160        rotation = tangent.normalized().to_track_quat("Z", "Y")161        for side in range(sides):162            angle = 2 * math.pi * side / sides163            offset = rotation @ Vector(164                (math.cos(angle) * radii[index], math.sin(angle) * radii[index], 0)165            )166            verts.append(tuple(point + offset))167    for ring in range(len(pts) - 1):168        for side in range(sides):169            a = ring * sides + side170            b = ring * sides + (side + 1) % sides171            c = (ring + 1) * sides + (side + 1) % sides172            d = (ring + 1) * sides + side173            faces.append((a, b, c, d))174    start = len(verts)175    verts.append(tuple(pts[0]))176    for side in range(sides):177        faces.append((start, (side + 1) % sides, side))178    end = len(verts)179    verts.append(tuple(pts[-1]))180    base = (len(pts) - 1) * sides181    for side in range(sides):182        faces.append((end, base + side, base + (side + 1) % sides))183    return mesh_object(name, verts, faces, mat)184185186def group(parts, name):187    """Parent every part under one empty root the game can clone and scale."""188    root = bpy.data.objects.new(name, None)189    bpy.context.collection.objects.link(root)190    for part in parts:191        part.parent = root192    return root193194195def revolve(name, profile, mat, *, cols=48, y_scale=1.0, ripple=0.0, wave=0.0, thickness=0.012):196    """A smooth surface of revolution around Z, with optional water ripples."""197    rows = len(profile)198    verts = []199    faces = []200    for row, (z, radius) in enumerate(profile):201        for col in range(cols):202            angle = 2 * math.pi * col / cols203            scaled = radius * (1 + ripple * math.sin(angle * 6 + row * 0.22))204            verts.append(205                (206                    math.cos(angle) * scaled,207                    math.sin(angle) * scaled * y_scale,208                    z + wave * math.sin(angle * 6 + 0.7) * (row / (rows - 1)) ** 2,209                )210            )211    for row in range(rows - 1):212        for col in range(cols):213            a = row * cols + col214            b = row * cols + (col + 1) % cols215            c = (row + 1) * cols + (col + 1) % cols216            d = (row + 1) * cols + col217            faces.append((a, b, c, d))218    obj = mesh_object(name, verts, faces, mat)219    if thickness:220        solidify = obj.modifiers.new(f"{name} Thickness", "SOLIDIFY")221        solidify.thickness = thickness222        solidify.offset = 0.0223    return obj224225226def subdivide(obj, levels=1):227    """Round an organic primitive with Catmull-Clark; applied on export."""228    mod = obj.modifiers.new(f"{obj.name} Subdivision", "SUBSURF")229    mod.levels = levels230    mod.render_levels = levels231    return obj232233234def sculpted_head(name, center, radii, mat, *, jaw=0.22, cheek=0.012, brow=0.01, chin=0.018,235                  theta_max=math.pi, edge=None, ripple=0.0, rings=22, sides=36):236    """A head shaped by an ellipsoid with a tapered jaw, cheekbones, brow and chin.237238    The crown is always closed. `theta_max` below pi leaves the lower edge open,239    which is how the hair shell and hood are built to sit over the head. `edge`240    may be a function of the azimuth `phi` that returns the lower limit for that241    column, so the opening can rise over the forehead and fall at the nape.242    """243    rx, ry, rz = radii244    cx, cy, cz = center245    closed = theta_max >= math.pi - 1e-6 and edge is None246    limit = edge or (lambda phi: theta_max)247    lat_end = rings if closed else rings + 1248    verts = [(cx, cy, cz + rz)]  # crown pole, index 0249    for i in range(1, lat_end):250        for j in range(sides):251            phi = 2 * math.pi * j / sides252            theta = limit(phi) * i / rings253            t = math.cos(theta)254            s_theta = math.sin(theta)255            sn = min(1.0, max(0.0, (0.1 - t) / 1.1))256            width = 1.0 - jaw * sn ** 1.6257            cos_p = math.cos(phi)258            sin_p = math.sin(phi)259            # Cloth folds: vertical creases that fade toward the crown.260            fold = 1 + ripple * math.sin(9 * phi + 2 * theta) * (1 - t * t * 0.5)261            x_ext = (width + cheek * math.exp(-((t + 0.02) / 0.32) ** 2)) * fold262            x = rx * s_theta * cos_p * x_ext263            y = ry * s_theta * sin_p * fold264            if sin_p < 0:265                front = -sin_p266                y -= brow * math.exp(-((t - 0.28) / 0.13) ** 2) * front * front267                y -= chin * math.exp(-((t + 0.78) / 0.22) ** 2) * front * front268            verts.append((cx + x, cy + y, cz + rz * t))269    rings_built = lat_end - 1270    faces = []271    for j in range(sides):272        faces.append((0, 1 + (j + 1) % sides, 1 + j))273    for ring in range(rings_built - 1):274        for j in range(sides):275            a = 1 + ring * sides + j276            b = 1 + ring * sides + (j + 1) % sides277            faces.append((a, b, b + sides, a + sides))278    if closed:279        bottom = len(verts)280        verts.append((cx, cy, cz - rz))281        base = 1 + (rings_built - 1) * sides282        for j in range(sides):283            faces.append((bottom, base + j, base + (j + 1) % sides))284    return mesh_object(name, verts, faces, mat)285286287def capsule(name, start, end, radius_start, radius_end, mat, *, sides=14, rings=8, bulge=0.0, bulge_at=0.35):288    """A tapered limb with hemispherical ends and an optional muscle bulge.289290    Unlike `limb`, the ends are closed by rounded caps rather than flat cones, so a291    later Catmull-Clark pass or a bent joint does not pinch them.292    """293    start = Vector(start)294    end = Vector(end)295    direction = end - start296    length = direction.length297    d = direction.normalized()298    helper = Vector((0, 0, 1)) if abs(d.z) < 0.9 else Vector((1, 0, 0))299    u = d.cross(helper).normalized()300    v = d.cross(u).normalized()301302    # Stations along the axis: (position, radius, is_pole). Caps use a quarter circle.303    stations = []304    cap = 4305    for k in range(cap, 0, -1):306        a = (math.pi / 2) * k / cap307        stations.append((-radius_start * math.sin(a), radius_start * math.cos(a), k == cap))308    for r in range(rings + 1):309        t = r / rings310        bump = 1 + bulge * math.exp(-((t - bulge_at) / 0.28) ** 2)311        stations.append((length * t, (radius_start + (radius_end - radius_start) * t) * bump, False))312    for k in range(1, cap + 1):313        a = (math.pi / 2) * k / cap314        stations.append((length + radius_end * math.sin(a), radius_end * math.cos(a), k == cap))315316    verts = []317    rings_idx = []318    for pos, radius, pole in stations:319        center = start + d * pos320        if pole or radius < 1e-6:321            rings_idx.append([len(verts)])322            verts.append(tuple(center))323            continue324        indices = []325        for side in range(sides):326            angle = 2 * math.pi * side / sides327            offset = (u * math.cos(angle) + v * math.sin(angle)) * radius328            indices.append(len(verts))329            verts.append(tuple(center + offset))330        rings_idx.append(indices)331332    faces = []333    for ring in range(len(rings_idx) - 1):334        a_ring = rings_idx[ring]335        b_ring = rings_idx[ring + 1]336        if len(a_ring) == 1 and len(b_ring) == 1:337            continue338        if len(a_ring) == 1:339            pole = a_ring[0]340            for side in range(sides):341                faces.append((pole, b_ring[side], b_ring[(side + 1) % sides]))342        elif len(b_ring) == 1:343            pole = b_ring[0]344            for side in range(sides):345                faces.append((pole, a_ring[(side + 1) % sides], a_ring[side]))346        else:347            for side in range(sides):348                nxt = (side + 1) % sides349                faces.append((a_ring[side], a_ring[nxt], b_ring[nxt], b_ring[side]))350    return mesh_object(name, verts, faces, mat)