Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // CS 435 - Project 1: write a program to render a koch snowflake, or something
- // to that effect.
- // g++ -lGL -lGLU -lglut -o snowflake snowflake.cpp
- #include <GL/glut.h>
- #include <math.h>
- using namespace std;
- #ifndef M_PI
- #define M_PI (3.1415926535897932384626433832795)
- #endif
- double x = -0.5; // starting point
- double y = 0.3;
- double angle = 0; //starting angle is 0, drawing east ->
- int fractallevel = 8; // fractal depth, 8 is large enough to be detailed without being so large as to take FOREVER
- void recurse_koch(int level, double length) {
- if (level <= 0) { //oh ho ho we got here time to draw draw draw
- double newx = x + length * cos(M_PI * angle / 180.0); // sum trig work it out if you want to know what it does
- double newy = y + length * sin(M_PI * angle / 180.0); // mo' trig, all computed relatively to current point/direction
- glBegin(GL_LINES); // draw the line it is time :-o
- glVertex2d(x, y);
- glVertex2d(newx, newy);
- glEnd();
- x = newx; // change our starting point for the next line segment, dont wanna create a * thing.
- y = newy; // doop doop
- } else {
- recurse_koch(level-1, length/3.0); // first line segment.
- angle += 60; // rotate counter clockwise, creating the 'hump' (technical term)
- recurse_koch(level-1, length/3.0); // upward half of hump
- angle -= 120; // correct for the hump plus some to get back to where the line's supposed to be
- recurse_koch(level-1, length/3.0); // downward half of hump
- angle += 60; // there angle fixed we're going in the correct direction again
- recurse_koch(level-1, length/3.0); // finish the line
- }
- }
- void koch(int level) {
- recurse_koch(level, 1.0); // after this finishes, will be east of the starting point, so rotate clockwise
- angle -= 120;
- recurse_koch(level, 1.0); // after this finishes, will be at the bottom point, so rotate clockwise towards the orgin
- angle -= 120;
- recurse_koch(level, 1.0); // will finish at the orgin, completing the triangle/figure
- }
- void display() {
- glClearColor(1.0, 1.0, 1.0, 1.0); // white background
- glClear(GL_COLOR_BUFFER_BIT);
- glLineWidth(1.0);
- glColor3d(1.0, 0.0, 0.0); // red color
- koch(fractallevel);
- glMatrixMode(GL_MODELVIEW);
- glFlush();
- }
- int main(int argc, char ** argv) {
- glutInit(&argc, argv);
- glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
- glutInitWindowSize(500, 500);
- glutCreateWindow("Koch Snowflake");
- glutDisplayFunc(display);
- glutMainLoop();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement