333 lines
17 KiB
Python
333 lines
17 KiB
Python
# Builds the ornaments inside the running Blender in the ornament_showcase.py style
|
|
# (bevelled per-pixel cubes, paint / gold metal / glowing gem materials, gold cap + smooth hook)
|
|
# and exports each one as a Roblox-ready .glb like export_roblox.py (one merged mesh + palette texture).
|
|
# Send with: python bl.py bl_build.py "NUMS=[208]; RENDER=True"
|
|
import bpy, bmesh, os, sys, random
|
|
from collections import deque
|
|
from mathutils import Matrix, Vector
|
|
|
|
ROOT = r"C:\Users\писикакич\Desktop\ornaments"
|
|
OUT = os.path.join(ROOT, "roblox_glb")
|
|
sys.path.insert(0, ROOT)
|
|
for _m in ('gen_ornaments', 'gen_designs', 'designs'): sys.modules.pop(_m, None)
|
|
import gen_designs as G, designs
|
|
ns = {"__name__": "showcase_lib"}
|
|
exec(open(os.path.join(ROOT, "ornament_showcase.py"), encoding="utf-8").read(), ns)
|
|
|
|
if not bpy.app.background:
|
|
raise SystemExit("Run in background: blender -b --factory-startup --python bl_build.py")
|
|
NUMS = [int(v) for v in os.environ['ORN_NUMS'].split(',')] if os.environ.get('ORN_NUMS') else sorted(designs.D)
|
|
RENDER = os.environ.get('ORN_RENDER') == '1'
|
|
SAVE = os.environ.get('ORN_SAVE')
|
|
GLOW, METAL = set('CEY'), set('Gg')
|
|
SCALE, TEX = 0.05, 64
|
|
|
|
def lin(v):
|
|
v /= 255
|
|
return v / 12.92 if v <= 0.04045 else ((v + 0.055) / 1.055) ** 2.4
|
|
|
|
def to_srgb(c):
|
|
return 12.92 * c if c <= 0.0031308 else 1.055 * (c ** (1 / 2.4)) - 0.055
|
|
|
|
def vivid(c, s_mul=1.35, v_mul=1.05):
|
|
import colorsys
|
|
h, s, v = colorsys.rgb_to_hsv(*(x / 255 for x in c))
|
|
return tuple(int(x * 255) for x in colorsys.hsv_to_rgb(h, min(1, s * s_mul), min(1, v * v_mul)))
|
|
|
|
def cells_for(num):
|
|
name, tpl, subs, *ovs = designs.D[num]
|
|
g = G.grid_of(tpl, subs, ovs); G.fix_floating(g)
|
|
S = set(g); dist, q = {}, deque()
|
|
for p in S:
|
|
if any((p[0] + a, p[1] + b) not in S for a, b in G.N4): dist[p] = 0; q.append(p)
|
|
while q:
|
|
p = q.popleft()
|
|
for a, b in G.N4:
|
|
n = (p[0] + a, p[1] + b)
|
|
if n in S and n not in dist: dist[n] = dist[p] + 1; q.append(n)
|
|
ys = [y for _, y in g]; xs = [x for x, _ in g]; top, ymax = min(ys), max(ys)
|
|
gx = sum(xs) / len(xs); cols = {}
|
|
for x, y in g: cols[x] = min(cols.get(x, 99), y)
|
|
cx = G.HOOKX if G.HOOKX in cols else min(cols, key=lambda x: (abs(x - gx) > 1.5, cols[x], abs(x - gx)))
|
|
span = max(max(xs) - min(xs), ymax - top) + 1; my = (top + ymax) / 2
|
|
random.seed(num); cells = {}
|
|
for (x, y), (ch, raised) in g.items():
|
|
d = min(3, 1 + dist[(x, y)])
|
|
kind = 'glow' if ch in GLOW else 'metal' if ch in METAL else 'paint'
|
|
if raised or kind != 'paint': d += 1 # details stand proud of the surface
|
|
base = vivid(G.sh(G.PAL[ch], 1 + 0.25 * ((cx - x) + (my - y)) / span))
|
|
for yy in range(-d, d + 1):
|
|
c = [lin(v) for v in base]
|
|
if yy > 0 and kind != 'glow': c = [v * 0.82 for v in c] # back a touch darker
|
|
if kind == 'paint' and (x + y) % 2: c = [v * 0.9 for v in c] # A/B pixel checker
|
|
cells[(x - cx, yy, ymax - y)] = (kind, ns['jit'](tuple(c)))
|
|
return f'{num:03d}_{name}', cells, ymax - cols[cx]
|
|
|
|
TILE = 16
|
|
FACE_LIGHT = {(2, 1): 1.15, (2, -1): 0.62, (1, -1): 1.0, (1, 1): 0.8, (0, 1): 0.86, (0, -1): 0.86}
|
|
|
|
def solid_object(name, cells, coll, loc, bevel=0.12):
|
|
"""Replaces showcase voxel_object: one welded shell (no gaps between cubes), per-face colour,
|
|
outer edges rounded by an angle-limited bevel."""
|
|
bm = bmesh.new(); col = bm.loops.layers.float_color.new("Col"); vc = {}
|
|
def vert(p):
|
|
k = tuple(round(v, 4) for v in p)
|
|
if k not in vc: vc[k] = bm.verts.new(k)
|
|
return vc[k]
|
|
kinds = ns['KINDS']
|
|
for (x, y, z), (kind, c) in cells.items():
|
|
for a in range(3):
|
|
for s in (-1, 1):
|
|
n = [x, y, z]; n[a] += s
|
|
if tuple(n) in cells: continue
|
|
o = [i for i in range(3) if i != a]; quad = []
|
|
for uu, vv in ((-.5, -.5), (.5, -.5), (.5, .5), (-.5, .5)):
|
|
p = [float(x), float(y), float(z)]; p[a] += .5 * s; p[o[0]] += uu; p[o[1]] += vv
|
|
quad.append(vert(p))
|
|
if s < 0: quad.reverse()
|
|
if a == 1: quad.reverse()
|
|
f = bm.faces.new(quad); f.material_index = kinds.index(kind)
|
|
for lp in f.loops: lp[col] = (*c, 1.0)
|
|
bmesh.ops.recalc_face_normals(bm, faces=list(bm.faces))
|
|
me = bpy.data.meshes.new(name); bm.to_mesh(me); bm.free()
|
|
for k in kinds: me.materials.append(ns['MATS'][k])
|
|
me.color_attributes.active_color_name = "Col"
|
|
ob = bpy.data.objects.new(name, me); ob.location = loc; coll.objects.link(ob)
|
|
bv = ob.modifiers.new("Bevel", "BEVEL")
|
|
bv.width, bv.segments, bv.limit_method, bv.angle_limit = bevel, 2, "ANGLE", 0.6
|
|
bv.harden_normals = True
|
|
return ob
|
|
|
|
ns['voxel_object'] = solid_object
|
|
|
|
def add_aura(num, g, cells, cx, ymax, top_z):
|
|
"""Rarity flair behind the silhouette: epic = glowing violet rim, legendary = gold rim + gems + rays."""
|
|
r = G.rarity(num)
|
|
if r not in ('epic', 'legendary'): return
|
|
S = set(g); out, q = {}, deque()
|
|
for p in S:
|
|
for a, b in G.N4:
|
|
n = (p[0] + a, p[1] + b)
|
|
if n not in S and n not in out: out[n] = 1; q.append(n)
|
|
while q:
|
|
p = q.popleft()
|
|
if out[p] >= 6: continue
|
|
for a, b in G.N4:
|
|
n = (p[0] + a, p[1] + b)
|
|
if n not in S and n not in out: out[n] = out[p] + 1; q.append(n)
|
|
xs = [x for x, _ in S]; ys = [y for _, y in S]
|
|
mx, my = (min(xs) + max(xs)) / 2, (min(ys) + max(ys)) / 2
|
|
import math
|
|
for (x, y), d in out.items():
|
|
X, Z = x - cx, ymax - y
|
|
if Z > top_z - 1 and abs(X) <= 3: continue # keep the cap / hook clear
|
|
vx, vy = x + .5 - mx, my - y - .5
|
|
k4 = (x + y) % 4 == 0
|
|
if r == 'epic':
|
|
if d > 1: continue
|
|
cell = ('glow', (1.0, 0.2, 0.8)) if k4 else ('paint', ns['jit'](ns['PUR_HI']))
|
|
else:
|
|
ray = any(vx * math.cos(a) + vy * math.sin(a) > 0 and abs(vx * math.sin(a) - vy * math.cos(a)) < 0.55
|
|
for a in (0, math.pi, -math.pi / 2))
|
|
if d == 1: cell = ('glow', ns['CYAN_GEM']) if k4 else ('metal', ns['jit'](ns['GOLD_A']))
|
|
elif ray and d <= 4: cell = ('glow', (1.0, 0.85, 0.3)) if d == 4 else ('metal', ns['jit'](ns['GOLD_HI']))
|
|
else: continue
|
|
for yy in (1, 2):
|
|
cells.setdefault((X, yy, Z), cell)
|
|
|
|
def _emit_mat(name, col, strength, metal=False):
|
|
m = bpy.data.materials.get(name)
|
|
if m: return m
|
|
m = bpy.data.materials.new(name); bs = m.node_tree.nodes.get("Principled BSDF")
|
|
bs.inputs["Base Color"].default_value = (*col, 1)
|
|
bs.inputs["Metallic"].default_value = 0.85 if metal else 0.0
|
|
bs.inputs["Roughness"].default_value = 0.2 if metal else 0.08
|
|
bs.inputs["Emission Color"].default_value = (*col, 1)
|
|
bs.inputs["Emission Strength"].default_value = strength
|
|
return m
|
|
|
|
def add_frame(num, name, cells, coll, loc):
|
|
"""Rarity flair readable from every angle: epic = slim violet-silver ring, legendary = gold ring + 4 glowing gems."""
|
|
import math
|
|
r = G.rarity(num)
|
|
if r not in ('epic', 'legendary'): return
|
|
leg = r == 'legendary'
|
|
xs = [k[0] for k in cells]; zs = [k[2] for k in cells]
|
|
cxr, cz = (min(xs) + max(xs)) / 2, (min(zs) + max(zs)) / 2
|
|
R = max(max(xs) - min(xs), max(zs) - min(zs)) / 2 + 2.0
|
|
tint = ns['GOLD_A'] if leg else (0.62, 0.5, 1.0)
|
|
mat = ns['MATS']['hook'] if leg else _emit_mat('Frame_Epic', tint, 0.25, metal=True)
|
|
c0 = Vector(loc) + Vector((cxr, 0, cz))
|
|
bpy.ops.mesh.primitive_torus_add(major_radius=R, minor_radius=0.55 if leg else 0.38, major_segments=64,
|
|
minor_segments=10, location=c0, rotation=(math.pi / 2, 0, 0))
|
|
objs = [bpy.context.active_object]; objs[0].data.materials.append(mat); objs[0]['tint'] = list(tint)
|
|
if leg:
|
|
gem = _emit_mat('Gem_Cyan', ns['CYAN_GEM'], 3.0)
|
|
for a in (45, 135, 225, 315):
|
|
p = c0 + Vector((R * math.cos(math.radians(a)), 0, R * math.sin(math.radians(a))))
|
|
bpy.ops.mesh.primitive_ico_sphere_add(radius=1.0, subdivisions=1, location=p)
|
|
o = bpy.context.active_object; o.data.materials.append(gem); o['tint'] = list(ns['CYAN_GEM']); objs.append(o)
|
|
for i, o in enumerate(objs):
|
|
o.name = f'{name}_Frame{i}'
|
|
for c in list(o.users_collection): c.objects.unlink(o)
|
|
coll.objects.link(o)
|
|
|
|
def merged_mesh(name, cells, hooks, loc):
|
|
"""export_roblox.py style mesh, but every voxel face maps to its own bevelled 'pixel cube' tile."""
|
|
tiles = {}
|
|
def tile(c, kind, light):
|
|
k = (tuple(round(v, 2) for v in c), kind, light)
|
|
if k not in tiles: tiles[k] = len(tiles)
|
|
return tiles[k]
|
|
bm = bmesh.new(); uv = bm.loops.layers.uv.new("UVMap"); vc = {}
|
|
def vert(p):
|
|
k = tuple(round(v, 4) for v in p)
|
|
if k not in vc: vc[k] = bm.verts.new(k)
|
|
return vc[k]
|
|
faces = []
|
|
for (x, y, z), (kind, c) in cells.items():
|
|
for a in range(3):
|
|
for s in (-1, 1):
|
|
n = [x, y, z]; n[a] += s
|
|
if tuple(n) in cells: continue
|
|
o = [i for i in range(3) if i != a]; quad = []; corners = []
|
|
for uu, vv in ((-.5, -.5), (.5, -.5), (.5, .5), (-.5, .5)):
|
|
p = [float(x), float(y), float(z)]; p[a] += .5 * s; p[o[0]] += uu; p[o[1]] += vv
|
|
quad.append(vert(p)); corners.append((uu + .5, vv + .5))
|
|
if s < 0: quad.reverse(); corners.reverse()
|
|
if a == 1: quad.reverse(); corners.reverse()
|
|
faces.append((bm.faces.new(quad), corners, tile(c, kind, FACE_LIGHT[(a, s)])))
|
|
gold = tile(ns['GOLD_A'], 'flat', 1.0)
|
|
for h in hooks:
|
|
if h.get('tint'): tile(tuple(h['tint']), 'flat', 1.0)
|
|
G_ = 1
|
|
while G_ * G_ < len(tiles): G_ *= 2
|
|
texs = G_ * TILE; pad = 1.5 / texs
|
|
def tuv(i, cu, cv):
|
|
u0, v0 = (i % G_) / G_, (i // G_) / G_
|
|
return u0 + pad + cu * (1 / G_ - 2 * pad), v0 + pad + cv * (1 / G_ - 2 * pad)
|
|
for f, corners, ti in faces:
|
|
for lp, (cu, cv) in zip(f.loops, corners): lp[uv].uv = tuv(ti, cu, cv)
|
|
gold_uv = tuv(gold, .5, .5)
|
|
bmesh.ops.recalc_face_normals(bm, faces=list(bm.faces))
|
|
dg = bpy.context.evaluated_depsgraph_get()
|
|
for h in hooks:
|
|
me = bpy.data.meshes.new_from_object(h.evaluated_get(dg))
|
|
me.transform(Matrix.Translation(-Vector(loc)) @ h.matrix_world)
|
|
if not me.uv_layers: me.uv_layers.new(name="UVMap")
|
|
huv = tuv(tile(tuple(h['tint']), 'flat', 1.0), .5, .5) if h.get('tint') else gold_uv
|
|
for d in me.uv_layers[0].data: d.uv = huv
|
|
bm.from_mesh(me); bpy.data.meshes.remove(me)
|
|
me = bpy.data.meshes.new(name + "_glb"); bm.to_mesh(me); bm.free()
|
|
me.transform(Matrix.Scale(SCALE, 4))
|
|
return me, (tiles, G_)
|
|
|
|
def tile_pixels(c, kind, light):
|
|
"""16x16 'bevelled pixel cube': dark seam, light top-left bevel, shaded bottom-right bevel."""
|
|
out = []
|
|
for py in range(TILE): # image rows go bottom -> top
|
|
for px_ in range(TILE):
|
|
e = min(px_, py, TILE - 1 - px_, TILE - 1 - py)
|
|
if kind == 'flat': f = 1.0
|
|
elif kind == 'glow': f = 1.35 if e > 3 else 1.15
|
|
elif e == 0: f = 0.72 # soft seam between pixels
|
|
elif e <= 2: f = 1.28 if (px_ < TILE / 2 and py > px_) or py >= TILE - 3 else 0.72
|
|
else: f = 1.0 + 0.06 * ((TILE - py) - px_) / TILE # soft gloss
|
|
f *= light if kind != 'glow' else 1.0
|
|
out += [min(1.0, to_srgb(min(1.0, v * f))) for v in c] + [1.0]
|
|
return out
|
|
|
|
def export_glb(sc, name, me, pal, folder):
|
|
tiles, G_ = pal; texs = G_ * TILE
|
|
img = bpy.data.images.new(name + "_Texture", texs, texs, alpha=False)
|
|
px = [0.0] * (texs * texs * 4)
|
|
for (c, kind, light), i in tiles.items():
|
|
tp = tile_pixels(c, kind, light); tx0, ty0 = (i % G_) * TILE, (i // G_) * TILE
|
|
for r in range(TILE):
|
|
o = ((ty0 + r) * texs + tx0) * 4
|
|
px[o:o + TILE * 4] = tp[r * TILE * 4:(r + 1) * TILE * 4]
|
|
img.pixels = px
|
|
m = BASE.copy(); m.name = name + "_Mat"
|
|
next(n for n in m.node_tree.nodes if n.type == "TEX_IMAGE").image = img
|
|
me.materials.append(m)
|
|
ob = bpy.data.objects.new(name, me); sc.collection.objects.link(ob)
|
|
bpy.ops.object.select_all(action="DESELECT")
|
|
ob.select_set(True); bpy.context.view_layer.objects.active = ob
|
|
path = os.path.join(folder, name + ".glb")
|
|
bpy.ops.export_scene.gltf(filepath=path, export_format="GLB", use_selection=True, export_apply=True, export_yup=True)
|
|
tris = sum(len(p.vertices) - 2 for p in me.polygons)
|
|
bpy.data.objects.remove(ob); bpy.data.meshes.remove(me); bpy.data.materials.remove(m); bpy.data.images.remove(img)
|
|
return tris, path
|
|
|
|
# ---------------------------------------------------------------- scene (fresh factory file in background)
|
|
sc = bpy.context.scene; sc.name = "Ornaments"
|
|
for o in list(bpy.data.objects): bpy.data.objects.remove(o, do_unlink=True)
|
|
def _coll(n):
|
|
c = sc.collection.children.get(n)
|
|
if not c: c = bpy.data.collections.new(n); sc.collection.children.link(c)
|
|
for o in list(c.objects): bpy.data.objects.remove(o, do_unlink=True)
|
|
return c
|
|
orn, studio = _coll("Ornaments"), _coll("Studio")
|
|
ns['GLOW_STRENGTH'] = 3.0 # half the showcase value: gems glow without blowing out the viewport
|
|
for k in ns["KINDS"]: ns["MATS"][k] = ns["attr_material"]("Ornament_" + k.capitalize(), k)
|
|
ns["MATS"]["hook"] = ns["plain_gold"]()
|
|
BASE = bpy.data.materials.get("Palette_Base")
|
|
if not BASE:
|
|
BASE = bpy.data.materials.new("Palette_Base")
|
|
nt = BASE.node_tree; nt.nodes.clear()
|
|
bs = nt.nodes.new("ShaderNodeBsdfPrincipled"); bs.inputs["Roughness"].default_value = 0.35
|
|
tx = nt.nodes.new("ShaderNodeTexImage"); tx.interpolation = "Closest"
|
|
nt.links.new(tx.outputs["Color"], bs.inputs["Base Color"])
|
|
nt.links.new(bs.outputs["BSDF"], nt.nodes.new("ShaderNodeOutputMaterial").inputs["Surface"])
|
|
|
|
PERFILE = not RENDER # normal run: one .blend per ornament (with studio light + camera, like the showcase)
|
|
if PERFILE:
|
|
ns['setup_studio'](sc, studio, [(0, 0)]); ns['setup_render'](sc, studio)
|
|
for o in list(studio.objects):
|
|
if o.name.startswith('Halo_'): bpy.data.objects.remove(o, do_unlink=True) # no grey wall in viewport
|
|
for scr in bpy.data.screens: # open in Material Preview so colours show right away
|
|
for a in scr.areas:
|
|
for s in a.spaces:
|
|
if s.type == 'VIEW_3D':
|
|
s.shading.type = 'RENDERED' # looks like the showcase render
|
|
s.region_3d.view_perspective = 'CAMERA'
|
|
positions = []
|
|
for i, num in enumerate(NUMS):
|
|
name, cells, top = cells_for(num)
|
|
loc = (0, 0, 0) if PERFILE else (((i % 10) - (min(len(NUMS), 10) - 1) / 2) * ns['SPACING'], 0, -(i // 10) * ns['ROW_GAP'])
|
|
before = set(orn.objects)
|
|
ns['finish'](name, cells, orn, loc, cx=0, top=top)
|
|
add_frame(num, name, cells, orn, loc)
|
|
hooks = [o for o in orn.objects if o not in before and o.name != name] # ring + hook curve
|
|
folder = os.path.join(OUT, G.rarity(num)); os.makedirs(folder, exist_ok=True)
|
|
me, pal = merged_mesh(name, cells, hooks, loc)
|
|
tris, gpath = export_glb(sc, name, me, pal, folder)
|
|
print(name, 'tris', tris, 'tiles', len(pal[0]))
|
|
if RENDER: # preview the Roblox .glb one row below its Blender version
|
|
before = set(bpy.data.objects)
|
|
bpy.ops.import_scene.gltf(filepath=gpath)
|
|
for o in set(bpy.data.objects) - before:
|
|
if o.parent is None:
|
|
o.scale = (1 / SCALE,) * 3; o.location = (loc[0], 0, loc[2] - ns['ROW_GAP'] + 3)
|
|
positions.append((loc[0], loc[2] - ns['ROW_GAP']))
|
|
if PERFILE:
|
|
bf = os.path.join(ROOT, 'blender', G.rarity(num)); os.makedirs(bf, exist_ok=True)
|
|
bpy.ops.wm.save_as_mainfile(filepath=os.path.join(bf, name + '.blend'), copy=True)
|
|
for o in list(orn.objects): bpy.data.objects.remove(o, do_unlink=True)
|
|
for dc in (bpy.data.meshes, bpy.data.curves):
|
|
for dblk in list(dc):
|
|
if dblk.users == 0: dc.remove(dblk)
|
|
else:
|
|
positions.append((loc[0], loc[2]))
|
|
|
|
if RENDER:
|
|
ns['setup_studio'](sc, studio, positions)
|
|
ns['setup_render'](sc, studio)
|
|
sc.render.resolution_x, sc.render.resolution_y = 1600, (1200 if len(positions) > 5 else 600)
|
|
sc.render.filepath = os.path.join(ROOT, "render_test.png")
|
|
bpy.ops.render.render(write_still=True)
|
|
print('render ->', sc.render.filepath)
|
|
if SAVE:
|
|
bpy.ops.wm.save_as_mainfile(filepath=os.path.join(ROOT, SAVE))
|
|
print('saved ->', SAVE)
|