2017-08-27 75 views
0

我想通過使用LWJGL的Java學習opengl。當試圖編譯着色器程序時,我得到錯誤GLSL:非法非指令後#

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

是的,然後它說:0:1(1):錯誤:語法錯誤,意外NEW_IDENTIFIER – madmax

回答

3

讀取文件的方式會丟棄包括換行符在內的所有空格。你會得到錯誤,因爲着色器編譯器有效地讀取類似於 version330layout(....

由於空格和換行符對於使用掃描器(或至少不逐字讀取它)的glsl着色器停止讀取整個文件很重要。看看this answers如何閱讀整個文件而不會失去空格。

+0

謝謝,我嘗試加載文件的另一種方式,在另一個程序中工作。我仍然得到相同的意外的新標識符錯誤 – madmax