加载着色器后清除内存

时间:2014-05-06 13:56:41

标签: c++ opengl glsl shader

虽然我做了建议的步骤,但是我得到了内存泄漏。我按如下方式加载和删除着色器:

glCreateShader
glShaderSource
glCompileShader
glAttachShader
glLinkProgram
glUseProgram
glDetachShader
glDeleteShader
glUseProgram(0);
glDeleteProgram
当我在循环中执行所有这些步骤时,

glLingProgram()似乎会导致泄漏。下面是我的测试代码。你能帮我解决一下这个问题吗? (该代码基于http://opengl-tutorial.org/)上的教程。

编辑:我认为只有在顶点着色器包含attribute类型时才会出现这种情况。

for (int i = 0; i < 1000; i++) {
    GLuint VertexShaderID = glCreateShader(GL_VERTEX_SHADER);
    GLuint FragmentShaderID = glCreateShader(GL_FRAGMENT_SHADER);

    std::string VertexShaderCode;
    std::ifstream VertexShaderStream("VertexShader.vs", std::ios::in);
    if(VertexShaderStream.is_open()) {
        std::string Line = "";
        while(getline(VertexShaderStream, Line))
            VertexShaderCode += "\n" + Line;
        VertexShaderStream.close();
    }
    else {
        printf("Cannot open vertex shader!");
        getchar();
        return 0;
    }

    std::string FragmentShaderCode;
    std::ifstream FragmentShaderStream("FragmentShader.fs", std::ios::in);
    if(FragmentShaderStream.is_open()) {
        std::string Line = "";
        while(getline(FragmentShaderStream, Line)) {
            FragmentShaderCode += "\n" + Line;
        }
        FragmentShaderStream.close();
    }
    else {
        printf("Cannot open fragment shader!");
        getchar();
        return 0;
    }

    char const * VertexSourcePointer = VertexShaderCode.c_str();
    glShaderSource(VertexShaderID, 1, &VertexSourcePointer , NULL);
    glCompileShader(VertexShaderID);

    char const * FragmentSourcePointer = FragmentShaderCode.c_str();
    glShaderSource(FragmentShaderID, 1, &FragmentSourcePointer , NULL);
    glCompileShader(FragmentShaderID);

    GLuint ProgramID = glCreateProgram();

    glAttachShader(ProgramID, VertexShaderID);
    glAttachShader(ProgramID, FragmentShaderID);

    glLinkProgram(ProgramID);

    glUseProgram(ProgramID);

    glDetachShader(ProgramID, VertexShaderID);
    glDetachShader(ProgramID, FragmentShaderID);

    glDeleteShader(VertexShaderID);
    glDeleteShader(FragmentShaderID);

    glUseProgram(0);

    glDeleteProgram(ProgramID);
}

1 个答案:

答案 0 :(得分:0)

您应该只在开头加载着色器。只有glUseProgram用于渲染循环。

使用着色器的标准模板如下:

glCreateProgram
glCreateShader
glShaderSource
glCompileShader
glAttachShader
glLinkProgram <- after this line opengl got everything it needs, 
                 you can free shader resources
glDetachShader
glDeleteShader

for{//render loop
   glUseProgram
   //...drawing operations
   glUseProgram(0);
}

glDeleteProgram