Skip to content

Instantly share code, notes, and snippets.

@grifdail
Created November 18, 2017 11:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save grifdail/5b2f7663bc5b3eac93c69bb9c20ddba2 to your computer and use it in GitHub Desktop.
Save grifdail/5b2f7663bc5b3eac93c69bb9c20ddba2 to your computer and use it in GitHub Desktop.
Voxelizer
// Copy that into MeshPlayground
// http://grifdail.fr/MeshPlayground/
var box = new Box(1);
const sphereVolume = (radius, center) => (x,y,z) => sqrt((x-center.x)*(x-center.x)+(y-center.y)*(y-center.y)+(z-center.z)*(z-center.z))<radius;
const mainSphere = sphereVolume(0.4, Vector3.one().scale(0.5));
const holeSphere = sphereVolume(0.7, Vector3.one().scale(1));
const holeSphere2 = sphereVolume(0.3, new Vector3(0.3,0.3,0.6));
const holeNoise = (x,y,z) => perlin3(x*1,y*4,z*2)<-0.2;
const volumeFunction = (...params) =>{
if(params.some(x => x<0 || x>1)) {
return false
}
return holeNoise(...params) && !mainSphere(...params);
};
const palette = ColorPalettes.Moon;
const colorFunction = (x,y,z) => palette[floor(remapZeroOne(perlin3(x*2,y,z*3)) * palette.length)];
setBackgroundColor(palette[0])
noiseSeed(random())
function voxelizeVolume(size, fn, colorFn) {
const m = new Mesh();
const delta = 1/size;
m.translate(-size*0.5,-size*0.5,-size*0.5);
for(var x = 0; x<size; x++) {
for(var y = 0; y<size; y++) {
for(var z = 0; z<size; z++) {
m.push();
m.translate(new Vector3(x,y,z));
let posCenter = new Vector3((x+0.5)/size, (y+0.5)/size, (z+0.5)/size);
m.setColor(colorFunction(posCenter.x,posCenter.y,posCenter.z))
if (fn(posCenter.x,posCenter.y,posCenter.z)) {
if (!fn(posCenter.x-delta,posCenter.y,posCenter.z)) {
m.addQuad(box.LTF, box.LTB, box.LBB, box.LBF);
}
if (!fn(posCenter.x+delta,posCenter.y,posCenter.z)) {
m.addQuad(box.RTB, box.RTF, box.RBF, box.RBB);
}
if (!fn(posCenter.x,posCenter.y+delta,posCenter.z)) {
m.addQuad(box.LTF, box.RTF, box.RTB, box.LTB);
}
if (!fn(posCenter.x,posCenter.y-delta,posCenter.z)) {
m.addQuad(box.LBB, box.RBB, box.RBF, box.LBF);
}
if (!fn(posCenter.x,posCenter.y,posCenter.z+delta)) {
m.addQuad(box.RTF, box.LTF, box.LBF, box.RBF);
}
if (!fn(posCenter.x,posCenter.y,posCenter.z-delta)) {
m.addQuad(box.LTB, box.RTB, box.RBB, box.LBB);
}
}
m.pop()
}
}
}
return m;
}
const vox = voxelizeVolume(100,volumeFunction, colorFunction);
//scale(10)
addFaces(vox);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment