In [ ]:
import k3d
import numpy as np
import skimage.measure
In [ ]:
def generate(dim):
data = np.zeros((dim, dim, dim), dtype=np.uint8)
x = np.linspace(-0.5, 0.5, dim, dtype=np.float32)
y = np.linspace(-0.5, 0.5, dim, dtype=np.float32)
z = np.linspace(-0.5, 0.5, dim, dtype=np.float32)
x, y, z = np.meshgrid(x, y, z)
c, s = np.cos(1.5 * x), np.sin(1.5 * x)
my = y * c - z * s
mz = y * s + z * c
my = np.fmod(my + 0.5, 0.333) * 3 - 0.5
mz = np.fmod(mz + 0.5, 0.333) * 3 - 0.5
displace = np.sin(60.0 * x) * np.sin(60.0 * my) * np.sin(60.0 * mz) * 0.1
data = np.sqrt(my**2 + mz**2) * (2.5 + 0.8 * np.sin(x * 50)) + displace
return (data < 0.25).astype(np.uint8)
dim = 256
data = generate(dim)
In [ ]:
plot = k3d.plot()
plot += k3d.voxels(data)
plot.display()
In [ ]:
plot.grid_visible = False
In [ ]:
chunk_size = 16
voxelsGroup = []
for z,y,x in zip(*np.where(skimage.measure.block_reduce(data, (chunk_size,chunk_size,chunk_size), np.max) > 0)):
chunk = {
"voxels": data[z*chunk_size:(z+1)*chunk_size,
y*chunk_size:(y+1)*chunk_size,
x*chunk_size:(x+1)*chunk_size],
"coord": np.array([x,y,z]) * chunk_size,
"multiple": 1
}
voxelsGroup.append(chunk)
In [ ]:
len(voxelsGroup), (len(voxelsGroup) * chunk_size ** 3) / (1024 ** 2), data.size / (1024 ** 2)
space_size = np.array(data.shape, dtype=np.uint32)[::-1]
In [ ]:
plot = k3d.plot()
obj = k3d.voxels_group(space_size, voxelsGroup)
plot += obj
plot.display()
In [ ]:
np.sum(np.dstack([p['voxels'] for p in obj.voxels_group]))
Edit object (add/remove some voxels)
In [ ]:
plot.mode = 'change'
In [ ]:
obj.fetch_data('voxels_group')
In [ ]:
np.sum(np.dstack([p['voxels'] for p in obj.voxels_group]))
In [ ]:
chunks = [k3d.voxel_chunk(g["voxels"], g["coord"], compression_level=1) for g in voxelsGroup]
In [ ]:
plot = k3d.plot()
obj = k3d.voxels_group(space_size,
chunks_ids=[c["id"] for c in chunks])
plot += obj
plot.display()
In [ ]:
for c in chunks:
c.voxels = np.ones_like(c.voxels)
In [ ]:
len(chunks)
In [ ]:
plot -= obj