Recently I've been looking at Povray, pyprocessing, and cfdg (version 3.0) as tools for creating digital images. I have branched two separate blogs where I mainly explore jruby + processing and processing.py

Tuesday, 1 September 2009

Recursive Sierpinski Triangle Using Processing


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
   2 float T_HEIGHT = sqrt(3)/2; 
   3 float TOP_Y = 1/sqrt(3);
   4 float BOT_Y = sqrt(3)/6;
   5 float triangleSize = 800;
   6 
   7 void setup(){
   8   size(int(triangleSize),int(T_HEIGHT*triangleSize));
   9   smooth();  
  10   fill(255);
  11   background(0);
  12   noStroke();
  13   drawSierpinski(width/2, height * (TOP_Y/T_HEIGHT), triangleSize);
  14 }
  15 
  16 void drawSierpinski(float cx, float cy, float sz){
  17   if (sz < 5){  // Limit no of recursions on size
  18     drawTriangle(cx, cy, sz); // Only draw terminals
  19     noLoop();
  20   }
  21   else{
  22     float cx0 = cx;
  23     float cy0 = cy - BOT_Y * sz;
  24     float cx1 = cx - sz/4;
  25     float cy1 = cy + (BOT_Y/2) * sz;
  26     float cx2 = cx + sz/4;
  27     float cy2 = 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 
  34 void drawTriangle(float cx, float cy, float sz){
  35   float cx0 = cx;
  36   float cy0 = cy - TOP_Y * sz;
  37   float cx1 = cx - sz/2;
  38   float cy1 = cy + BOT_Y * sz;
  39   float cx2 = cx + sz/2;
  40   float cy2 = cy + BOT_Y * sz;
  41   triangle(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.

1 comment:

  1. 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

Followers

Blog Archive

About Me

My photo
Pembrokeshire, United Kingdom
I have developed JRubyArt and propane new versions of ruby-processing for JRuby-9.1.5.0 and processing-3.2.2