3

我正在尝试学习如何将 SDL 与 OpenGL 一起使用,并将 GLEW 用于扩展方法。据我所知,从SDL角的Using OpenGL with SDL等页面可以看出,以下代码应该可以工作

#include <glew.h>
#include <SDL.h>

#include <cstdlib>

int main(int argc, char *argv[]) {
    if (SDL_Init( SDL_INIT_EVERYTHING ) != 0) exit(EXIT_FAILURE);
    if (SDL_GL_LoadLibrary( NULL ) != 0) exit(EXIT_FAILURE);
    if (SDL_SetVideoMode(640, 480, 0, SDL_OPENGL) == NULL) exit(EXIT_FAILURE);
    if (glewInit() != GLEW_OK) exit(EXIT_FAILURE);

    glViewport(0, 0, 640, 480);

    while (1) {
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();
        gluPerspective(50.0, 1.0, 0.1, 1000.0);

        glMatrixMode(GL_MODELVIEW);
        glLoadIdentity();
        gluLookAt(0.0, 0.0, 3.0, 0.0, 0.0, 2.0, 0.0, 1.0, 0.0);

        glPolygonMode(GL_FRONT, GL_FILL);

        glBegin(GL_QUADS);
            glColor3f(1, 0, 0); glVertex3f(0, 0, 0);
            glColor3f(1, 1, 0); glVertex3f(3, 0, 0);
            glColor3f(1, 0, 1); glVertex3f(3, 3, 0);
            glColor3f(1, 1, 1); glVertex3f(0, 3, 0);
        glEnd();

        SDL_GL_SwapBuffers();
    }

    SDL_Quit();
    return 0;
}

但是,它只是在尝试调用时在第 12 行出现段错误glViewport。这是在 OS X 10.7 上编译的:

clang++ -g $(pkg-config --cflags sdl gl glu glew) -o test test.cpp $(pkg-config --libs sdl gl glu glew)

SDL 是 1.2.14 版,GLEW 是 1.7.0 版。

4

1 回答 1

0

尝试将投影和模型视图部分放在 while 循环之外,并将 glViewport 放在投影之后:

#include <glew.h>
#include <SDL.h>

#include <cstdlib>

int main(int argc, char *argv[]) {
    if (SDL_Init( SDL_INIT_EVERYTHING ) != 0) exit(EXIT_FAILURE);
    if (SDL_GL_LoadLibrary( NULL ) != 0) exit(EXIT_FAILURE);
    if (SDL_SetVideoMode(640, 480, 0, SDL_OPENGL) == NULL) exit(EXIT_FAILURE);
    if (glewInit() != GLEW_OK) exit(EXIT_FAILURE);

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glViewport(0, 0, 640, 480);
    gluPerspective(50.0, 1.0, 0.1, 1000.0);

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    gluLookAt(0.0, 0.0, 3.0, 0.0, 0.0, 2.0, 0.0, 1.0, 0.0);

    while (1) {
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        glPolygonMode(GL_FRONT, GL_FILL);

        glBegin(GL_QUADS);
            glColor3f(1, 0, 0); glVertex3f(0, 0, 0);
            glColor3f(1, 1, 0); glVertex3f(3, 0, 0);
            glColor3f(1, 0, 1); glVertex3f(3, 3, 0);
            glColor3f(1, 1, 1); glVertex3f(0, 3, 0);
        glEnd();

        SDL_GL_SwapBuffers();
    }

    SDL_Quit();
    return 0;
}
于 2013-10-28T08:31:12.660 回答