OpenGl 显示动画并绘制文本

OpenGl display animation and draw text

本文关键字:绘制 文本 动画 显示 OpenGl      更新时间:2023-10-16

我想展示太阳系并绘制一个简单的文字,上面写着"Hello world":

下面的代码显示了太阳系,一切正常:

#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)
}

下面的代码绘制文本" 你好世界 "并且也可以工作:

#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 != ''; 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 != ''; 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)
}

我试图将它们一起使用来显示太阳系并绘制文本,但是

我得到一个空白的黑屏:

#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 != ''; 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 != ''; 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)
}

main() 中的这些行会导致问题:

glutKeyboardFunc( KeyPressFunc );
glutSpecialFunc( SpecialKeyFunc );
glutReshapeFunc( ResizeWindow );
glutDisplayFunc( Animate );
glutDisplayFunc(render);
glutIdleFunc(render);

glutDisplayFunc() 覆盖 GLUT 内部的函数指针。所以只有 render() 函数被调用,而不是 Animate()。

这里的第二个问题:Idle 函数也是 render(),所以它被调用了两次。与重塑功能相同。

您需要组合 ResizeWindow() 和 reshape() 函数,然后是 render()

和 Animate() 函数,然后删除 glutIdleFunc 调用,因为它一切都已经在 render() 中完成。