C++ OpenGl显示动画和绘制文本

C++ OpenGl显示动画和绘制文本,c++,c,opengl,C++,C,Opengl,我想展示太阳系,并画一个简单的文字说“你好,世界”: 下面的代码显示了太阳系和一切工作: #include <iostream> #include <OpenGL/gl.h> #include <GLUT/glut.h> void OpenGLInit(void); static void Animate(void ); static void Key_r(void ); static void Key_s(void ); static void K

我想展示太阳系,并画一个简单的文字说“你好,世界”:

下面的代码显示了太阳系和一切工作:

#include <iostream>

#include <OpenGL/gl.h>

#include <GLUT/glut.h>


void OpenGLInit(void);

static void Animate(void );
static void Key_r(void );
static void Key_s(void );
static void Key_up(void );
static void Key_down(void );
static void ResizeWindow(int w, int h);

static void KeyPressFunc( unsigned char Key, int x, int y );
static void SpecialKeyFunc( int Key, int x, int y );





static GLenum spinMode = GL_TRUE;
static GLenum singleStep = GL_FALSE;

// These three variables control the animation's state and speed.
static float HourOfDay = 0.0;
static float DayOfYear = 0.0;
static float AnimateIncrement = 24.0;  // Time step for animation (hours)

// glutKeyboardFunc is called below to set this function to handle
//      all normal key presses.  
static void KeyPressFunc( unsigned char Key, int x, int y )
{
    switch ( Key ) {
        case 'R':
        case 'r':
            Key_r();
            break;
        case 's':
        case 'S':
            Key_s();
            break;
        case 27:    // Escape key
            exit(1);
    }
}

// glutSpecialFunc is called below to set this function to handle
//      all special key presses.  See glut.h for the names of
//      special keys.
static void SpecialKeyFunc( int Key, int x, int y )
{
    switch ( Key ) {
        case GLUT_KEY_UP:       
            Key_up();
            break;
        case GLUT_KEY_DOWN:
            Key_down();
            break;
    }
}


static void Key_r(void)
{
    if ( singleStep ) {         // If ending single step mode
        singleStep = GL_FALSE;
        spinMode = GL_TRUE;     // Restart animation
    }
    else {
        spinMode = !spinMode;   // Toggle animation on and off.
    }
}

static void Key_s(void)
{
    singleStep = GL_TRUE;
    spinMode = GL_TRUE;
}

static void Key_up(void)
{
    AnimateIncrement *= 2.0;            // Double the animation time step
}

static void Key_down(void)
{
    AnimateIncrement /= 2.0;            // Halve the animation time step

}

/*
 * Animate() handles the animation and the redrawing of the
 *      graphics window contents.
 */
static void Animate(void)
{
    // Clear the redering window
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    if (spinMode) {
        // Update the animation state
        HourOfDay += AnimateIncrement;
        DayOfYear += AnimateIncrement/24.0;

        HourOfDay = HourOfDay - ((int)(HourOfDay/24))*24;
        DayOfYear = DayOfYear - ((int)(DayOfYear/365))*365;
    }

    // Clear the current matrix (Modelview)
    glLoadIdentity();

    // Back off eight units to be able to view from the origin.
    glTranslatef ( 0.0, 0.0, -8.0 );

    // Rotate the plane of the elliptic
    // (rotate the model's plane about the x axis by fifteen degrees)
    glRotatef( 15.0, 1.0, 0.0, 0.0 );

    // Draw the sun -- as a yellow, wireframe sphere
    glColor3f( 1.0, 1.0, 0.0 );         
    glutWireSphere( 1.0, 15, 15 );

    // Draw the Earth
    // First position it around the sun
    //      Use DayOfYear to determine its position
    glRotatef( 360.0*DayOfYear/365.0, 0.0, 1.0, 0.0 );
    glTranslatef( 4.0, 0.0, 0.0 );
    glPushMatrix();                     // Save matrix state
    // Second, rotate the earth on its axis.
    //      Use HourOfDay to determine its rotation.
    glRotatef( 360.0*HourOfDay/24.0, 0.0, 1.0, 0.0 );
    // Third, draw the earth as a wireframe sphere.
    glColor3f( 0.2, 0.2, 1.0 );
    glutWireSphere( 0.4, 10, 10);
    glPopMatrix();                      // Restore matrix state

    // Draw the moon.
    //  Use DayOfYear to control its rotation around the earth
    glRotatef( 360.0*12.0*DayOfYear/365.0, 0.0, 1.0, 0.0 );
    glTranslatef( 0.7, 0.0, 0.0 );
    glColor3f( 0.3, 0.7, 0.3 );
    glutWireSphere( 0.1, 5, 5 );

    // Flush the pipeline, and swap the buffers
    glFlush();
    glutSwapBuffers();

    if ( singleStep ) {
        spinMode = GL_FALSE;
    }

    glutPostRedisplay();        // Request a re-draw for animation purposes

}

// Initialize OpenGL's rendering modes
void OpenGLInit(void)
{
    glShadeModel( GL_FLAT );
    glClearColor( 0.0, 0.0, 0.0, 0.0 );
    glClearDepth( 1.0 );
    glEnable( GL_DEPTH_TEST );
}

// ResizeWindow is called when the window is resized
static void ResizeWindow(int w, int h)
{
    float aspectRatio;
    h = (h == 0) ? 1 : h;
    w = (w == 0) ? 1 : w;
    glViewport( 0, 0, w, h );   // View port uses whole window
    aspectRatio = (float)w/(float)h;

    // Set up the projection view matrix (not very well!)
    glMatrixMode( GL_PROJECTION );
    glLoadIdentity();
    gluPerspective( 60.0, aspectRatio, 1.0, 30.0 );

    // Select the Modelview matrix
    glMatrixMode( GL_MODELVIEW );
}




// Main routine
// Set up OpenGL, hook up callbacks, and start the main loop
int main( int argc, char** argv )
{
    // Need to double buffer for animation
    glutInit(&argc,argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH );

    // Create and position the graphics window
    glutInitWindowPosition( 0, 0 );
    glutInitWindowSize( 600, 360 );
    glutCreateWindow( "Solar System Demo" );


    // Initialize OpenGL.
    OpenGLInit();

    // Set up callback functions for key presses
    glutKeyboardFunc( KeyPressFunc );
    glutSpecialFunc( SpecialKeyFunc );

    // Set up the callback function for resizing windows
    glutReshapeFunc( ResizeWindow );

    // Callback for graphics image redrawing
    glutDisplayFunc( Animate );



    // Start the main loop.  glutMainLoop never returns.
    glutMainLoop(  );

    return(0);          // Compiler requires this to be here. (Never reached)
}
#包括
#包括
#包括
void OpenGLInit(void);
静态void动画(void);
静态无效键(无效);
静态无效键(无效);
静态无效键向上(无效);
静态无效键_向下(无效);
静态空隙大小调整窗口(int w,int h);
静态void KeyPressFunc(无符号字符键,int x,int y);
静态void SpecialKeyFunc(int键,int x,int y);
静态盂自旋模式=GL_真;
静态肩胛盂单步=GL_假;
//这三个变量控制动画的状态和速度。
静态浮动时间=0.0天;
年静态浮动日=0.0;
静态浮点动画增量=24.0;//动画的时间步长(小时)
//下面调用glutKeyboardFunc将此函数设置为句柄
//所有正常按键。
静态void KeyPressFunc(无符号字符键,整数x,整数y)
{
开关(钥匙){
案例“R”:
案例“r”:
键_r();
打破
案例s:
案例S:
键_s();
打破
案例27://逃生钥匙
出口(1);
}
}
//下面调用glutSpecialFunc将此函数设置为处理
//所有特殊按键。请参见glut.h以了解
//特殊钥匙。
静态void SpecialKeyFunc(int键、int x、int y)
{
开关(钥匙){
案例过多关键点:
键向上();
打破
案例过量键关闭:
按键向下();
打破
}
}
静态无效键(无效)
{
if(单步){//if结束单步模式
单步=GL_假;
spinMode=GL_TRUE;//重新启动动画
}
否则{
spinMode=!spinMode;//打开和关闭动画。
}
}
静态无效键(无效)
{
singleStep=GL_TRUE;
spinMode=GL_TRUE;
}
静态无效键向上(无效)
{
AnimateIncrement*=2.0;//动画时间步长加倍
}
静态无效键向下(无效)
{
AnimateIncrement/=2.0;//将动画时间步长减半
}
/*
*Animate()处理动画和图像的重绘
*图形窗口内容。
*/
静态空心动画(空心)
{
//清除重新装饰的窗户
glClear(GL_颜色_缓冲_位| GL_深度_缓冲_位);
如果(旋转模式){
//更新动画状态
HourOfDay+=动画增量;
DayOfYear+=动画增量/24.0;
houroday=houroday-((int)(houroday/24))*24;
DayOfYear=DayOfYear-((int)(DayOfYear/365))*365;
}
//清除当前矩阵(Modelview)
glLoadIdentity();
//后退八个单位,以便能够从原点查看。
glTranslatef(0.0,0.0,-8.0);
//旋转椭圆曲线的平面
//(将模型平面绕x轴旋转十五度)
glRotatef(15.0,1.0,0.0,0.0);
//把太阳画成一个黄色的线框球体
GL3F(1.0,1.0,0.0);
(1.0,15,15);
//画地球
//首先把它放在太阳周围
//使用DayOfYear确定其位置
glRotatef(360.0*DayOfYear/365.0,0.0,1.0,0.0);
glTranslatef(4.0,0.0,0.0);
glPushMatrix();//保存矩阵状态
//第二,绕地轴旋转地球。
//使用HourOfDay确定其旋转。
glRotatef(360.0*小时/天/24.0,0.0,1.0,0.0);
//第三,将地球绘制为线框球体。
GL3F(0.2,0.2,1.0);
球状(0.4,10,10);
glPopMatrix();//还原矩阵状态
//画月亮。
//使用DayOfYear控制其绕地球旋转
glRotatef(360.0*12.0*DayOfYear/365.0,0.0,1.0,0.0);
glTranslatef(0.7,0.0,0.0);
GL3F(0.3,0.7,0.3);
(0.1,5,5);
//刷新管道,并交换缓冲区
glFlush();
glutSwapBuffers();
如果(单步){
spinMode=GL_假;
}
glutPostRedisplay();//为动画目的请求重新绘制
}
//初始化OpenGL的渲染模式
void OpenGLInit(void)
{
glShadeModel(GLU平面);
glClearColor(0.0,0.0,0.0,0.0);
glClearDepth(1.0);
glEnable(GLU深度试验);
}
//调整窗口大小时调用ResizeWindow
静态无效大小调整窗口(int w,int h)
{
浮体;
h=(h==0)?1:h;
w=(w==0)?1:w;
glViewport(0,0,w,h);//视图端口使用整个窗口
aspectRatio=(浮动)w/(浮动)h;
//设置投影视图矩阵(不是很好!)
glMatrixMode(GL_投影);
glLoadIdentity();
gluPerspective(60.0,aspectRatio,1.0,30.0);
//选择Modelview矩阵
glMatrixMode(GLU模型视图);
}
//主要程序
//设置OpenGL,连接回调,并启动主循环
int main(int argc,字符**argv)
{
//需要为动画增加两倍缓冲区
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_双精度| GLUT_RGB | GLUT_深度);
//创建并定位图形窗口
glutInitWindowPosition(0,0);
glutInitWindowSize(600360);
glutCreateWindow(“太阳系演示”);
//初始化OpenGL。
OpenGLInit();
//设置按键的回调函数
键盘功能(按键功能);
glutSpecialFunc(SpecialKeyFunc);
//设置用于调整窗口大小的回调函数
GLUTEFUNC(调整窗口大小);
//用于图形图像重画的回调
glutDisplayFunc(动画);
//启动主循环。glutMainLoop永远不会返回。
glutMainLoop();
return(0);//编译器要求它在这里。(从未到达)
}
下面的代码绘制了文本“Hello world”,并且也起作用:

#include <iostream>

#include <OpenGL/gl.h>

#include <GLUT/glut.h>




void drawBitmapText(char *string,float x,float y,float z) 
{  
    char *c;
    glRasterPos3f(x, y,z);

    for (c=string; *c != '\0'; c++) 
    {
        glutBitmapCharacter(GLUT_BITMAP_TIMES_ROMAN_10, *c);
    }
}

void drawStrokeText(char*string,int x,int y,int z)
{
    char *c;
    glPushMatrix();
    glTranslatef(x, y+8,z);
    // glScalef(0.09f,-0.08f,z);

    for (c=string; *c != '\0'; c++)
    {
        glutStrokeCharacter(GLUT_STROKE_ROMAN , *c);
    }
    glPopMatrix();
}





void reshape(int w,int h) 
{ 

    glViewport(0,0,w,h); 
    glMatrixMode(GL_PROJECTION); 
    glLoadIdentity(); 
    gluOrtho2D(0,w,h,0); 
    glMatrixMode(GL_MODELVIEW); 
    glLoadIdentity(); 

}


void render(void)
{ 


    glClear(GL_COLOR_BUFFER_BIT); 
    glLoadIdentity();

    glColor3f(0,1,0);

    drawBitmapText("Hello world",200,200,0);
    glutSwapBuffers(); 

} 


// Main routine
// Set up OpenGL, hook up callbacks, and start the main loop
int main( int argc, char** argv )
{
    // Need to double buffer for animation
    glutInit(&argc,argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH );

    // Create and position the graphics window
    glutInitWindowPosition( 0, 0 );
    glutInitWindowSize( 600, 360 );
    glutCreateWindow( "Solar System Demo" );




    glutDisplayFunc(render);
    glutIdleFunc(render);
    glutReshapeFunc(reshape); 



    // Start the main loop.  glutMainLoop never returns.
    glutMainLoop(  );

    return(0);          // Compiler requires this to be here. (Never reached)
}
#包括
#包括
#包括
void drawBitmapText(字符*字符串、浮点x、浮点y、浮点z)
{  
char*c;
glRasterPos3f(x,y,z);
对于(c=string;*c!='\0';
#include <iostream>

#include <OpenGL/gl.h>

#include <GLUT/glut.h>


void OpenGLInit(void);

static void Animate(void );
static void Key_r(void );
static void Key_s(void );
static void Key_up(void );
static void Key_down(void );
static void ResizeWindow(int w, int h);

static void KeyPressFunc( unsigned char Key, int x, int y );
static void SpecialKeyFunc( int Key, int x, int y );





static GLenum spinMode = GL_TRUE;
static GLenum singleStep = GL_FALSE;

// These three variables control the animation's state and speed.
static float HourOfDay = 0.0;
static float DayOfYear = 0.0;
static float AnimateIncrement = 24.0;  // Time step for animation (hours)

// glutKeyboardFunc is called below to set this function to handle
//      all normal key presses.  
static void KeyPressFunc( unsigned char Key, int x, int y )
{
    switch ( Key ) {
        case 'R':
        case 'r':
            Key_r();
            break;
        case 's':
        case 'S':
            Key_s();
            break;
        case 27:    // Escape key
            exit(1);
    }
}

// glutSpecialFunc is called below to set this function to handle
//      all special key presses.  See glut.h for the names of
//      special keys.
static void SpecialKeyFunc( int Key, int x, int y )
{
    switch ( Key ) {
        case GLUT_KEY_UP:       
            Key_up();
            break;
        case GLUT_KEY_DOWN:
            Key_down();
            break;
    }
}


static void Key_r(void)
{
    if ( singleStep ) {         // If ending single step mode
        singleStep = GL_FALSE;
        spinMode = GL_TRUE;     // Restart animation
    }
    else {
        spinMode = !spinMode;   // Toggle animation on and off.
    }
}

static void Key_s(void)
{
    singleStep = GL_TRUE;
    spinMode = GL_TRUE;
}

static void Key_up(void)
{
    AnimateIncrement *= 2.0;            // Double the animation time step
}

static void Key_down(void)
{
    AnimateIncrement /= 2.0;            // Halve the animation time step

}

/*
 * Animate() handles the animation and the redrawing of the
 *      graphics window contents.
 */
static void Animate(void)
{
    // Clear the redering window
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    if (spinMode) {
        // Update the animation state
        HourOfDay += AnimateIncrement;
        DayOfYear += AnimateIncrement/24.0;

        HourOfDay = HourOfDay - ((int)(HourOfDay/24))*24;
        DayOfYear = DayOfYear - ((int)(DayOfYear/365))*365;
    }

    // Clear the current matrix (Modelview)
    glLoadIdentity();

    // Back off eight units to be able to view from the origin.
    glTranslatef ( 0.0, 0.0, -8.0 );

    // Rotate the plane of the elliptic
    // (rotate the model's plane about the x axis by fifteen degrees)
    glRotatef( 15.0, 1.0, 0.0, 0.0 );

    // Draw the sun -- as a yellow, wireframe sphere
    glColor3f( 1.0, 1.0, 0.0 );         
    glutWireSphere( 1.0, 15, 15 );

    // Draw the Earth
    // First position it around the sun
    //      Use DayOfYear to determine its position
    glRotatef( 360.0*DayOfYear/365.0, 0.0, 1.0, 0.0 );
    glTranslatef( 4.0, 0.0, 0.0 );
    glPushMatrix();                     // Save matrix state
    // Second, rotate the earth on its axis.
    //      Use HourOfDay to determine its rotation.
    glRotatef( 360.0*HourOfDay/24.0, 0.0, 1.0, 0.0 );
    // Third, draw the earth as a wireframe sphere.
    glColor3f( 0.2, 0.2, 1.0 );
    glutWireSphere( 0.4, 10, 10);
    glPopMatrix();                      // Restore matrix state

    // Draw the moon.
    //  Use DayOfYear to control its rotation around the earth
    glRotatef( 360.0*12.0*DayOfYear/365.0, 0.0, 1.0, 0.0 );
    glTranslatef( 0.7, 0.0, 0.0 );
    glColor3f( 0.3, 0.7, 0.3 );
    glutWireSphere( 0.1, 5, 5 );

    // Flush the pipeline, and swap the buffers
    glFlush();
    glutSwapBuffers();

    if ( singleStep ) {
        spinMode = GL_FALSE;
    }

    glutPostRedisplay();        // Request a re-draw for animation purposes

}

// Initialize OpenGL's rendering modes
void OpenGLInit(void)
{
    glShadeModel( GL_FLAT );
    glClearColor( 0.0, 0.0, 0.0, 0.0 );
    glClearDepth( 1.0 );
    glEnable( GL_DEPTH_TEST );
}

// ResizeWindow is called when the window is resized
static void ResizeWindow(int w, int h)
{
    float aspectRatio;
    h = (h == 0) ? 1 : h;
    w = (w == 0) ? 1 : w;
    glViewport( 0, 0, w, h );   // View port uses whole window
    aspectRatio = (float)w/(float)h;

    // Set up the projection view matrix (not very well!)
    glMatrixMode( GL_PROJECTION );
    glLoadIdentity();
    gluPerspective( 60.0, aspectRatio, 1.0, 30.0 );

    // Select the Modelview matrix
    glMatrixMode( GL_MODELVIEW );
}




void drawBitmapText(char *string,float x,float y,float z) 
{  
    char *c;
    glRasterPos3f(x, y,z);

    for (c=string; *c != '\0'; c++) 
    {
        glutBitmapCharacter(GLUT_BITMAP_TIMES_ROMAN_10, *c);
    }
}

void drawStrokeText(char*string,int x,int y,int z)
{
    char *c;
    glPushMatrix();
    glTranslatef(x, y+8,z);
    // glScalef(0.09f,-0.08f,z);

    for (c=string; *c != '\0'; c++)
    {
        glutStrokeCharacter(GLUT_STROKE_ROMAN , *c);
    }
    glPopMatrix();
}





void reshape(int w,int h) 
{ 

    glViewport(0,0,w,h); 
    glMatrixMode(GL_PROJECTION); 
    glLoadIdentity(); 
    gluOrtho2D(0,w,h,0); 
    glMatrixMode(GL_MODELVIEW); 
    glLoadIdentity(); 

}


void render(void)
{ 


    glClear(GL_COLOR_BUFFER_BIT); 
    glLoadIdentity();

    glColor3f(0,1,0);

    drawBitmapText("Hello world",200,200,0);
    glutSwapBuffers(); 

} 


// Main routine
// Set up OpenGL, hook up callbacks, and start the main loop
int main( int argc, char** argv )
{
    // Need to double buffer for animation
    glutInit(&argc,argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH );

    // Create and position the graphics window
    glutInitWindowPosition( 0, 0 );
    glutInitWindowSize( 600, 360 );
    glutCreateWindow( "Solar System Demo" );

    // Initialize OpenGL.
    OpenGLInit();

    // Set up callback functions for key presses
    glutKeyboardFunc( KeyPressFunc );
    glutSpecialFunc( SpecialKeyFunc );

    // Set up the callback function for resizing windows
    glutReshapeFunc( ResizeWindow );

    // Callback for graphics image redrawing
    glutDisplayFunc( Animate );



    glutDisplayFunc(render);
    glutIdleFunc(render);
    glutReshapeFunc(reshape); 


    // Start the main loop.  glutMainLoop never returns.
    glutMainLoop(  );

    return(0);          // Compiler requires this to be here. (Never reached)
}
glutKeyboardFunc( KeyPressFunc );
glutSpecialFunc( SpecialKeyFunc );
glutReshapeFunc( ResizeWindow );
glutDisplayFunc( Animate );
glutDisplayFunc(render);
glutIdleFunc(render);