import numpy as np
import k3d
import base64
iteration = 4
size = 3**iteration
voxels = np.ones((size, size, size));
def iterate(length, x, y, z):
nl = length // 3
if nl < 1:
return
margin = (nl-1) // 2
voxels[z-margin:z+margin+1, y-margin:y+margin+1, :] = 0
voxels[z-margin:z+margin+1, :, x-margin:x+margin+1] = 0
voxels[:, y-margin:y+margin+1, x-margin:x+margin+1] = 0
for ix,iy,iz in np.ndindex((3,3,3)):
if (1 if ix !=1 else 0) + (1 if iy != 1 else 0) + (1 if iz != 1 else 0) !=2:
iterate(nl, x + (ix-1) * nl, y + (iy-1) * nl , z + (iz-1) * nl)
iterate(size, size//2, size//2, size//2)
plot = k3d.plot()
plot += k3d.voxels(voxels.astype(np.uint8), compression_level=9)
template = """
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>K3D in js</title>
<style>
#canvasTarget {
width: 100%;
height: 100%;
position: absolute;
}
</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.6/require.min.js"></script>
<script src="https://unpkg.com/k3d/dist/standalone.js"></script>
</head>
<body>
<div id="canvasTarget"></div>
<script>
var K3DInstance;
var data = '[DATA]';
// base64 is only for embeding data in html normally recommeded way is to load data via ajax
function _base64ToArrayBuffer(base64) {
var binary_string = window.atob(base64);
var len = binary_string.length;
var bytes = new Uint8Array(len);
for (var i = 0; i < len; i++) {
bytes[i] = binary_string.charCodeAt(i);
}
return bytes;
}
require(['k3d'], function (lib) {
try {
K3DInstance = new lib.CreateK3DAndLoadBinarySnapshot(
_base64ToArrayBuffer(data),
document.getElementById('canvasTarget'),
);
K3DInstance.then(function(K3DInstance) {
console.log(K3DInstance);
});
} catch (e) {
console.log(e);
return;
}
});
</script>
</body>
</html>
"""
data = plot.get_binary_snapshot()
with open("k3d_in_javascript.html", "w") as f:
# base64 is only for embeding data in html normally recommeded way is to load data via ajax
f.write(template.replace("[DATA]", base64.b64encode(data).decode("utf-8")))