我正在尝试使用LWJGL通过java学习opengl。在尝试编译着色器程序时,我收到错误
java.lang.Exception: Error compiling shading code: 0:1(1): preprocessor error: Illegal non-directive after #
我对C只有Java一无所知。
#version 330
layout (location =0) in vec3 position;
void main()
{
gl_Position = vec4(position, 1.0);
}
#version 330
out vec4 fragColor;
main()
{
fragColor = vec4(0.0, 0.5, 0.5, 1.0);
}
这是我的两个着色器文件。
这是加载它们的代码:
public void createVertexShader(String code) throws Exception{
vertexShaderId = createShader(code,GL_VERTEX_SHADER);
}
public void createFragmentShader(String code) throws Exception{
fragmentShaderId = createShader(code,GL_FRAGMENT_SHADER);
}
protected int createShader(String code, int type) throws Exception{
int shaderId = glCreateShader(type);
if(shaderId == 0){
throw new Exception("error createing shader. type: "+type);
}
glShaderSource(shaderId,code);
glCompileShader(shaderId);
if(glGetShaderi(shaderId, GL_COMPILE_STATUS) == 0){
throw new Exception("Error compiling shading code: "+glGetShaderInfoLog(shaderId,1024));
}
glAttachShader(programId, shaderId);
return shaderId;
}
public static String loadResource(String fileName) throws Exception {
StringBuilder result = new StringBuilder();
try (InputStream in = Utils.class.getClass().getResourceAsStream(fileName);
Scanner scanner = new Scanner(in, "UTF-8")) {
while(scanner.hasNext()){
result.append( scanner.next() );
}
}
return result.toString();
我不明白编译这个简单文件需要做些什么。
StringBuilder builder = new StringBuilder();
try (InputStream in = new FileInputStream(fileName);
BufferedReader reader = new BufferedReader(new InputStreamReader(in))) {
String line;
while ((line = reader.readLine()) != null) {
builder.append(line).append("\n");
}
} catch (IOException ex) {
throw new RuntimeException("Failed to load a shader file!"
+ System.lineSeparator() + ex.getMessage());
}
String source = builder.toString();
return source;
我已将其更改为这是一个在另一个程序中工作的着色器加载程序。然而,在这里,我仍然得到了同样未被认可的新标识符。 怎么了?
答案 0 :(得分:3)
您阅读文件的方式会丢弃包括换行符在内的所有空格。您收到错误,因为着色器编译器有效地读取
version330layout(....
由于空格和换行对于glsl着色器非常重要,因此请停止使用扫描仪读取整个文件(或者至少不要逐字阅读)。看看this answers如何在不丢失空格的情况下阅读整个文件。