147 lines
8.3 KiB
Python
147 lines
8.3 KiB
Python
"""Export the approved Blender scenes to static Dice-Box d6 themes.
|
|
|
|
Run with bun run build:cosmic; BLENDER_EXECUTABLE can override the executable.
|
|
MCP: set COSMIC_REPO and exec this file. No authoring objects are modified.
|
|
Evaluated modifiers, corner colors and packed disk images become portable assets.
|
|
"""
|
|
import argparse
|
|
import json
|
|
import struct
|
|
import sys
|
|
import zlib
|
|
from pathlib import Path
|
|
|
|
import bpy
|
|
|
|
|
|
def png(path, width, height, rows):
|
|
def chunk(kind, data):
|
|
body = kind + data
|
|
return struct.pack('>I', len(data)) + body + struct.pack('>I', zlib.crc32(body))
|
|
path.write_bytes(b'\x89PNG\r\n\x1a\n' +
|
|
chunk(b'IHDR', struct.pack('>IIBBBBB', width, height, 8, 2, 0, 0, 0)) +
|
|
chunk(b'IDAT', zlib.compress(b''.join(b'\0' + row for row in rows), 9)) +
|
|
chunk(b'IEND', b''))
|
|
|
|
|
|
def srgb_byte(value):
|
|
value = max(0, min(1, value))
|
|
encoded = 12.92 * value if value <= 0.0031308 else 1.055 * value ** (1 / 2.4) - 0.055
|
|
return round(encoded * 255)
|
|
|
|
|
|
def export(repo):
|
|
original = json.loads((repo / 'node_modules/@3d-dice/dice-box/dist/assets/themes/default/default.json').read_text())
|
|
collider = next(m for m in original['meshes'] if m['name'] == 'd6_collider')
|
|
base = next(m for m in original['meshes'] if m['name'] == 'd6')
|
|
transform = {k: base[k] for k in ('position', 'rotationQuaternion', 'scaling')}
|
|
previous_scene = bpy.context.window.scene
|
|
report = []
|
|
try:
|
|
for level, theme in [('Low', 'cosmicBlackHoleLow'), ('Medium', 'cosmicBlackHoleMedium'), ('High', 'cosmicBlackHole')]:
|
|
scene = bpy.data.scenes['Cosmic Review - ' + level]
|
|
physics = json.loads(bpy.data.texts[scene['physics_text']].as_string())
|
|
if physics['collider'] != collider or physics['colliderFaceMap']['d6'] != original['colliderFaceMap']['d6'] or physics['render_transform'] != transform:
|
|
raise ValueError('Blender physics reference differs from installed Dice-Box d6')
|
|
scale = scene['dice_box_metres_per_unit']
|
|
parts = sorted((o for o in scene.objects if o.get('dice_box_export')), key=lambda o: (o['export_order'], o.name))
|
|
for kind, expected in [('star', 21), ('outline', 21), ('core', 1), ('disk', 1)]:
|
|
if sum(o.get('part_type') == kind for o in parts) != expected:
|
|
raise ValueError(f'{level}: expected {expected} {kind} objects')
|
|
bpy.context.window.scene = scene
|
|
graph = bpy.context.evaluated_depsgraph_get()
|
|
graph.update()
|
|
mesh = {'name': 'd6', 'id': 'd6', **transform, 'isVisible': True, 'isEnabled': True,
|
|
'pickable': False, 'positions': [], 'normals': [], 'uvs': [], 'colors': [], 'indices': []}
|
|
manifest = []
|
|
textured = 'packed_disk_image' in scene
|
|
for obj in parts:
|
|
evaluated = obj.evaluated_get(graph)
|
|
data = evaluated.to_mesh(preserve_all_data_layers=True, depsgraph=graph)
|
|
try:
|
|
data.calc_loop_triangles()
|
|
colors = data.color_attributes.get('CosmosColor')
|
|
if not colors or colors.domain != 'CORNER':
|
|
raise ValueError('Missing CORNER CosmosColor: ' + obj.name)
|
|
uv = data.uv_layers.get('AccretionUV')
|
|
kind = obj['part_type']
|
|
if kind == 'disk' and textured and not uv:
|
|
raise ValueError('Missing AccretionUV: ' + obj.name)
|
|
# Root placement is for review; child transforms are exported.
|
|
matrix = obj.parent.matrix_world.inverted() @ evaluated.matrix_world
|
|
normal_matrix = matrix.to_3x3().inverted().transposed()
|
|
first = len(mesh['indices'])
|
|
for triangle in data.loop_triangles:
|
|
for loop_id in triangle.loops:
|
|
loop = data.loops[loop_id]
|
|
p = matrix @ data.vertices[loop.vertex_index].co
|
|
n = (normal_matrix @ data.corner_normals[loop_id].vector).normalized()
|
|
# Blender RH Z-up -> Babylon LH Y-up reflection.
|
|
mesh['indices'].append(len(mesh['positions']) // 3)
|
|
mesh['positions'].extend(round(float(v / scale), 7) for v in (p.x, p.z, p.y))
|
|
mesh['normals'].extend(round(float(v), 7) for v in (n.x, n.z, n.y))
|
|
color = list(colors.data[loop_id].color)
|
|
coords = (0.02, 0.02) if textured else (0.5, 0.5)
|
|
if kind in ('core', 'outline'):
|
|
color = [0, 0, 0, 1]
|
|
elif kind == 'disk' and textured:
|
|
color = [1, 1, 1, 1]
|
|
coords = uv.data[loop_id].uv
|
|
elif kind == 'trail':
|
|
color = [v * 0.43 for v in color[:3]] + [1]
|
|
mesh['colors'].extend(round(float(v), 7) for v in color)
|
|
mesh['uvs'].extend(round(float(v), 7) for v in coords)
|
|
manifest.append({'name': obj.name, 'kind': kind, 'indexStart': first,
|
|
'indexCount': len(mesh['indices']) - first})
|
|
finally:
|
|
evaluated.to_mesh_clear()
|
|
output = repo / 'assets/dice-themes' / theme
|
|
output.mkdir(parents=True, exist_ok=True)
|
|
size = 2
|
|
if textured:
|
|
image = bpy.data.images[scene['packed_disk_image']]
|
|
if not image.packed_file or image.size[0] != image.size[1]:
|
|
raise ValueError('A packed square disk texture is required')
|
|
size = image.size[0]
|
|
pixels = list(image.pixels)
|
|
rows = []
|
|
# PNG top-down rows; Blender image pixels and UVs are bottom-up.
|
|
# Untextured parts sample a white corner outside the disk.
|
|
for y in reversed(range(size)):
|
|
row = bytearray()
|
|
for x in range(size):
|
|
rgb = [255, 255, 255] if x < size // 16 and y < size // 16 else [
|
|
srgb_byte(pixels[(y * size + x) * 4 + c]) for c in range(3)]
|
|
row.extend(rgb)
|
|
rows.append(bytes(row))
|
|
png(output / 'diffuse.png', size, size, rows)
|
|
else:
|
|
png(output / 'diffuse.png', 2, 2, [bytes([255] * 6)] * 2)
|
|
png(output / 'specular.png', 2, 2, [bytes(6)] * 2)
|
|
model = {'producer': {'name': 'Blender cosmic theme exporter', 'version': '2', 'file': 'cosmic-black-hole.json'},
|
|
'meshes': [mesh, collider], 'colliderFaceMap': {'d6': original['colliderFaceMap']['d6']}}
|
|
config = {'name': 'Cosmic Black Hole - ' + level, 'systemName': theme, 'author': '21', 'version': 2,
|
|
'meshFile': 'cosmic-black-hole.json', 'diceAvailable': ['d6'],
|
|
'material': {'type': 'standard', 'diffuseTexture': 'diffuse.png', 'diffuseLevel': 1.65,
|
|
'specularTexture': 'specular.png'}}
|
|
(output / 'cosmic-black-hole.json').write_text(json.dumps(model, separators=(',', ':')) + '\n', encoding='utf-8')
|
|
(output / 'theme.config.json').write_text(json.dumps(config, indent=2) + '\n', encoding='utf-8')
|
|
(output / 'LICENSE.txt').write_bytes((repo / 'assets/dice-themes/cosmicBlackHole/LICENSE.txt').read_bytes())
|
|
entry = {'quality': level.lower(), 'theme': theme, 'triangles': len(mesh['indices']) // 3,
|
|
'textureSize': size, 'parts': manifest}
|
|
(output / 'export-manifest.json').write_text(json.dumps(entry, indent=2) + '\n', encoding='utf-8')
|
|
report.append({k: v for k, v in entry.items() if k != 'parts'})
|
|
finally:
|
|
bpy.context.window.scene = previous_scene
|
|
return {'exported': report, 'physics_unchanged': True}
|
|
|
|
|
|
if 'COSMIC_REPO' in globals():
|
|
result = export(Path(COSMIC_REPO))
|
|
else:
|
|
parser = argparse.ArgumentParser()
|
|
parser.add_argument('--repo', required=True)
|
|
args = parser.parse_args(sys.argv[sys.argv.index('--') + 1:])
|
|
result = export(Path(args.repo))
|
|
print(json.dumps(result))
|