使用面向对象的方法加载着色器

时间:2012-08-26 11:57:42

标签: c++ string opengl

我的应用程序将成为使用OpenGL 4.2GLFWGLEW的OpenGL游戏。问题是关于从文件加载GLSL着色器。我为所有与着色器相关的任务使用了一个名为ShadersObject的类。

class ShadersObject
{
public:
    // ...
private:
    // ...
    void LoadFile(string Name, string Path);
    string FolderPath;
    Shaders ShaderList;
};

该类使用ShaderObject s的地图来存储着色器。

enum ShaderType{ Vertex = GL_VERTEX_SHADER,
                 Geometry = GL_GEOMETRY_SHADER,
                 Fragment = GL_FRAGMENT_SHADER };

struct ShaderObject
{
    const GLchar* File;
    ShaderType Type;
    GLuint Shader;
    // ...
};

typedef map<string, ShaderObject> Shaders;

以下方法我应该将GLSL着色器的源代码从文件加载到ShaderObject中的ShaderList。因此,它使用Path到文件和着色器的Name,因为ShaderList地图中的字符串键已命名。

void ShadersObject::LoadFile(string Name, string Path)
{
    string FilePath = FolderPath + Path;
    ifstream Stream(FilePath);

    if(Stream.is_open())
    {
        cout << "Loading Shader from " << FilePath << endl;

        string Output;
        Stream.seekg(0, ios::end);   
        Output.reserve(Stream.tellg());
        Stream.seekg(0, ios::beg);
        Output.assign((istreambuf_iterator<char>(Stream)),istreambuf_iterator<char>());

        // this line doesn't compile
        strcpy(ShaderList[Name].File, Output.c_str());
    }
    else cout << "Can not load Shader from " << FilePath << endl;
}

我想使用ShaderList[Name].File中的值来使用glShaderSourceglCompileShader来加载和编译着色器的另一种方法。其中glShaderSource需要指向持有源代码的const GLchar*的指针。在我的情况下,这将是&ShaderList[Name].File

前段时间我使用ShaderList[Name].File = Output.c_str();而不是现在不编译的行。结果是只有指针保存在ShaderList中,并且退出方法后源代码消失了。这就是我尝试使用strcpy的原因,但此函数不接受const GLchar*作为参数类型。

如何将读取的文件保存到我的班级成员中?

1 个答案:

答案 0 :(得分:3)

这不是一个复杂的问题:存储字符串。将Output存储在ShadersObject课程中。如果您需要致电glShaderSource,请将其转换为const GLchar* string::c_str

或者更好;不要存储其中任何一个; OpenGL将在着色器对象中保留着色器字符串。您可以通过API从OpenGL查询着色器字符串。因此,存储OpenGL已经存储的着色器对象实际上没有任何意义。