HatchLing-TuneBox / ling_gltf.py
taellinglin's picture
Dice and board (3D) tab: polyhedra, primitives, glTF export
a336255 verified
Raw History Blame Contribute Delete
15.5 kB
"""The pieces as real 3D objects: a binary glTF (.glb) that opens in Blender, three.js, Unity, Godot, model-viewer and so on.
Every dial and tile becomes its own object (a node you can pick up and move) standing on a base: a round or square board like a Reactable
table, a ball, or a die. Dials are puck-like primitives chosen by style (cylinders, cones, domes, spheres, hexagonal prisms, rings, cubes, or a
different one for each key); tiles are slabs. Signal dials stand taller. Wires are thin tubes in the key's colour. Each node carries its key,
role, signal number and name in its `extras`, so a script (or Blender's custom properties) can read them.
glb = export_glb(scene, style='by key', board='auto') # scene: ling_globe.build(), ling_musicbox.flat_scene() or ling_dice.build()
"""
import json
import math
import struct
import numpy as np
from scipy.spatial.transform import Rotation
from ling_hatch import KEYS, THEMES
STYLES = ['by key (a different shape for each key)', 'cylinders', 'cones', 'domes', 'spheres', 'hexagonal prisms', 'cubes', 'rings', 'pyramids']
BOARDS = ['auto', 'round board', 'square board', 'ball', 'none']
# a different primitive for each of the seven keys
BY_KEY = {'asm': 'cone', 'lit': 'sphere', 'bind': 'cube', 'ctl': 'cylinder', 'call': 'dome', 'fn': 'hexprism', 'mod': 'ring'}
STYLE_OF = {'cylinders': 'cylinder', 'cones': 'cone', 'domes': 'dome', 'spheres': 'sphere', 'hexagonal prisms': 'hexprism', 'cubes': 'cube',
'rings': 'ring', 'pyramids': 'pyramid'}
# =========================================================================== unit meshes: base on z = 0, radius 1, up is +z
def _flat(V, T):
"""Triangles with their own vertices and flat normals."""
V = np.asarray(V, np.float32); T = np.asarray(T, np.int64); tri = V[T]
n = np.cross(tri[:, 1] - tri[:, 0], tri[:, 2] - tri[:, 0]); n /= np.maximum(np.linalg.norm(n, axis=1, keepdims=True), 1e-12)
return tri.reshape(-1, 3), np.repeat(n, 3, 0).astype(np.float32), np.arange(len(T) * 3, dtype=np.uint32)
def _cylinder(n=32, z0=0.0, z1=1.0, r=1.0):
a = np.linspace(0, 2 * math.pi, n, endpoint=False); c, s = np.cos(a), np.sin(a)
pos, nor, idx = [], [], []
for z in (z0, z1): # the side: smooth normals
pos += [np.stack([r * c, r * s, np.full(n, z)], 1)]; nor += [np.stack([c, s, np.zeros(n)], 1)]
k = 0
for i in range(n):
j = (i + 1) % n; idx += [(i, j, n + j), (i, n + j, n + i)]
base = 2 * n
for z, up in ((z1, 1.0), (z0, -1.0)): # the two caps
ring = np.stack([r * c, r * s, np.full(n, z)], 1); pos += [ring, [[0, 0, z]]]; nor += [np.tile([0, 0, up], (n + 1, 1))]
for i in range(n):
j = (i + 1) % n; idx.append((base + i, base + j, base + n) if up > 0 else (base + j, base + i, base + n))
base += n + 1
return np.vstack(pos).astype(np.float32), np.vstack(nor).astype(np.float32), np.array(idx, np.uint32).ravel()
def _cone(n=32, flat=False):
a = np.linspace(0, 2 * math.pi, n, endpoint=False); ring = np.stack([np.cos(a), np.sin(a), np.zeros(n)], 1)
V = np.vstack([ring, [[0, 0, 0]], [[0, 0, 1]]]); T = [(i, (i + 1) % n, n + 1) for i in range(n)] + [((i + 1) % n, i, n) for i in range(n)]
pos, nor, idx = _flat(V, T)
if not flat and n > 4: # smooth the side
nor = nor.copy(); P = pos.reshape(-1, 3, 3)
for t in range(n):
for k in range(3):
x, y = P[t, k, 0], P[t, k, 1]
if P[t, k, 2] > 0.5: x, y = (P[t, 0, 0] + P[t, 1, 0]), (P[t, 0, 1] + P[t, 1, 1])
nrm = np.array([x, y, 1.0]); nor.reshape(-1, 3, 3)[t, k] = nrm / np.linalg.norm(nrm)
return pos, nor, idx
def _sphere(nu=32, nv=16, z0=1.0, half=False):
"""Radius 1 about (0, 0, z0); half: only the upper half (a dome standing on z = z0)."""
v = np.linspace(0, math.pi / (2 if half else 1), nv + 1); u = np.linspace(0, 2 * math.pi, nu + 1)
U, Vv = np.meshgrid(u, v); x = np.sin(Vv) * np.cos(U); y = np.sin(Vv) * np.sin(U); z = np.cos(Vv)
pos = np.stack([x, y, z + z0], -1).reshape(-1, 3); nor = np.stack([x, y, z], -1).reshape(-1, 3)
idx = []
for i in range(nv):
for j in range(nu):
a = i * (nu + 1) + j; b = a + nu + 1; idx += [(a, a + 1, b + 1), (a, b + 1, b)]
idx = np.array(idx, np.int64) # wound outward (the sphere is parametrised from the top down)
return pos.astype(np.float32), nor.astype(np.float32), idx.ravel().astype(np.uint32)
def _torus(R=0.75, r=0.25, nu=32, nv=12):
u = np.linspace(0, 2 * math.pi, nu + 1); v = np.linspace(0, 2 * math.pi, nv + 1); U, Vv = np.meshgrid(u, v)
cx, cy = np.cos(U), np.sin(U); x = (R + r * np.cos(Vv)) * cx; y = (R + r * np.cos(Vv)) * cy; z = r * np.sin(Vv) + r
nor = np.stack([np.cos(Vv) * cx, np.cos(Vv) * cy, np.sin(Vv)], -1).reshape(-1, 3); pos = np.stack([x, y, z], -1).reshape(-1, 3); idx = []
for i in range(nv):
for j in range(nu):
a = i * (nu + 1) + j; b = a + nu + 1; idx += [(a, b + 1, a + 1), (a, b, b + 1)]
return pos.astype(np.float32), nor.astype(np.float32), np.array(idx, np.uint32).ravel()
def _box():
V = [(-1, -1, 0), (1, -1, 0), (1, 1, 0), (-1, 1, 0), (-1, -1, 1), (1, -1, 1), (1, 1, 1), (-1, 1, 1)]
T = [(4, 5, 6), (4, 6, 7), (0, 3, 2), (0, 2, 1), (0, 1, 5), (0, 5, 4), (1, 2, 6), (1, 6, 5), (2, 3, 7), (2, 7, 6), (3, 0, 4), (3, 4, 7)]
return _flat(V, T)
def _prism(n):
a = np.linspace(0, 2 * math.pi, n, endpoint=False) + (math.pi / n if n == 4 else 0.0)
ring = np.stack([np.cos(a), np.sin(a)], 1); V = [(x, y, 0.0) for x, y in ring] + [(x, y, 1.0) for x, y in ring] + [(0, 0, 0.0), (0, 0, 1.0)]
T = []
for i in range(n):
j = (i + 1) % n; T += [(i, j, n + j), (i, n + j, n + i), (2 * n + 1, n + i, n + j), (2 * n, j, i)]
return _flat(V, T)
def _poly(vertices, faces):
"""A convex solid (vertices (n, 3), faces as lists of vertex indices, wound anticlockwise from outside), flat shaded."""
V = np.asarray(vertices, np.float32); T = []
for f in faces:
for k in range(1, len(f) - 1): T.append((f[0], f[k], f[k + 1]))
return _flat(V, T)
UNIT = {'cylinder': lambda: _cylinder(40), 'cone': lambda: _cone(40), 'pyramid': lambda: _cone(4, True), 'sphere': lambda: _sphere(),
'dome': lambda: _sphere(32, 10, 0.0, True), 'cube': _box, 'hexprism': lambda: _prism(6), 'ring': _torus}
UNIFORM = {'sphere'} # scaled the same all round: its height is its radius
# =========================================================================== tubes (wires)
def _tube(pts, r, sides=5):
pts = np.asarray(pts, float)
if len(pts) < 2: return None
tang = np.gradient(pts, axis=0); tang /= np.maximum(np.linalg.norm(tang, axis=1, keepdims=True), 1e-12)
ref = np.where(np.abs(tang[:, [1]]) < 0.9, np.array([[0.0, 1.0, 0.0]]), np.array([[1.0, 0.0, 0.0]]))
n1 = np.cross(tang, ref); n1 /= np.maximum(np.linalg.norm(n1, axis=1, keepdims=True), 1e-12); n2 = np.cross(tang, n1)
a = np.linspace(0, 2 * math.pi, sides, endpoint=False); ring = np.cos(a)[None, :, None] * n1[:, None] + np.sin(a)[None, :, None] * n2[:, None]
pos = (pts[:, None] + r * ring).reshape(-1, 3); nor = ring.reshape(-1, 3); idx = []
for i in range(len(pts) - 1):
for j in range(sides):
k = (j + 1) % sides; a0, a1, b0, b1 = i * sides + j, i * sides + k, (i + 1) * sides + j, (i + 1) * sides + k
idx += [(a0, a1, b1), (a0, b1, b0)]
return pos.astype(np.float32), nor.astype(np.float32), np.array(idx, np.uint32).ravel()
# =========================================================================== the file
class _Glb:
def __init__(self):
self.bin = bytearray(); self.views = []; self.acc = []; self.meshes = []; self.mats = []; self.nodes = []
def _view(self, data: bytes, target=None):
while len(self.bin) % 4: self.bin.append(0)
v = {'buffer': 0, 'byteOffset': len(self.bin), 'byteLength': len(data)}
if target: v['target'] = target
self.bin += data; self.views.append(v); return len(self.views) - 1
def mesh(self, pos, nor, idx, material, name):
pos, nor, idx = np.ascontiguousarray(pos, np.float32), np.ascontiguousarray(nor, np.float32), np.ascontiguousarray(idx, np.uint32)
a = []
for arr, comp, typ, target, extra in ((pos, 5126, 'VEC3', 34962, {'min': pos.min(0).tolist(), 'max': pos.max(0).tolist()}),
(nor, 5126, 'VEC3', 34962, {}), (idx, 5125, 'SCALAR', 34963, {})):
self.acc.append({'bufferView': self._view(arr.tobytes(), target), 'componentType': comp, 'count': int(len(arr)), 'type': typ, **extra}); a.append(len(self.acc) - 1)
self.meshes.append({'name': name, 'primitives': [{'attributes': {'POSITION': a[0], 'NORMAL': a[1]}, 'indices': a[2], 'material': material, 'mode': 4}]})
return len(self.meshes) - 1
def material(self, name, hexcolor, emissive=0.0, rough=0.55, metal=0.15):
c = [((v + 0.055) / 1.055) ** 2.4 if v > 0.04045 else v / 12.92 for v in (int(hexcolor[i:i + 2], 16) / 255 for i in (1, 3, 5))] # sRGB to the linear values glTF wants
m = {'name': name, 'pbrMetallicRoughness': {'baseColorFactor': c + [1.0], 'metallicFactor': metal, 'roughnessFactor': rough}, 'doubleSided': True}
if emissive: m['emissiveFactor'] = [x * emissive for x in c]
self.mats.append(m); return len(self.mats) - 1
def node(self, **kw):
self.nodes.append(kw); return len(self.nodes) - 1
def write(self, root: int) -> bytes:
doc = {'asset': {'version': '2.0', 'generator': 'HatchLing-TuneBox'}, 'scene': 0, 'scenes': [{'nodes': [root]}], 'nodes': self.nodes,
'meshes': self.meshes, 'materials': self.mats, 'accessors': self.acc, 'bufferViews': self.views,
'buffers': [{'byteLength': len(self.bin)}]}
js = json.dumps(doc, separators=(',', ':')).encode(); js += b' ' * (-len(js) % 4)
bn = bytes(self.bin) + b'\0' * (-len(self.bin) % 4)
return (b'glTF' + struct.pack('<II', 2, 12 + 8 + len(js) + 8 + len(bn)) + struct.pack('<I', len(js)) + b'JSON' + js
+ struct.pack('<I', len(bn)) + b'BIN\0' + bn)
def export_glb(sc: dict, style: str = STYLES[0], board: str = 'auto', diameter_m: float = None, theme: str = 'black', wires: bool = True) -> bytes:
"""A scene (the globe's, the flat board's or a die's) -> a .glb with every piece as an object. See the module's notes."""
els = [e for e in sc['els'] if e.get('tess', 0) != 2]; nodes = sc.get('nodes', []); th = THEMES[theme]
flat = bool(sc.get('flat')); solid = sc.get('solid')
C = np.array([np.asarray(e['c'], float) * (np.array([1, 1, 0]) if flat else 1) for e in els]); S = np.array([float(e['scale']) for e in els])
ext = float((np.linalg.norm(C, axis=1) + S).max()) if len(els) else 1.0
if board == 'auto': board = 'none' if solid else ('round board' if flat else 'ball')
if flat and board == 'ball': board = 'round board'
diameter_m = diameter_m or (0.9 if flat else 0.3)
f = diameter_m / (2.0 * ext * (1.04 if flat else 1.0)); g = _Glb()
mats = [g.material('key_' + k, th[k]) for k in KEYS]; mats_node = [g.material('signal_' + k, th[k], emissive=0.35) for k in KEYS]
mboard = g.material('board', '#1c1c20', rough=0.8, metal=0.0); mwire = [g.material('wire_' + k, th[k], emissive=0.8, rough=0.4, metal=0.0) for k in KEYS]
meshes = {}
def unit(name):
if name not in meshes: meshes[name] = {}
return meshes[name]
def mesh_for(prim, hue, node):
d = unit(prim); k = (hue, node)
if k not in d: d[k] = g.mesh(*UNIT[prim](), (mats_node if node else mats)[hue], '%s_%s%s' % (prim, KEYS[hue], '_signal' if node else ''))
return d[k]
children = []
# the base
ctr = np.zeros(3)
if board in ('round board', 'square board') and len(els):
R = ext * 1.04; thick = 0.05 * R
if board == 'round board': m = g.mesh(*_cylinder(96, -1.0, 0.0), mboard, 'board'); sc3 = [R, R, thick]
else:
xy = C[:, :2]; hx = float((np.abs(xy[:, 0]) + S).max()) * 1.04; hy = float((np.abs(xy[:, 1]) + S).max()) * 1.04
m = g.mesh(*_box(), mboard, 'board'); sc3 = [hx, hy, thick]
children.append(g.node(name='board', mesh=m, translation=[0, 0, -thick], scale=sc3))
elif board == 'ball':
m = g.mesh(*_sphere(64, 32, 0.0), mboard, 'ball'); children.append(g.node(name='ball', mesh=m, scale=[0.997] * 3))
if solid is not None: # a die: the solid itself is the base
m = g.mesh(*_poly(solid['V'], solid['F']), mboard, 'die'); children.append(g.node(name='die', mesh=m, scale=[0.998] * 3))
# the pieces
for e, c, s in zip(els, C, S):
hue = int(e['hue']); step = int(e['label']) % 4; is_node = bool(e.get('node')); kind = int(e['kind'])
e1 = np.asarray(e['e1'], float); e2 = np.asarray(e['e2'], float); n = np.cross(e1, e2); n /= max(np.linalg.norm(n), 1e-12)
R = np.stack([e1, e2, n], 1); q = Rotation.from_matrix(R).as_quat().tolist()
if kind == 1: # a tile: a slab
prim, h = 'cube', s * (0.16 + 0.05 * step)
else:
prim = BY_KEY[KEYS[hue]] if style.startswith('by key') else STYLE_OF.get(style, 'cylinder')
h = s * ((0.7 if is_node else 0.32) + 0.08 * step)
if prim == 'ring': h = s
scale = [s, s, s] if prim in UNIFORM else [s, s, h]
extras = {'key': KEYS[hue], 'kind': 'tile' if kind == 1 else 'dial', 'signal': int(e.get('sig', -1)), 'tone': step}
if is_node and e.get('sig', -1) >= 0 and nodes: extras['name'] = nodes[e['sig']].get('name', '')
children.append(g.node(name='%s_%d_%s' % (extras['kind'], e['i'], KEYS[hue]), mesh=mesh_for(prim, hue, is_node), translation=c.tolist(), rotation=q,
scale=scale, extras=extras))
# the wires
if wires and sc.get('wires'):
tr = 0.0035 * ext; by = {}
for w in sc['wires']:
P = np.asarray(w['pts'], float) * (np.array([1, 1, 0]) if flat else 1)
t = _tube(P, tr * (1.6 if w['kind'] == 3 else 1.0))
if t is not None: by.setdefault(int(w['hue']), []).append(t)
for hue, parts in sorted(by.items()):
off = np.cumsum([0] + [len(p[0]) for p in parts[:-1]])
m = g.mesh(np.vstack([p[0] for p in parts]), np.vstack([p[1] for p in parts]), np.concatenate([p[2] + o for p, o in zip(parts, off)]), mwire[hue], 'wires_' + KEYS[hue])
children.append(g.node(name='wires_' + KEYS[hue], mesh=m))
rot = Rotation.from_euler('x', -90, degrees=True).as_quat().tolist() if flat else [0, 0, 0, 1] # the board lies flat: its z becomes up
root = g.node(name='HatchLing-TuneBox', children=children, rotation=rot, scale=[f, f, f], extras={'source': sc.get('name', ''), 'style': style})
return g.write(root)