赛平斯基Sierpinski垫片 源代码

#include
#include
#include
#include
using namespace std;


struct GLPoint{
    GLfloat x, y;
};

void myDisplay(void);
void myReshape(int x, int y);
void myMouse(int button, int state , int x ,int y);
void myKeyboard(unsigned char key,int x, int y );
void myInit(void);
void sierpinski_render(void);

int main(int argc, char** argv)
{
   glutInit(&argc,argv);
   glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);            //单缓冲
   glutInitWindowSize(640,480);
   glutInitWindowPosition(100,150);
   glutCreateWindow("my first attempt");

   //只有注册回调函数才显示窗口,奇怪
   glutDisplayFunc(myDisplay);
   glutReshapeFunc(myReshape);
   glutMouseFunc(myMouse);
   glutKeyboardFunc(myKeyboard);
 
   myInit();

   glutMainLoop();

    return 0;
}

void myDisplay(void){
    sierpinski_render();
}
void myReshape(int x, int y){
    std::cout<<"( "<
}
void myMouse(int button, int state , int x ,int y){
    std::cout<<"state:"< }
void myKeyboard(unsigned char key,int x, int y ){
    std::cout< }
void myInit(void){
    std::cout<<"Init Begin..."<     glClearColor(1.0,1.0,1.0,1.0);    //设定清除颜色,这条指令只是为后面的使用设置状态变量 白色
    glColor3f(0.0f,0.0f,0.0f);        //笔触黑色
    glPointSize(4.0);                //笔触大小4x4像素
    glMatrixMode(GL_PROJECTION);        //设置合适的矩阵
    glLoadIdentity();
    gluOrtho2D(0.0,640,0.0,600);    //设定屏幕窗口的变换

}

void sierpinski_render(void){
    glClear(GL_COLOR_BUFFER_BIT);
    GLPoint T[3] = {{10,10},{600,10},{300,600}};

    int index = rand()%3;
    GLPoint point = T[index];

    glBegin(GL_POINTS);
    glVertex2i(point.x, point.y);
    

    for (int i=0;i<5500;i++)
    {
        index  = rand()%3;
        point.x = (point.x + T[index].x)/2;
        point.y = (point.y + T[index].y)/2;
        glVertex2i(point.x , point.y);
    }

    glEnd();
    glFlush();
}



运行结果 :

赛平斯基Sierpinski垫片 源代码_第1张图片

你可能感兴趣的:(OpenGL)