world_model / blender /blend_code.py
qsun2001's picture
Sync Blender code
38dbb2a verified
Raw
History Blame Contribute Delete
15.4 kB
"""
Whole-scene voxelization exporter.
"""
import bpy
import json
import numpy as np
from pathlib import Path
from collections import defaultdict
# ── Parameters ────────────────────────────────────────────────────────
VOXEL_SIZE = 0.25
# Sub-voxel sampling density. A triangle is sampled so that no two
# consecutive samples are further apart than VOXEL_SIZE / SAMPLES_PER_EDGE.
# 3 empirically gives conservative coverage with reasonable runtime.
SAMPLES_PER_EDGE = 3
# ── Environment ───────────────────────────────────────────────────────
scene = bpy.context.scene
cam = scene.camera
frame_start = scene.frame_start
frame_end = scene.frame_end
OUT_DIR = Path(bpy.path.abspath("//")) / "voxel_export_data"
# ── Helpers ───────────────────────────────────────────────────────────
def is_dynamic(ob):
"""Armature-driven, shape-keyed, or animated meshes are dynamic."""
for mod in ob.modifiers:
if mod.type == 'ARMATURE':
return True
if ob.data.shape_keys is not None:
return True
if ob.animation_data is not None:
return True
return False
def _world_triangles(ob, dg):
"""
Extract triangles from the evaluated mesh in world space.
Returns
-------
tris_world : (T, 3, 3) world-space triangle vertices
tri_vert_ids: (T, 3) indices into the evaluated mesh vertex array
"""
ob_e = ob.evaluated_get(dg)
me = ob_e.to_mesh()
me.calc_loop_triangles()
n_verts = len(me.vertices)
coords = np.empty(n_verts * 3, dtype=np.float64)
if n_verts:
me.vertices.foreach_get("co", coords)
coords = coords.reshape(-1, 3)
n_tri = len(me.loop_triangles)
tri_vert_ids = np.empty(n_tri * 3, dtype=np.int32)
if n_tri:
me.loop_triangles.foreach_get("vertices", tri_vert_ids)
tri_vert_ids = tri_vert_ids.reshape(-1, 3)
mat = np.array(ob_e.matrix_world)
coords_world = (mat[:3, :3] @ coords.T).T + mat[:3, 3] if n_verts else coords
if n_tri:
tris_world = coords_world[tri_vert_ids]
else:
tris_world = np.empty((0, 3, 3), dtype=np.float64)
ob_e.to_mesh_clear()
return tris_world, tri_vert_ids
def _barycentric_grid(n):
"""
Stratified barycentric samples (w, u, v) on the canonical triangle with
n+1 samples along each parametric direction (u, v).
For n=1 we include the three vertices plus the centroid so tiny
triangles still contribute 4 samples.
"""
if n <= 1:
w = np.array([1.0, 0.0, 0.0, 1.0 / 3.0])
u = np.array([0.0, 1.0, 0.0, 1.0 / 3.0])
v = np.array([0.0, 0.0, 1.0, 1.0 / 3.0])
return np.stack([w, u, v], axis=1)
ug, vg = np.meshgrid(
np.linspace(0.0, 1.0, n + 1),
np.linspace(0.0, 1.0, n + 1),
indexing='ij',
)
uu = ug.ravel()
vv = vg.ravel()
keep = uu + vv <= 1.0 + 1e-9
uu = uu[keep]
vv = vv[keep]
ww = 1.0 - uu - vv
return np.stack([ww, uu, vv], axis=1)
def _sample_tris(tris, spacing):
"""
Dense barycentric sampling of a triangle soup.
The sampling rate adapts to the longest edge so every voxel a triangle
passes through receives at least one sample (up to the spacing tolerance).
Returns
-------
pts : (M, 3) world-space sample positions
tri_ids : (M,) which triangle each sample belongs to
bary : (M, 3) (w, u, v) barycentric coordinates per sample
"""
if tris.shape[0] == 0:
return (np.empty((0, 3), dtype=np.float64),
np.empty(0, dtype=np.int64),
np.empty((0, 3), dtype=np.float64))
e1 = tris[:, 1] - tris[:, 0]
e2 = tris[:, 2] - tris[:, 0]
e3 = tris[:, 2] - tris[:, 1]
max_edge = np.maximum.reduce([
np.linalg.norm(e1, axis=1),
np.linalg.norm(e2, axis=1),
np.linalg.norm(e3, axis=1),
])
n_per = np.maximum(1, np.ceil(max_edge / max(spacing, 1e-9)).astype(int))
pts_all = []
tri_ids_all = []
bary_all = []
for n in np.unique(n_per):
sel = np.where(n_per == n)[0]
bary = _barycentric_grid(int(n)) # (S, 3)
sub_tris = tris[sel] # (K, 3, 3)
# (K, S, 3) = sum_i bary[s,i] * sub_tris[k,i,:]
pts = np.einsum('si,kij->ksj', bary, sub_tris)
K, S, _ = pts.shape
pts_all.append(pts.reshape(-1, 3))
tri_ids_all.append(np.repeat(sel, S))
bary_all.append(np.tile(bary, (K, 1)))
return (np.concatenate(pts_all, axis=0),
np.concatenate(tri_ids_all, axis=0),
np.concatenate(bary_all, axis=0))
# ── Static voxelization (whole scene, single grid) ────────────────────
def voxelize_static_scene(static_objects, dg, voxel_size):
"""
Voxelize every static mesh into a single shared voxel grid.
Each occupied voxel is attributed to exactly one object (the one that
contributed the most surface samples to that cell), so the returned
per-object arrays partition the scene's voxels with no overlaps.
Returns
-------
per_obj_centers : dict[name -> (N, 3) float32] voxel-center positions
grid_info : dict with {'origin', 'cell_size'}
"""
if not static_objects:
return {}, {"origin": [0.0, 0.0, 0.0], "cell_size": float(voxel_size)}
obj_tris = {ob.name: _world_triangles(ob, dg)[0] for ob in static_objects}
all_tris = [t for t in obj_tris.values() if t.shape[0] > 0]
if not all_tris:
empty = {n: np.empty((0, 3), dtype=np.float32) for n in obj_tris}
return empty, {"origin": [0.0, 0.0, 0.0], "cell_size": float(voxel_size)}
# Compute global origin from scene AABB, snapped to the voxel grid.
cat_pts = np.concatenate([t.reshape(-1, 3) for t in all_tris], axis=0)
origin = np.floor(cat_pts.min(axis=0) / voxel_size) * voxel_size
spacing = voxel_size / SAMPLES_PER_EDGE
# For every object, count how many samples land in each voxel.
counts_per_obj = {}
for name, tris in obj_tris.items():
if tris.shape[0] == 0:
counts_per_obj[name] = {}
continue
pts, _, _ = _sample_tris(tris, spacing)
keys = np.floor((pts - origin) / voxel_size).astype(np.int64)
uniq, counts = np.unique(keys, axis=0, return_counts=True)
counts_per_obj[name] = {tuple(k): int(c) for k, c in zip(uniq, counts)}
# Assign each voxel to the object with the highest sample count.
# Ties resolved by iteration order (stable across runs given same scene).
winner_count = {}
winner_name = {}
for name, counter in counts_per_obj.items():
for k, c in counter.items():
if k not in winner_count or c > winner_count[k]:
winner_count[k] = c
winner_name[k] = name
# Group voxel keys by winning object, emit centers at grid cell centers.
keys_by_obj = defaultdict(list)
for k, name in winner_name.items():
keys_by_obj[name].append(k)
per_obj_centers = {}
for name in obj_tris:
keys = keys_by_obj.get(name, [])
if not keys:
per_obj_centers[name] = np.empty((0, 3), dtype=np.float32)
continue
ks = np.array(keys, dtype=np.int64)
order = np.lexsort((ks[:, 2], ks[:, 1], ks[:, 0]))
ks = ks[order]
centers = origin + (ks + 0.5) * voxel_size
per_obj_centers[name] = centers.astype(np.float32)
grid_info = {"origin": origin.tolist(), "cell_size": float(voxel_size)}
return per_obj_centers, grid_info
# ── Dynamic voxelization (per-object, aligned to global grid) ─────────
def voxelize_dynamic_mesh(ob, dg, voxel_size, origin):
"""
Build frame-stable voxel groups for a dynamic mesh aligned to the global
grid. Barycentric samples are cached so that each frame we can recompute
sample world positions from the current evaluated mesh and average them
per voxel group, yielding voxel centers that deform with the mesh while
keeping a stable per-voxel ID across frames.
"""
tris, tri_vert_ids = _world_triangles(ob, dg)
empty_state = {
"tri_vert_ids": tri_vert_ids,
"sample_tri_ids": np.empty(0, dtype=np.int64),
"sample_bary": np.empty((0, 3), dtype=np.float64),
"sorted_keys": [],
"voxel_groups": {},
"initial_centers": np.empty((0, 3), dtype=np.float32),
}
if tris.shape[0] == 0:
return empty_state
pts, sample_tri_ids, sample_bary = _sample_tris(tris, voxel_size / SAMPLES_PER_EDGE)
if pts.shape[0] == 0:
return empty_state
keys = np.floor((pts - origin) / voxel_size).astype(np.int64)
groups = defaultdict(list)
for i in range(keys.shape[0]):
groups[tuple(keys[i])].append(i)
sorted_keys = sorted(groups.keys())
voxel_groups = {k: np.asarray(groups[k], dtype=np.int64) for k in sorted_keys}
initial_centers = np.empty((len(sorted_keys), 3), dtype=np.float32)
for i, k in enumerate(sorted_keys):
initial_centers[i] = pts[voxel_groups[k]].mean(axis=0)
return {
"tri_vert_ids": tri_vert_ids,
"sample_tri_ids": sample_tri_ids,
"sample_bary": sample_bary,
"sorted_keys": sorted_keys,
"voxel_groups": voxel_groups,
"initial_centers": initial_centers,
}
def compute_dynamic_centers(ob, dg, state):
"""Recompute dynamic voxel centers from the current frame's evaluated mesh."""
sorted_keys = state["sorted_keys"]
if len(sorted_keys) == 0:
return np.empty((0, 3), dtype=np.float32)
tri_vert_ids = state["tri_vert_ids"]
sample_tri_ids = state["sample_tri_ids"]
sample_bary = state["sample_bary"]
voxel_groups = state["voxel_groups"]
ob_e = ob.evaluated_get(dg)
me = ob_e.to_mesh()
n_verts = len(me.vertices)
coords = np.empty(n_verts * 3, dtype=np.float64)
if n_verts:
me.vertices.foreach_get("co", coords)
coords = coords.reshape(-1, 3)
mat = np.array(ob_e.matrix_world)
coords_world = (mat[:3, :3] @ coords.T).T + mat[:3, 3] if n_verts else coords
ob_e.to_mesh_clear()
tri_verts_world = coords_world[tri_vert_ids] # (T, 3, 3)
sample_tris = tri_verts_world[sample_tri_ids] # (S, 3, 3)
sample_pts = np.einsum('si,sij->sj', sample_bary, sample_tris)
centers = np.empty((len(sorted_keys), 3), dtype=np.float32)
for i, k in enumerate(sorted_keys):
inds = voxel_groups[k]
centers[i] = sample_pts[inds].mean(axis=0)
return centers
# ── Camera ────────────────────────────────────────────────────────────
def extract_camera_data():
"""Extract 4x4 extrinsics and intrinsics from the active scene camera."""
mat = [list(row) for row in cam.matrix_world]
cam_data = cam.data
intrinsics = {
"sensor_width": cam_data.sensor_width,
"sensor_height": cam_data.sensor_height,
"sensor_fit": cam_data.sensor_fit,
"focal_length": cam_data.lens,
"resolution_x": scene.render.resolution_x,
"resolution_y": scene.render.resolution_y,
}
return mat, intrinsics
# ── Driver ────────────────────────────────────────────────────────────
def run():
OUT_DIR.mkdir(exist_ok=True, parents=True)
# ── Step 1: frame 1 β€” classify & voxelize ────────────────────────
scene.frame_set(frame_start)
dg = bpy.context.evaluated_depsgraph_get()
meshes = [ob for ob in scene.objects if ob.type == 'MESH']
static_objs = [ob for ob in meshes if not is_dynamic(ob)]
dynamic_objs = [ob for ob in meshes if is_dynamic(ob)]
print(f"[init] meshes: {len(static_objs)} static, {len(dynamic_objs)} dynamic")
static_centers, grid_info = voxelize_static_scene(static_objs, dg, VOXEL_SIZE)
origin = np.array(grid_info["origin"], dtype=np.float64)
dyn_state = {}
for ob in dynamic_objs:
st = voxelize_dynamic_mesh(ob, dg, VOXEL_SIZE, origin)
dyn_state[ob.name] = st
print(f"[init] dynamic {ob.name}: "
f"{len(st['sorted_keys'])} voxels, "
f"{len(st['sample_tri_ids'])} samples")
for name, centers in static_centers.items():
print(f"[init] static {name}: {centers.shape[0]} voxels")
# ── Step 2: objects_info / static npz ────────────────────────────
objects_info = {}
for ob in static_objs:
objects_info[ob.name] = {
"type": "static",
"voxel_size": float(VOXEL_SIZE),
"grid_info": grid_info,
}
for ob in dynamic_objs:
objects_info[ob.name] = {
"type": "dynamic",
"voxel_size": float(VOXEL_SIZE),
"grid_info": grid_info,
}
static_npz = "static.npz"
np.savez_compressed(str(OUT_DIR / static_npz),
**{n: c for n, c in static_centers.items()})
total_static = sum(c.shape[0] for c in static_centers.values())
print(f"[static] saved {total_static} voxels across "
f"{len(static_centers)} static objects -> {static_npz}")
# ── Step 3: per-frame dynamic centers + camera ───────────────────
frames_meta = []
for f in range(frame_start, frame_end + 1):
scene.frame_set(f)
dg = bpy.context.evaluated_depsgraph_get()
frame_centers = {}
for ob in dynamic_objs:
frame_centers[ob.name] = compute_dynamic_centers(ob, dg, dyn_state[ob.name])
npz_name = f"frame_{f:04d}.npz"
np.savez_compressed(str(OUT_DIR / npz_name), **frame_centers)
extrinsics, intrinsics = extract_camera_data()
frames_meta.append({
"frame": f,
"camera_extrinsics": extrinsics,
"camera_intrinsics": intrinsics,
"data_file": npz_name,
})
total = sum(c.shape[0] for c in frame_centers.values()) + total_static
print(f"[frame {f:04d}] exported {total} voxels "
f"({len(frame_centers)} dynamic + {len(static_centers)} static)")
# ── Metadata ─────────────────────────────────────────────────────
metadata = {
"voxel_size": float(VOXEL_SIZE),
"global_grid": grid_info,
"objects_info": objects_info,
"static_data_file": static_npz,
"frames": frames_meta,
}
with open(str(OUT_DIR / "metadata.json"), "w") as fp:
json.dump(metadata, fp, indent=2)
print(f"[done] exported {len(frames_meta)} frames to {OUT_DIR}")
if __name__ == "__main__":
run()