A proper Sierpinski triangle (only terminal triangles are drawn), recursion is the way to do it, something I learnt while exploring context free art.

1 // Sierpinski.pde by Martin Prout 2floatT_HEIGHT=sqrt(3)/2; 3floatTOP_Y=1/sqrt(3); 4floatBOT_Y=sqrt(3)/6; 5floattriangleSize=800; 6 7voidsetup(){8size(int(triangleSize),int(T_HEIGHT*triangleSize)); 9smooth(); 10fill(255); 11background(0); 12noStroke(); 13 drawSierpinski(width/2, height*(TOP_Y/T_HEIGHT), triangleSize); 14}15 16voiddrawSierpinski(floatcx,floatcy,floatsz){17 if (sz<5){// Limit no of recursions on size 18 drawTriangle(cx, cy, sz); // Only draw terminals 19noLoop(); 20}21else{22floatcx0=cx; 23floatcy0=cy-BOT_Y*sz; 24floatcx1=cx-sz/4; 25floatcy1=cy+(BOT_Y/2)*sz; 26floatcx2=cx+sz/4; 27floatcy2=cy+(BOT_Y/2)*sz; 28 drawSierpinski(cx0, cy0, sz/2); 29 drawSierpinski(cx1, cy1, sz/2); 30 drawSierpinski(cx2, cy2, sz/2); 31}32}33 34voiddrawTriangle(floatcx,floatcy,floatsz){35floatcx0=cx; 36floatcy0=cy-TOP_Y*sz; 37floatcx1=cx-sz/2; 38floatcy1=cy+BOT_Y*sz; 39floatcx2=cx+sz/2; 40floatcy2=cy+BOT_Y*sz; 41triangle(cx0, cy0, cx1, cy1, cx2, cy2); 42}

The mathematically literate of you will see that I could have set the center of the Sierpinski triangle at 2/3 the height, the

*sqrt(3)'s*cancel out. Another thing to be careful about is the processing coordinate system, since you could easily draw the triangle upside-down!!! What you don,t need to worry about is the terminal shape, image might look a bit fuzzy at the edge but you could substitute rect or ellipse as terminal and still get the triangle.

Ah, there's the Sierpinski triangle - one of the nicest things you can see. It reminds me of old Greek buildings, I don't know why.

ReplyDelete