Header Ads

Fractal patterns using Koch curve.

The Koch curve is a mathematical curve and one of the earliest fractal curves to have
been described. The progression for the area of the snowflake converges to 8/5 times the
area of the original triangle, while the progression for the curves perimeter diverges to
infinity.
The Koch curve can be constructed by starting with an equilateral triangle, then
recursively altering each line segment as follows:

  1. divide the line segment into three segments of equal length.

  2. draw an equilateral triangle that has the middle segment from step 1 as its base and
    points outward.

  3. remove the line segment that is the base of the triangle from step 2.
    After one iteration of this process, the resulting shape is the outline of a hexagram.

Algorithm:


Input to the algorithm:

Direction(angle), length and iteration for drawing the Koch curve .
Output of the algorithm
Displaying the Koch Curve.
Data Variables
oldx, oldy : are static float coordinates for the vertex of triangle.
dir
: stores the angle of line segment.
len
: stores the length of line segment.
iter
: stores the number of iterations performed on triangle to produce th koch curve.
dirRad : calculates radians of angle using dir.
newX, newY : calculates new vertex coordinates for cuvre using oldx and oldy by
performing cosine and sine operations on dirRad.
Algorithm
1. Start
2. oldx=-0.7, oldy=0.5;
3. input dir, len and iter
4. dirRad = 0.0174533 * dir;
5. newX = oldx + len * cos(dirRad);
6. newY = oldy + len * sin(dirRad);
7. if (iter==0) { oldx = newX, oldy = newY; }
else{ decrement iter;
drawkoch(dir, len, iter) with dir as 60, -120 and 60 degrees; }
8. goto step no 7
9. Stop.
Output: Display koch curve.
#include <GL/glut.h>
#include <math.h>

GLfloat oldx=-0.7,oldy=0.5;

void drawkoch(GLfloat dir,GLfloat len,GLint iter) {
 GLdouble dirRad = 0.0174533 * dir;  
 GLfloat newX = oldx + len * cos(dirRad);
 GLfloat newY = oldy + len * sin(dirRad);
 if (iter==0) {
  glVertex2f(oldx, oldy);
  glVertex2f(newX, newY);
  oldx = newX;
  oldy = newY;
 }
 else {
  iter--;
  //draw the four parts of the side _/\_ 
  drawkoch(dir, len, iter);
  dir += 60.0;              
  drawkoch(dir, len, iter); 
  dir -= 120.0;
  drawkoch(dir, len, iter); 
  dir += 60.0;
  drawkoch(dir, len, iter); 
 }
}

void display(){
  glClear( GL_COLOR_BUFFER_BIT );
  glBegin(GL_LINES);
    glColor3f(0.0, 1.0, 0.0);
  drawkoch(0.0,0.04,3);
  drawkoch(-120.0, 0.04, 3);
  drawkoch(120.0,0.04,3);
  glEnd();
  glFlush(); 
}

int main(int argc, char** argv)
{
 glutInit(&argc,argv); 
 glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);      
 glutInitWindowSize(500,500);     
 glutInitWindowPosition(0,0); 
 glutCreateWindow("Koch Curve");     
 glutDisplayFunc(display);  
 glutMainLoop();
}

output:



No comments:

Powered by Blogger.