2015-05-26 73 views
2

我试图在我的Linux机器上用Radeon HD 5470视频卡和fglrx AMD驱动程序编译简单着色器。GLSL Shader编译错误

我的顶点着色器代码

#version 330 core 

layout(location = 0) in vec3 vertexPosition_modelspace; 

void main() 
{ 

    gl_Position.xyz = vertexPosition_modelspace; 
    gl_Position.w = 1.0; 

} 

从文件中读取代码

void Shader::load_from_file(const std::string& file) 
{ 
    std::ifstream is(file, std::ios_base::in); 
    if (is.is_open()) { 
     std::string line{""}; 
     while(std::getline(is, line)) { 
      // program_code_ is a std::string member 
      program_code_ += "\n" + line; 
     } 

     is.close(); 
    } else { 
     throw Exception("Could not open shader source code file"); 
    }  
} 

尝试编译

void Shader::build_shader() 
{ 
    const GLchar* tmp = program_code_.c_str();  
    const GLint tmplen = program_code_.length(); 

    std::cout << "Shader code: " << tmp << std::endl; 

    glShaderSource(shader_handler_, 1, &tmp, &tmplen); 
    CHECK_ERR(); 

    glCompileShader(shader_handler_); 
    CHECK_ERR(); 
    //... 
} 

而且有错误,从glGetShaderInfoLog

Exception caught: Vertex shader failed to compile with the following errors: 
ERROR: 0:1: error(#132) Syntax error: "<" parse error 
ERROR: error(#273) 1 compilation errors. No code generated 

但我打电话glShaderSource之前,我打印到TMP指针的标准输出值,它似乎有效shader代码:

Shader code: 
#version 330 core 

layout(location = 0) in vec3 vertexPosition_modelspace; 

void main() 
{ 

    gl_Position.xyz = vertexPosition_modelspace; 
    gl_Position.w = 1.0; 

} 

我的代码不会从内存中读取垃圾,但我不明白什么是错的。

而且

% glxinfo | grep vertex_program 
% GL_ARB_vertex_program 
+0

你应该追加'line +'\ n“'而不是'\ n”+ line'。 (虽然它可能不会修复错误。) – leemes

+2

另外,为什么你甚至一行一行读取它?你可以[一次读取整个文件](http://stackoverflow.com/questions/2602013/read-whole-ascii-file-into-c-stdstring)。 – leemes

+2

另一个可能的问题是,你只能附加到字符串成员变量,但不清除它。可能是''load_from_file''被多次调用,或者其他原因为什么成员可能在调用之前包含数据? – leemes

回答

1

逐行读取文件中的行,和连接这些线,似乎是问题。

我不知道这是如何引入一个错误,它与您从着色器编译器获得的错误消息相匹配,但正如在注释中所建议的,一次读取整个文件可解决问题。

以下各行通过利用函数rdbufstringstream(你需要#include <sstream>)从一个文件流is读取:

std::ostringstream contents; 
contents << is.rdbuf(); 
program_code_ = contents.str(); 

有关此方法的更多信息,以及其它方法的比较,看http://insanecoding.blogspot.de/2011/11/how-to-read-in-file-in-c.html