William's profileWilliamBlogListsGuestbookMore Tools Help

Blog


    March 05

    Sierpinski gasket

    I am learning computer graphics through reading <Computer Graphics Using OpenGL Second Edition>.

    And I generated the Sierpinski gasket using OpenGL and VC++ 2005. There is the result:

    sierpinski

    There is the source code which can be compiled in visual studio 2005:

    // Draw sierpinski gasket
    //P49 in <Computer Graphics Using OpenGL>

    #include "GLintPoint.h"
    #include <iostream>

    using std::cout;
    using std::cin;
    using std::endl;

    // Create a number between 0 and m(a number which will be given)
    // the input m must be less than 32767 according to P49 in <Computer Graphics Using OpenGL>
    int random(int m)
    {
        if(m<0||m>32767)
        {
            cout<<"There is something wrong in random."<<endl;
        }
        int rand();
        return rand()%m;
    }

    void drawDot (GLint x, GLint y)
    {
        glBegin(GL_POINTS);
            glVertex2i(x,y);
        glEnd();
    }

    // Draw sierpinski gasket
    void sierpinski()
    {
        GLint random(GLint);
        glClear(GL_COLOR_BUFFER_BIT);       //clear the screen

        GLintPoint T[3]={{10,10},{300,30},{200,300}};
        int index=random(3);       //0,1 or 2 equally likely
        GLintPoint point = T[index]; // initial point
        drawDot(point.x,point.y);     //draw initial point

        drawDot(T[0].x,T[0].y);
        drawDot(T[1].x,T[1].y);
        drawDot(T[2].x,T[2].y);

        // Draw 10000 Dots
        for( int i=0;i<10000;i++)
        {
            index = random(3);
            point.x = (point.x+T[index].x)/2;
            point.y = (point.y+T[index].y)/2;
            drawDot(point.x,point.y);
        }
        glFlush();       // Send all output to display   
    }

    // Initialization
    void Init(void)    
    {
        glClearColor(1.0,1.0,1.0,0.0); // Set white background color
        glColor3f(0.0f,0.0f,0.0f);    // Set the drawing color
        glPointSize(4.0);             // a 'dot' is 4 by 4 pixels
        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();
        gluOrtho2D(0.0,640.0,0.0,480.0);
    }

    void main(int argc,char *argv[])
    {
        glutInit(&argc, argv);  // Initialize the toolkit
        glutInitDisplayMode(GLUT_RGB | GLUT_SINGLE);  // Set display mode
        glutInitWindowPosition(100, 150);  // Set window pozition on screen
        glutInitWindowSize(640, 480);      // Set window size
        glutCreateWindow("sierpinski gasket"); // Open the screen window
        glutDisplayFunc(sierpinski); // Register redraw function
        Init();
        glutMainLoop();  // Go into a perpetual loop
    }