OpenGL黑屏/没有绘制?

时间:2011-12-22 20:46:01

标签: c opengl glut

为什么这段代码会产生黑屏(没有画出来......)?

我正在创建一个Pong克隆,但如果不让它工作,我就无法继续。

#include <GL/glut.h>

struct Rectangle {
    int x;
    int y;
    int width;
    int height;
};

struct Ball {
    int x;
    int y;
    int radius;
};

typedef struct Rectangle Rectangle;
typedef struct Ball Ball;

Rectangle rOne, rTwo;
Ball ball;

void display(void);
void reshape(int w, int h);
void drawRectangle(Rectangle *r);

int main(int argc, char* argv[]) {

    glutInit(&argc,argv);
    glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGB);
    glutInitWindowSize(800,600);
    glutCreateWindow("Pong");
    gluOrtho2D(0,0,800.0,600.0);

    rOne.x = 100;
    rOne.y = 100;
    rOne.width = 100;
    rOne.height = 50;   

    glutDisplayFunc(display);
    glutReshapeFunc(reshape);
    glutMainLoop();

    return 0;

}

void display(void) {
    glClear(GL_COLOR_BUFFER_BIT);

    drawRectangle(&rOne);

    glFlush();
    glutSwapBuffers();
}

void reshape(int w, int h) {
    glViewport(0,0,w,h);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluOrtho2D(0,0,(GLfloat)w,(GLfloat)h);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
}

void drawRectangle(Rectangle *r) {
    glBegin(GL_QUADS);
        glVertex2i(r->x,r->y);
    glVertex2i(r->x+(r->width-1),r->y);
    glVertex2i(r->x+(r->width-1),r->y+(r->height-1));
    glVertex2i(r->x,r->y+(r->height-1));
    glEnd();
}

2 个答案:

答案 0 :(得分:5)

您正在请求零宽度的正投影:

gluOrtho2D(0,0,(GLfloat)w,(GLfloat)h);

这可能就是你的意思:

gluOrtho2D(0,(GLfloat)w,0,(GLfloat)h);

示例:

#include <GL/glut.h>

typedef struct {
    int x;
    int y;
    int width;
    int height;
} Rect;

typedef struct {
    int x;
    int y;
    int radius;
} Ball;

Rect rOne, rTwo;
Ball ball;

void display(void);
void reshape(int w, int h);
void drawRectangle(Rect *r);

int main(int argc, char* argv[]) 
{
    glutInit(&argc,argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
    glutInitWindowSize(800,600);
    glutCreateWindow("Pong");

    rOne.x = 100;
    rOne.y = 100;
    rOne.width = 100;
    rOne.height = 50;   

    glutDisplayFunc(display);
    glutReshapeFunc(reshape);
    glutMainLoop();

    return 0;
}

void display(void) 
{
    glClear(GL_COLOR_BUFFER_BIT);

    drawRectangle(&rOne);

    glFlush();
    glutSwapBuffers();
}

void reshape(int w, int h)
{
    glViewport(0,0,w,h);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluOrtho2D(0,(GLfloat)w,0,(GLfloat)h);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
}

void drawRectangle(Rect *r) 
{
    glBegin(GL_QUADS);
    glVertex2i(r->x,r->y);
    glVertex2i(r->x+(r->width-1),r->y);
    glVertex2i(r->x+(r->width-1),r->y+(r->height-1));
    glVertex2i(r->x,r->y+(r->height-1));
    glEnd();
}

答案 1 :(得分:3)

你的问题在于:

gluOrtho2D(0,0,800.0,600.0);

gluOrtho2D与glViewport不同。 gluOrtho2D的参数是:

gluOrtho2D(left, right, bottom, top);

所以你必须把它称为

gluOrtho(0, w, 0, h);