playful / chess-sim /code /sim /prepare_chess_assets.py
Ali-Uraish's picture
Add files using upload-large-folder tool
33c14d6 verified
Raw History Blame Contribute Delete
6.86 kB
"""Convert the vendored MIT Staunton STLs into metre-scale simulation assets.
Run only when rebuilding assets: uv pip install --python .venv/bin/python -e '.[assets]'
Then: .venv/bin/python sim/prepare_chess_assets.py
Scene generation and simulation use the checked-in outputs without these extra dependencies.
"""
from __future__ import annotations
import hashlib
import json
from pathlib import Path
import coacd
import numpy as np
import trimesh
ROOT = Path(__file__).resolve().parent / "assets" / "chess"
COMMIT = "cef2c79445380c5bffec461a80c7c91caf89b3b2"
KINDS = ("pawn", "rook", "knight", "bishop", "queen", "king")
# One uniform scale for the entire set; the upstream king is 78 units tall.
KING_HEIGHT = 0.046
SCALE = KING_HEIGHT / 78.0
# Estimates, not physical measurements. Replace with weighed masses before deployment.
MASS_KG = dict(pawn=0.006, rook=0.009, knight=0.009, bishop=0.008, queen=0.010, king=0.011)
DECOMPOSITION = dict(threshold=0.035, max_convex_hull=32, resolution=1500,
mcts_iterations=60, mcts_nodes=15, decimate=True,
max_ch_vertex=80, seed=0)
def convex_slice(mesh, lo, hi):
"""Convex hull of a horizontal slab, including exact triangle/plane crossings."""
vertices = mesh.vertices
points = [vertices[(vertices[:, 2] >= lo) & (vertices[:, 2] <= hi)]]
a, b = vertices[mesh.edges_unique[:, 0]], vertices[mesh.edges_unique[:, 1]]
for z in (lo, hi):
mask = ((a[:, 2] <= z) & (b[:, 2] > z)) | ((b[:, 2] <= z) & (a[:, 2] > z))
aa, bb = a[mask], b[mask]
points.append(aa + (bb - aa) * ((z - aa[:, 2]) / (bb[:, 2] - aa[:, 2]))[:, None])
points = np.concatenate(points)
if len(points) < 4 or np.ptp(points[:, 2]) < 1e-7:
return None
# Millimetres avoid welding distinct vertices in sub-millimetre slabs.
hull = trimesh.Trimesh(vertices=points * 1000, process=False).convex_hull
hull.apply_scale(0.001)
return hull
def prepare(kind: str) -> dict:
source = ROOT / "source" / f"{kind.title()}.stl"
mesh = trimesh.load_mesh(source)
# CAD files are Y-up and have different offsets. +90 degrees about X gives Z-up.
mesh.vertices = mesh.vertices[:, [0, 2, 1]] * [1, -1, 1]
# Centre using the circular foot, not the asymmetric knight's head.
foot = mesh.vertices[mesh.vertices[:, 2] < mesh.bounds[0, 2] + 0.1]
origin = np.r_[(foot[:, :2].min(0) + foot[:, :2].max(0)) / 2, mesh.bounds[0, 2]]
mesh.apply_translation(-origin)
mesh.apply_scale(SCALE)
mesh.export(ROOT / f"{kind}.stl")
height = float(mesh.extents[2])
# Choose an actual narrow cross-section in the middle of the body, below the head.
candidates = []
fractions = (0.25, 0.39) if kind == "knight" else (0.32, 0.58)
for z in np.linspace(height * fractions[0], height * fractions[1], 50):
section = mesh.section(plane_origin=[0, 0, z], plane_normal=[0, 0, 1])
if section is not None:
radius = float(np.linalg.norm(section.vertices[:, :2], axis=1).max())
candidates.append((radius, float(z)))
radius, grasp_z = min(candidates)
# Work in millimetres for the decomposition's numerical conditioning.
settings = dict(DECOMPOSITION)
parts = coacd.run_coacd(coacd.Mesh(mesh.vertices * 1000, mesh.faces), **settings)
hulls = [trimesh.Trimesh(vertices=np.asarray(v) / 1000, faces=f).convex_hull for v, f in parts]
if kind == "knight":
# Automatic remeshing of the non-watertight horse head also inflates its
# thin neck. Preserve the foot/neck directly as convex slices (0.25 mm
# around the gripping region, 1 mm elsewhere) and
# retain only the upper part of the automatic decomposition for the head.
split_z = 0.014
upper = []
for hull in hulls:
clipped = convex_slice(hull, split_z, float(mesh.bounds[1, 2]) + 0.01)
if clipped is not None:
upper.append(clipped)
lower = []
# Split at the narrowest neck itself so its groove is not bridged.
edges = np.unique(np.round(np.r_[np.linspace(0, split_z, 15), np.linspace(0.007, 0.012, 21), grasp_z], 9))
for lo, hi in zip(edges[:-1], edges[1:]):
lower.append(convex_slice(mesh, lo, hi))
hulls = lower + upper
settings["lower_exact_slices"] = dict(height_m=split_z, z_edges_m=edges.tolist())
files = []
for i, hull in enumerate(hulls):
if not hull.is_watertight or hull.volume <= 0:
raise ValueError(f"Invalid collision hull for {kind}: {i}")
path = ROOT / "collision" / f"{kind}_{i:02d}.stl"
hull.export(path)
files.append(str(path.relative_to(ROOT)))
for stale in (ROOT / "collision").glob(f"{kind}_*.stl"):
if str(stale.relative_to(ROOT)) not in files:
stale.unlink()
# Full-mesh inertia where valid; knight uses the convex approximation. Explicit
# body inertials prevent duplicate visual and collision geometry adding mass.
solid = mesh if mesh.is_watertight else trimesh.util.concatenate(hulls)
mass = MASS_KG[kind]
inertia = solid.moment_inertia * mass / solid.volume
return dict(source_file=str(source.relative_to(ROOT)),
source_sha256=hashlib.sha256(source.read_bytes()).hexdigest(),
visual=f"{kind}.stl", collision=files, height_m=height,
bounds_m=mesh.bounds.tolist(), mass_kg=mass,
center_of_mass_m=solid.center_mass.tolist(),
fullinertia_kg_m2=[float(inertia[i, j]) for i, j in
((0, 0), (1, 1), (2, 2), (0, 1), (0, 2), (1, 2))],
inertia_source="uniform solid mesh" if mesh.is_watertight else "convex parts approximation",
source_watertight=bool(mesh.is_watertight),
grasp_z_m=grasp_z, grasp_diameter_m=2 * radius,
triangles=len(mesh.faces), collision_hulls=len(hulls), decomposition=settings)
def main():
(ROOT / "collision").mkdir(exist_ok=True)
coacd.set_log_level("warn")
manifest = dict(source_url="https://github.com/clarkerubber/Staunton-Pieces",
source_commit=COMMIT, license="MIT", units="metres",
uniform_scale_from_source=SCALE,
mass_note="Estimated masses and uniform-density inertia; calibrate against the real set.",
decomposition=DECOMPOSITION, pieces={})
for kind in KINDS:
manifest["pieces"][kind] = prepare(kind)
p = manifest["pieces"][kind]
print(f"{kind}: {p['height_m']*1000:.1f} mm, {p['triangles']} triangles, "
f"{p['collision_hulls']} collision hulls", flush=True)
(ROOT / "manifest.json").write_text(json.dumps(manifest, indent=2) + "\n")
if __name__ == "__main__":
main()