Reputation: 615
I am trying to learn opengl through java using LWJGL. When trying to compile shader programs I get the error
java.lang.Exception: Error compiling shading code: 0:1(1): preprocessor error: Illegal non-directive after #
I know nothing about C only 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);
}
These are my two shader files.
this is the code that loads them:
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();
I don't understand what I need to do to compile this simple file.
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;
I've changed it to this which is a shader loader that works in another program. Yet here I am still getting the same unexcpected New Identifier. What the hell?
Upvotes: 0
Views: 553
Reputation: 22167
The way you read the file discards all whitespaces including newlines. You get the error because the shader compiler effectively reads something like
version330layout(....
Since whitespaces and newlines are important for a glsl shader stop reading whole files with a Scanner (or at least don't read it word by word). Have a look at this answers on how to read whole files without loosing whitespaces.
Upvotes: 3