float mx, my; boolean[][][] sponge; int separation, subdivisions; //------------------------- void setup(){ size(300,300, P3D); mx = width/2f; my = height/2f; framerate(30); separation = 0; subdivisions = 0; sponge = new boolean[3][3][3]; // this code fills the sponge template tensor with booelan values // which reveals where the menger sponge iteration should be filled for(int x=0;x<3;x++) for(int y=0;y<3;y++) for(int z=0;z<3;z++) sponge[x][y][z] = !( (x==1)&&(y==1) || (y==1)&&(z==1) || (x==1)&&(z==1) ); } //------------------------- void draw(){ background(245); fill(128); noStroke(); directionalLight(192, 255, 128, 0.5, 0.5, -0.5); pointLight(192, 255, 128, 0, 0, 0); translate(mx,my,-2*mx); rotateX( -(mouseY-my)*0.01 ); rotateY( -(mouseX-mx)*0.01 ); drawMengerSponge( 100f, subdivisions ); } //------------------------- void drawMengerSponge(float siz, int level){ for(int x=0;x<3;x++) for(int y=0;y<3;y++) for(int z=0;z<3;z++) if(sponge[x][y][z]){ translate( (x-1)*siz, (y-1)*siz, (z-1)*siz ); if(level!=0) drawMengerSponge( siz/3, level-1 ); else box(siz-separation); translate( -(x-1)*siz, -(y-1)*siz, -(z-1)*siz ); } } //------------------------- void keyPressed(){ if(key=='1') subdivisions = 0; if(key=='2') subdivisions = 1; if(key=='3') subdivisions = 2; if(key=='q' || key=='Q') separation = (separation+2) % 4; } //-------------------------