cntrl/tools/blender/actor_kit.py

328 lines
11 KiB
Python

# tools/blender/actor_kit.py
# FBC: NIGHT SHIFT — procedural sculpted-actor kit (S10).
#
# Replaces the old box/chamfer kit with lofts, swept tubes, deformed masses and
# crystal growths: RoR2 chunky-but-polished silhouettes in Control's palette.
# Every part is painted into one COLOR_0 vertex-colour attribute so the merged
# GLB still draws in a single call with the game's actor shader.
import math
import random
import bpy
from mathutils import Euler, Vector
def srgb_to_linear(c):
return c / 12.92 if c <= 0.04045 else ((c + 0.055) / 1.055) ** 2.4
def rgb(hexstr):
h = hexstr.lstrip("#")
return tuple(srgb_to_linear(int(h[i:i + 2], 16) / 255.0) for i in (0, 2, 4))
PALETTE = {
"concrete": "#2b2b2f", "paper": "#e8e4d8", "redaction": "#26272c",
"hiss": "#c1121f", "hiss_hot": "#ff3b46", "hiss_dull": "#8e1a24",
"board": "#f5c518", "teal": "#4ec9b0", "navy": "#3b4a5e",
"navy_lt": "#5c7086", "navy_dk": "#28313e", "tan": "#c8b99b",
"skin": "#e0cdb0", "steel": "#8a96a1", "steel_dk": "#5d6873",
"mold": "#556b4e", "mold_dk": "#374636", "mold_glow": "#78906b",
}
def color(value):
return rgb(value) if isinstance(value, str) else tuple(value)
def actor_material():
"""One shared material: COLOR_0 drives the base colour, as before."""
mat = bpy.data.materials.get("actor") or bpy.data.materials.new("actor")
mat.use_nodes = True
nodes = mat.node_tree.nodes
bsdf = next(n for n in nodes if n.type == "BSDF_PRINCIPLED")
if not any(n.type == "ATTRIBUTE" and n.attribute_name == "Color"
for n in nodes):
attr = nodes.new("ShaderNodeAttribute")
attr.attribute_name = "Color"
mat.node_tree.links.new(attr.outputs["Color"], bsdf.inputs["Base Color"])
return mat
MAT = None
ROOTS = []
def new_actor(name):
global MAT
if MAT is None:
MAT = actor_material()
root = bpy.data.objects.new(name, None)
bpy.context.scene.collection.objects.link(root)
ROOTS.append(root)
return root
def _mesh(root, name, verts, faces, material=None, smooth=False):
mesh = bpy.data.meshes.new(name + "_mesh")
mesh.from_pydata(verts, [], faces)
mesh.validate()
mesh.update()
obj = bpy.data.objects.new(name, mesh)
bpy.context.scene.collection.objects.link(obj)
obj.data.materials.append(material or MAT)
for poly in obj.data.polygons:
poly.use_smooth = smooth
obj.parent = root
return obj
def paint(obj, value, ao=0.12, z_bias=0.0):
"""Bake linear RGB into COLOR_0, with cheap painted AO toward the feet."""
col = color(value)
zs = [v.co.z for v in obj.data.vertices]
lo, hi = min(zs), max(zs)
span = max(hi - lo, 1e-5)
attr = obj.data.color_attributes.new(name="Color", type="FLOAT_COLOR",
domain="POINT")
for i, v in enumerate(obj.data.vertices):
t = (v.co.z - lo) / span
shade = 1.0 - ao * (1.0 - t) ** 2
if z_bias > 0.0 and t > 0.7:
shade *= 1.0 + z_bias * (t - 0.7)
attr.data[i].color = (col[0] * shade, col[1] * shade, col[2] * shade,
1.0)
return obj
def loft(root, name, rings, value, smooth=False, ao=0.12, twist=0.0,
z_bias=0.0):
"""Sculpt a tapered, optionally folded body from a stack of cross-sections.
ring = {"z": float, "r": (rx, ry), "n": int,
"c": (x, y) optional, "phase": float optional,
"fold": (amplitude, frequency) optional, "cap": bool optional}
"""
verts, faces, offsets = [], [], []
for ring in rings:
n = ring["n"]
cx, cy = ring.get("c", (0.0, 0.0))
rx, ry = ring["r"]
z = ring["z"]
phase = ring.get("phase", 0.0)
fold = ring.get("fold", (0.0, 0.0))
start = len(verts)
offsets.append((start, n))
for j in range(n):
a = 2.0 * math.pi * j / n + phase + twist * z
m = 1.0 + fold[0] * math.sin(fold[1] * a + z * 4.0)
verts.append((cx + rx * m * math.cos(a),
cy + ry * m * math.sin(a), z))
for i in range(len(rings) - 1):
s0, n0 = offsets[i]
s1, n1 = offsets[i + 1]
if n0 != n1:
raise ValueError("loft %s: ring side counts differ" % name)
for j in range(n0):
k = (j + 1) % n0
faces.append((s0 + j, s0 + k, s1 + k, s1 + j))
for index, forward in ((0, False), (-1, True)):
ring = rings[index]
if not ring.get("cap", True):
continue
s, n = offsets[index]
cx, cy = ring.get("c", (0.0, 0.0))
c = len(verts)
verts.append((cx, cy, ring["z"]))
for j in range(n):
k = (j + 1) % n
faces.append((c, s + j, s + k) if forward
else (c, s + k, s + j))
return paint(_mesh(root, name, verts, faces, smooth=smooth), value, ao,
z_bias)
def tube(root, name, points, radii, value, sides=7, smooth=False, ao=0.1):
"""Sweep a tapered tube along a polyline (tendrils, fingers, cables)."""
pts = [Vector(p) for p in points]
if len(pts) != len(radii):
raise ValueError("tube %s: point/radius mismatch" % name)
verts, faces, offsets = [], [], []
for i, p in enumerate(pts):
if i == 0:
tangent = (pts[1] - pts[0]).normalized()
elif i == len(pts) - 1:
tangent = (pts[-1] - pts[-2]).normalized()
else:
tangent = (pts[i + 1] - pts[i - 1]).normalized()
up = Vector((0.0, 0.0, 1.0))
if abs(tangent.dot(up)) > 0.9:
up = Vector((0.0, 1.0, 0.0))
normal = tangent.cross(up).normalized()
binormal = tangent.cross(normal).normalized()
start = len(verts)
offsets.append(start)
for j in range(sides):
a = 2.0 * math.pi * j / sides
q = p + (normal * math.cos(a) + binormal * math.sin(a)) * radii[i]
verts.append(tuple(q))
for i in range(len(pts) - 1):
s0, s1 = offsets[i], offsets[i + 1]
for j in range(sides):
k = (j + 1) % sides
faces.append((s0 + j, s0 + k, s1 + k, s1 + j))
c0 = len(verts)
verts.append(tuple(pts[0]))
c1 = len(verts)
verts.append(tuple(pts[-1]))
for j in range(sides):
k = (j + 1) % sides
faces.append((c0, offsets[0] + k, offsets[0] + j))
faces.append((c1, offsets[-1] + j, offsets[-1] + k))
return paint(_mesh(root, name, verts, faces, smooth=smooth), value, ao)
def blob(root, name, center, scale, value, subdiv=1, warp=0.14, seed=0,
smooth=True, ao=0.06):
"""Deformed icosphere: organic muscle, mold lobes, cloth masses."""
bpy.ops.mesh.primitive_ico_sphere_add(subdivisions=subdiv, radius=1.0,
location=center)
obj = bpy.context.object
obj.name = name
phase = random.Random(seed).uniform(0.0, 6.283)
for v in obj.data.vertices:
p = v.co
n = (math.sin(p.x * 5.1 + phase) * math.cos(p.y * 4.3 - phase)
* math.sin(p.z * 3.7 + phase * 0.5))
f = 1.0 + warp * n
v.co = (p.x * f * scale[0], p.y * f * scale[1],
p.z * f * scale[2])
bpy.ops.object.transform_apply(location=True, rotation=True, scale=True)
obj.data.materials.append(MAT)
for poly in obj.data.polygons:
poly.use_smooth = smooth
obj.parent = root
return paint(obj, value, ao)
def crystal(root, name, center, size, value, sides=5, seed=0, tilt=(0, 0, 0),
ao=0.0):
"""Irregular bipyramid — Hiss / Board growths with cheap faceted glints."""
rng = random.Random(seed)
verts = [(0.0, 0.0, -size * 0.45)]
for j in range(sides):
a = 2.0 * math.pi * j / sides
r = size * rng.uniform(0.42, 0.62)
verts.append((r * math.cos(a), r * math.sin(a),
size * rng.uniform(0.30, 0.52)))
verts.append((size * rng.uniform(-0.12, 0.12),
size * rng.uniform(-0.12, 0.12), size))
faces = []
top = len(verts) - 1
for j in range(sides):
k = (j + 1) % sides
faces.append((0, 1 + k, 1 + j))
faces.append((top, 1 + j, 1 + k))
rot = Euler(tilt).to_matrix()
c = Vector(center)
verts = [tuple(c + rot @ Vector(v)) for v in verts]
return paint(_mesh(root, name, verts, faces), value, ao)
def plate(root, name, outline, z0, z1, taper, value, shift=(0.0, 0.0),
ao=0.06):
"""Tapered extruded polygon: angular armour that still catches the key."""
if len(shift) == 3:
ox, oy, dz = shift
z0, z1 = z0 + dz, z1 + dz
else:
ox, oy = shift
verts = [(x + ox, y + oy, z0) for x, y in outline]
verts += [(x * taper + ox, y * taper + oy, z1) for x, y in outline]
n = len(outline)
faces = []
for j in range(n):
k = (j + 1) % n
faces.append((j, k, n + k, n + j))
cb, ct = len(verts), len(verts) + 1
verts.append((ox, oy, z0))
verts.append((ox, oy, z1))
for j in range(n):
k = (j + 1) % n
faces.append((cb, k, j))
faces.append((ct, n + j, n + k))
return paint(_mesh(root, name, verts, faces), value, ao)
def ring(root, name, center, radius, thickness, value, segments=14):
bpy.ops.mesh.primitive_torus_add(major_segments=segments,
minor_segments=4, location=center,
major_radius=radius,
minor_radius=thickness)
obj = bpy.context.object
obj.name = name
bpy.ops.object.transform_apply(location=True, rotation=True, scale=True)
obj.data.materials.append(MAT)
for poly in obj.data.polygons:
poly.use_smooth = False
obj.parent = root
return paint(obj, value, 0.0)
def octagon(rx, ry=0.0):
ry = ry or rx
return [(rx * math.cos(math.pi * (0.25 + j / 4.0)),
ry * math.sin(math.pi * (0.25 + j / 4.0))) for j in range(8)]
def merge_actor(root, name):
meshes = [o for o in root.children if o.type == "MESH"]
if len(meshes) < 2:
return meshes[0] if meshes else None
bpy.ops.object.select_all(action="DESELECT")
for o in meshes:
o.select_set(True)
bpy.context.view_layer.objects.active = meshes[0]
bpy.ops.object.join()
joined = bpy.context.object
joined.name = name + "_mesh"
joined.parent = root
return joined
def triangle_count(root):
return sum(len(p.vertices) - 2 for o in root.children_recursive
if o.type == "MESH" for p in o.data.polygons)
def export_actor(root, name, path):
bpy.ops.object.select_all(action="DESELECT")
root.select_set(True)
for child in root.children_recursive:
child.select_set(True)
bpy.context.view_layer.objects.active = root
bpy.ops.export_scene.gltf(
filepath=path,
export_format="GLB",
use_selection=True,
export_apply=True,
export_yup=True,
export_materials="EXPORT",
export_cameras=False,
export_lights=False,
export_extras=False,
)
def clear_scene():
for obj in list(bpy.data.objects):
bpy.data.objects.remove(obj, do_unlink=True)
for datablocks in (bpy.data.meshes, bpy.data.materials, bpy.data.curves,
bpy.data.cameras, bpy.data.lights):
for block in list(datablocks):
if block.users == 0:
datablocks.remove(block)
global MAT, ROOTS
MAT = None
ROOTS = []