1

好的,我正在尝试学习 OpenGL 3.x,我曾经使用旧界面,但效果并不好。我使用 SDL2 进行窗口和输入。

我认为代码应该做的是在蓝色背景上绘制一个红色三角形。问题是它有时只这样做,实际上它似乎是完全随机的,有时它会这样做,有时它只是显示一个黑色窗口。

我不知道为什么。

#include "SDL2/SDL.h"
#include "GL/glew.h"

GLuint makeShader(const char * shader, GLint t){

    //---- Make Shader ----
    GLuint s = glCreateShader(t);
    glShaderSource(s, 1, &shader, NULL);
    glCompileShader(s);

    //---- Get Error Msg ----
    int l=0;
    glGetShaderiv(s, GL_INFO_LOG_LENGTH, &l);
    char *msg = new char [l+1];
    glGetShaderInfoLog(s, l, NULL, msg);

    printf("Shader MSG: %s", msg);
    delete [] msg;

    return s;

}

int main(){

    //----Init SDL & GL Context----
    SDL_Init(SDL_INIT_EVERYTHING);
    SDL_Window *screen = SDL_CreateWindow("My Game Window",
                          SDL_WINDOWPOS_UNDEFINED,
                          SDL_WINDOWPOS_UNDEFINED,
                          //1024, 768,
                          640, 480,
                          SDL_WINDOW_OPENGL);
    SDL_GLContext glContext = SDL_GL_CreateContext(screen);
    SDL_Event e;


    //----Init GLEW---
    glewExperimental=true; 
    GLenum err = glewInit();
    if(GLEW_OK != err)
        fprintf(stderr, "Error: %s\n", glewGetErrorString(err));


    //----VAO----
    GLuint VertexArrayID;
    glGenVertexArrays(1, &VertexArrayID);
    glBindVertexArray(VertexArrayID);


    //----Make Shaders----
    const char *vscr = "#version 330 core\nlayout(location = 0) in vec4 position;\nvoid main(){gl_Position = position * 0.5; gl_Position.w = 1.0;}";
    GLuint vshader = makeShader(vscr, GL_VERTEX_SHADER);

    const char *fscr = "#version 330 core\nout vec3 color;\nvoid main(){ color = vec3(1,0,0);}";
    GLuint fshader = makeShader(fscr, GL_FRAGMENT_SHADER);

    GLuint ProgramID = glCreateProgram();
    glAttachShader(ProgramID, vshader);
    glAttachShader(ProgramID, fshader);
    glLinkProgram(ProgramID);


    // ----make geometry----
     static const GLfloat g_vertex_buffer_data[] = {
       -1.0f, -1.0f, 0.0f,
        1.0f, -1.0f, 0.0f,
        0.0f,  1.0f, 0.0f,
    };

    GLuint vertexbuffer;
    glGenBuffers(1, &vertexbuffer);
    glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
    glBufferData(GL_ARRAY_BUFFER, sizeof(g_vertex_buffer_data), g_vertex_buffer_data, GL_STATIC_DRAW);

    glViewport(0,0,640,480);
    glClearColor(0.0f, 0.0f, 1.0f, 0.0f);

    //----MAIN LOOP----
    while(1){

        glClear(GL_COLOR_BUFFER_BIT);
        SDL_PollEvent(&e);

        glUseProgram(ProgramID);

        glEnableVertexAttribArray(0);
        glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
        glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (void*)0);

        glDrawArrays(GL_TRIANGLES, 0, 3);
        glDisableVertexAttribArray(0);

       glFlush();
       SDL_GL_SwapWindow(screen);

       if(e.type == SDL_QUIT)
            break;

    }

    SDL_GL_DeleteContext(screen);
    return 0;
 }
4

0 回答 0