Sierpinski triangle/Graphical: Difference between revisions

no edit summary
No edit summary
Line 1,630:
Should work with most versions of Processing
 
Recursive Sierpinski triangletriangles
 
===2D versions===
 
<lang Processing>
PVector [] coord = {new PVector(0, 0), new PVector(150, 300), new PVector(300, 0)};
Line 1,650 ⟶ 1,653:
for (int v=0; v<3; v++) {
sierpinski(new PVector((cPoint.x+coord[v].x)/2, (cPoint.y+coord[v].y)/2), cDepth-1);
}
}
</lang>
 
====Animated====
<lang Processing>
int depth = 5;
int interval = 50;
 
int currentTime;
int lastTime;
int progress = 0;
int lastProgress = 0;
//int finished = int(pow(3,depth));
boolean intervalExpired = false;
 
void setup() {
size(410, 230);
background(255);
fill(0);
lastTime = millis();
}
 
void draw() {
currentTime = millis();
triangle (10, 25, 100, depth);
}
 
void triangle (int x, int y, int l, int n) {
if (n == 0) {
checkIfIntervalExpired();
if (intervalExpired && progress == lastProgress) {
text("*", x, y);
lastProgress++;
intervalExpired = false;
}
progress++;
} else {
triangle(x, y+l, l/2, n-1);
triangle(x+l, y, l/2, n-1);
triangle(x+l*2, y+l, l/2, n-1);
}
}
 
void checkIfIntervalExpired() {
if (currentTime-lastTime > interval) {
lastTime = currentTime;
progress = 0;
intervalExpired = true;
}
}
 
void keyReleased() {
if (key==' ') { // reset
progress = 0;
lastProgress = 0;
background(255);
}
}
</lang>
 
===3D version===
<lang Processing>
import peasy.*;
 
int depth = 6; // recursion depth
int dWidth = 600;
int dHeight = 600;
 
color pyramidColor = color( 0 );
color bgColor = color( 255 );
 
// 3D Sierpinski tetrahedron vertices
PVector [] coord = {
new PVector( 0, 0, 0),
new PVector( 300, 0, 0),
new PVector( 150, 0, -260),
new PVector( 150, -245, -86.6)
};
int verts = coord.length;
float boxSize = 600/pow(3, depth);
 
// "random" start point (mid point)
PVector startPoint = new PVector(150, 183.7, 173.2);
 
PeasyCam cam;
 
void settings()
{
size(dWidth, dHeight, P3D);
}
 
void setup()
{
cam = new PeasyCam(this, startPoint.x, startPoint.y, startPoint.z, 400);
cam.setMaximumDistance(3000);
fill(pyramidColor);
stroke(pyramidColor);
}
 
void draw()
{
background(bgColor);
sierpinski(startPoint, depth);
}
 
void sierpinski(PVector currentPoint, int currentDepth)
{
if (currentDepth == 0) {
pushMatrix();
translate(currentPoint.x, 245+currentPoint.y, 260+currentPoint.z);
box(boxSize);
popMatrix();
return;
}
for (int v=0; v<verts; v++) {
sierpinski(new PVector(
(currentPoint.x+coord[v].x)/2,
(currentPoint.y+coord[v].y)/2,
(currentPoint.z+coord[v].z)/2),
currentDepth-1);
}
}
Anonymous user