Java-Gaming.org    
Featured games (79)
games approved by the League of Dukes
Games in Showcase (477)
Games in Android Showcase (108)
games submitted by our members
Games in WIP (536)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
 
    Home     Help   Search   Login   Register   
Pages: [1]
  ignore  |  Print  
  VBOs and Shaders in JOGL  (Read 6210 times)
0 Members and 1 Guest are viewing this topic.
Offline foota

Senior Newbie





« Posted 2011-08-01 13:25:12 »

So I got the hang of immediate mode drawing and tried doing some basic landscape rendering with it but was not pleased with the speed so I decided to try my hand with VBOs, then having conquered VBOs I decided to try adding shaders to that, and that's where I ran into serious trouble. I've been trying the last few days to get the below code to work and it compiles fine, but opengl gives me a 1281 error

this code goes in the realmain class
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
58  
59  
60  
61  
62  
63  
64  
65  
66  
67  
68  
69  
70  
71  
72  
73  
74  
75  
76  
77  
78  
79  
80  
81  
82  
83  
84  
85  
86  
87  
88  
89  
90  
91  
92  
93  
94  
95  
96  
97  
98  
99  
100  
101  
102  
103  
104  
105  
106  
107  
108  
109  
110  
111  
112  
113  
114  
115  
116  
117  
118  
119  
120  
121  
122  
123  
import javax.media.opengl.GL;
import javax.media.opengl.GL2;
import javax.media.opengl.GL3;
import javax.media.opengl.GLAutoDrawable;
import javax.media.opengl.GLCapabilities;
import javax.media.opengl.GLEventListener;
import javax.media.opengl.GLProfile;
import javax.media.opengl.awt.GLCanvas;
import javax.media.opengl.glu.GLU;
import javax.swing.*;

import com.jogamp.opengl.util.FPSAnimator;

import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;

public class RealMain{    
   public static void main(String[] args)    {        
      JFrame frame = new JFrame("JOGL test");
      frame.setSize(640, 480);
      GLProfile glProfile = GLProfile.getDefault();
      GLCapabilities glCapabilities = new GLCapabilities(glProfile);
      GLCanvas canvas = new GLCanvas(glCapabilities);        
      frame.add(canvas);      
      canvas.addGLEventListener(new JOGLRenderer());  
      FPSAnimator animator = new FPSAnimator(canvas, 60);  
      animator.add(canvas);
      animator.start();      
      frame.addWindowListener(new WindowAdapter(){          
         public void windowClosing(WindowEvent e)            {  
            System.exit(0);            }        });  
      frame.setVisible(true);  
   }  
   private static class JOGLRenderer implements GLEventListener    {
      ShaderProgram shader;
      public void init(GLAutoDrawable drawable){



         shader = new ShaderProgram(drawable, new File("bin/vert.txt"), new File("bin/frag.txt"));

         //setup opengl
        GL3 gl = drawable.getGL().getGL3();      
         gl.glClearColor(0.2f, 0.2f, 0.0f, 0.0f);        
         gl.glClearDepth(1.0f);          
         gl.glEnable(GL.GL_DEPTH_TEST);        
         gl.glDepthFunc(GL.GL_LEQUAL);          
         gl.glHint(GL2.GL_PERSPECTIVE_CORRECTION_HINT, GL.GL_NICEST);  

         // Create vertex data        
        float[] vertexData = new float[]{
               -1f, 1f, -2.0f, //0
              1f, 1f, -2.0f, //1
              -1f, -1f, -2.0f, //2
              1f, -1f, -2.0f, //3
        };
         ByteBuffer vertexByteBuffer = ByteBuffer.allocateDirect(7 * 4 * 4);            
         vertexByteBuffer.order(ByteOrder.nativeOrder());      
         FloatBuffer vertexBuffer = vertexByteBuffer.asFloatBuffer();          
         vertexBuffer.put(vertexData);

         // Create vertex buffer              
        int[] vertexBufferId = new int[1];        
         gl.glGenBuffers(1, vertexBufferId, 0);        
         gl.glBindBuffer(GL2.GL_ARRAY_BUFFER, vertexBufferId[0]);      
         gl.glBufferData(GL2.GL_ARRAY_BUFFER, 48, null, GL2.GL_DYNAMIC_DRAW);
         // Load vertex data into vertex buffer        
        gl.glBufferSubData(GL2.GL_ARRAY_BUFFER, 0, vertexByteBuffer.capacity(), vertexByteBuffer);

         // Create index data          
        int[] indexData = new int[]{0, 1, 2, 3};

         ByteBuffer indexByteBuffer = ByteBuffer.allocateDirect(4 * 4);    
         indexByteBuffer.order(ByteOrder.nativeOrder());
         IntBuffer indexBuffer = indexByteBuffer.asIntBuffer();      
         indexBuffer.put(indexData);

         // Create index buffer    
        int[] indexBufferId = new int[1];      
         gl.glGenBuffers(1, indexBufferId, 0);
         gl.glBindBuffer(GL2.GL_ELEMENT_ARRAY_BUFFER, indexBufferId[0]);          
         gl.glBufferData(GL2.GL_ELEMENT_ARRAY_BUFFER, 16, null, GL2.GL_DYNAMIC_DRAW);      
         // Load index data into index buffer          
        gl.glBufferSubData(GL2.GL_ELEMENT_ARRAY_BUFFER, 0, indexByteBuffer.capacity(), indexByteBuffer);

         

      }
      public void dispose(GLAutoDrawable drawable){}
      public void display(GLAutoDrawable drawable){        
         GL3 gl = drawable.getGL().getGL3();  
         gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT);      


         //gl.glMatrixMode(GL2.GL_MODELVIEW);
        //gl.glLoadIdentity();          
        int stride = 3 * 4; //3 floats per vert * 4 bytes per float


         
         gl.glVertexAttribPointer(gl.glGetAttribLocation(shader.p, "vertex"), 3, gl.GL_FLOAT, false, 20, 0);
         System.out.println(gl.glGetError());
         
         //shader code
        gl.glUseProgram(shader.p);
         gl.glDrawRangeElements(GL2.GL_TRIANGLE_STRIP, 0, 2, 3, GL2.GL_UNSIGNED_INT, 0); //start render at 0 verts go to 3 for a count of 4
        gl.glUseProgram(0);
      }    


      public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height)        {          
         GL3 gl = drawable.getGL().getGL3();    
         GLU glu = new GLU();
         gl.glViewport(0, 0, width, height);  
         glu.gluPerspective(45.0f, (float) width / (float) height, 0.1f, 100.0f);  
      }
   }
}


and this goes in shaderprogram
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
58  
59  
60  
61  
62  
63  
64  
65  
66  
67  
68  
69  
70  
71  
72  
73  
74  
75  
76  
77  
78  
79  
80  
81  
82  
83  
84  
85  
86  
87  
88  
89  
90  
91  
92  
93  
94  
95  
96  
97  
98  
99  
100  
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.Scanner;

import javax.media.opengl.GL;
import javax.media.opengl.GL2;
import javax.media.opengl.GL3;
import javax.media.opengl.GLAutoDrawable;
 
public class ShaderProgram {
   
    public ShaderProgram(GLAutoDrawable drawable, File vertf, File fragf) {
       this.vertf = vertf;
       this.fragf = fragf;
        GL3 gl = drawable.getGL().getGL3();
       
        int p = gl.glCreateProgram();
       
       
        //VERTEX STUFF
       int v = gl.glCreateShader(gl.GL_VERTEX_SHADER);
       
        ArrayList <String> vSourceA = new ArrayList<String>();
        Scanner vert = null;
      try {
         vert = new Scanner(vertf);
      } catch (FileNotFoundException e) {
         System.out.println("Vertex shader file was not found");
      }

      vert.useDelimiter("\n");
     
        while(vert.hasNext()){
           String temp = vert.next() + "\n";
           vSourceA.add(temp);
           System.out.print(temp);
        }
       
        String[] vSource = new String[vSourceA.size()];
        vSource = vSourceA.toArray(vSource);
        int [] lengths= new int[vSource.length];
        for(int i = 0; i < vSource.length; i++){
           lengths[i] = vSource[i].length();
        }
       
        gl.glShaderSource(v, lengths.length, vSource, lengths, 0);        
        gl.glCompileShader(v);
        gl.glAttachShader(p, v);
       
        //FRAGMENT SHADER CODE
       int f = gl.glCreateShader(gl.GL_FRAGMENT_SHADER);
       
        ArrayList <String> fSourceA = new ArrayList<String>();
       
        Scanner frag = null;
      try {
         frag = new Scanner(fragf);
      } catch (FileNotFoundException e) {
         System.out.println("Fragment shader file was not found");
      }
     
     
      frag.useDelimiter("\n");
        while(frag.hasNext()){
           String temp = frag.next() + "\n";
           fSourceA.add(temp);
           System.out.print(temp);
        }
       
        String[] fSource = new String[fSourceA.size()];
        fSource = fSourceA.toArray(fSource);
        lengths= new int[fSource.length];
        for(int i = 0; i < fSource.length; i++){
           lengths[i] = fSource[i].length();
        }
       
        gl.glShaderSource(f, lengths.length, fSource, lengths, 0);        
        gl.glCompileShader(f);
        gl.glAttachShader(p, f);
       
       
        //PROGRAM CODE
       gl.glLinkProgram(p);
        gl.glValidateProgram(p);
        System.out.println(gl.glGetError());
        valid = true;
    }
 
    int p;
    boolean valid = false;
     
    File vertf;
    File fragf;
 
}

frag.txt
1  
2  
3  
4  
5  
6  
7  
8  
#version 150
out vec4 fragmentColor;
void
main()
{
    fragmentColor = vec4(0.0, 1.0, 0.0, 1.0);
}
";

vert.txt
1  
2  
3  
4  
5  
6  
7  
8  
#version 150
in vec3 vertex;
void
main()
{
    gl_Position = vec4(vertex,1.0);
}
";
Offline lhkbob

JGO Knight


Medals: 32



« Reply #1 - Posted 2011-08-01 18:48:26 »

Can you try wrapping your GL3 in a DebugGL3 before you perform any OpenGL operations, that way you'll get an exception right where it fails and it will translate the int error code into a useful string.

Offline foota

Senior Newbie





« Reply #2 - Posted 2011-08-02 00:14:35 »

Hm, I did not know that you could do that that's neat.
So after wrapping gl with DebugGL3 it gives me this error message:
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
Exception in thread "Timer-0" javax.media.opengl.GLException: javax.media.opengl.GLException: Thread[AWT-EventQueue-0,6,main] glGetError() returned the following error codes after a call to glBufferSubData(<int> 0x8892, <long>, <long>, <java.nio.Buffer>): GL_INVALID_VALUE ( 1281 0x501), 
   at jogamp.opengl.awt.AWTThreadingPlugin.invokeOnOpenGLThread(AWTThreadingPlugin.java:98)
   at jogamp.opengl.ThreadingImpl.invokeOnOpenGLThread(ThreadingImpl.java:197)
   at javax.media.opengl.Threading.invokeOnOpenGLThread(Threading.java:164)
   at javax.media.opengl.awt.GLCanvas.maybeDoSingleThreadedWorkaround(GLCanvas.java:767)
   at javax.media.opengl.awt.GLCanvas.display(GLCanvas.java:388)
   at com.jogamp.opengl.util.AWTAnimatorImpl.display(AWTAnimatorImpl.java:74)
   at com.jogamp.opengl.util.AnimatorBase.display(AnimatorBase.java:140)
   at com.jogamp.opengl.util.FPSAnimator$1.run(FPSAnimator.java:125)
   at java.util.TimerThread.mainLoop(Unknown Source)
   at java.util.TimerThread.run(Unknown Source)
Caused by: javax.media.opengl.GLException: Thread[AWT-EventQueue-0,6,main] glGetError() returned the following error codes after a call to glBufferSubData(<int> 0x8892, <long>, <long>, <java.nio.Buffer>): GL_INVALID_VALUE ( 1281 0x501),
   at javax.media.opengl.DebugGL3.checkGLGetError(DebugGL3.java:12595)
   at javax.media.opengl.DebugGL3.glBufferSubData(DebugGL3.java:1409)
   at RealMain$JOGLRenderer.init(RealMain.java:72)
   at jogamp.opengl.GLDrawableHelper.init(GLDrawableHelper.java:155)
   at jogamp.opengl.GLDrawableHelper.init(GLDrawableHelper.java:175)
   at javax.media.opengl.awt.GLCanvas$InitAction.run(GLCanvas.java:856)
   at jogamp.opengl.GLDrawableHelper.invokeGL(GLDrawableHelper.java:356)
   at javax.media.opengl.awt.GLCanvas$DisplayOnEventDispatchThreadAction.run(GLCanvas.java:890)
   at java.awt.event.InvocationEvent.dispatch(Unknown Source)
   at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
   at java.awt.EventQueue.access$000(Unknown Source)
   at java.awt.EventQueue$1.run(Unknown Source)
   at java.awt.EventQueue$1.run(Unknown Source)
   at java.security.AccessController.doPrivileged(Native Method)
   at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
   at java.awt.EventQueue.dispatchEvent(Unknown Source)
   at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
   at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
   at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
   at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
   at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
   at java.awt.EventDispatchThread.run(Unknown Source)

So looking at that error it looks like I managed to break my VBOs while trying to get shaders to work...
Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline gouessej
« Reply #3 - Posted 2011-08-02 00:23:42 »

The error is at RealMain$JOGLRenderer.init(RealMain.java:72).
gl.glBufferSubData(GL2.GL_ARRAY_BUFFER, 0, vertexByteBuffer.capacity(), vertexByteBuffer);

I have a working demo using VBO and shaders to draw Mandelbrot things, I will compare this source code with yours tomorrow. Maybe something is wrong with the stride.

Offline foota

Senior Newbie





« Reply #4 - Posted 2011-08-02 00:33:12 »

Yeah I got that, the error was caused by
            ByteBuffer vertexByteBuffer = ByteBuffer.allocateDirect(7 * 4 * 4);    
which should have been
            ByteBuffer vertexByteBuffer = ByteBuffer.allocateDirect(3 * 4 * 4);    
I'd forgotten to change the buffer size after I removed the color data from the vertices.

But now back to my broken shaders.
new error code is posted below:
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
Exception in thread "Timer-0" javax.media.opengl.GLException: javax.media.opengl.GLException: Thread[AWT-EventQueue-0,6,main] glGetError() returned the following error codes after a call to glGetAttribLocation(<int> 0x0, <java.lang.String>): GL_INVALID_VALUE ( 1281 0x501), 
   at jogamp.opengl.awt.AWTThreadingPlugin.invokeOnOpenGLThread(AWTThreadingPlugin.java:98)
   at jogamp.opengl.ThreadingImpl.invokeOnOpenGLThread(ThreadingImpl.java:197)
   at javax.media.opengl.Threading.invokeOnOpenGLThread(Threading.java:164)
   at javax.media.opengl.awt.GLCanvas.maybeDoSingleThreadedWorkaround(GLCanvas.java:767)
   at javax.media.opengl.awt.GLCanvas.display(GLCanvas.java:388)
   at com.jogamp.opengl.util.AWTAnimatorImpl.display(AWTAnimatorImpl.java:74)
   at com.jogamp.opengl.util.AnimatorBase.display(AnimatorBase.java:140)
   at com.jogamp.opengl.util.FPSAnimator$1.run(FPSAnimator.java:125)
   at java.util.TimerThread.mainLoop(Unknown Source)
   at java.util.TimerThread.run(Unknown Source)
Caused by: javax.media.opengl.GLException: Thread[AWT-EventQueue-0,6,main] glGetError() returned the following error codes after a call to glGetAttribLocation(<int> 0x0, <java.lang.String>): GL_INVALID_VALUE ( 1281 0x501),
   at javax.media.opengl.DebugGL3.checkGLGetError(DebugGL3.java:12595)
   at javax.media.opengl.DebugGL3.glGetAttribLocation(DebugGL3.java:5641)
   at RealMain$JOGLRenderer.display(RealMain.java:105)
   at jogamp.opengl.GLDrawableHelper.display(GLDrawableHelper.java:191)
   at javax.media.opengl.awt.GLCanvas$DisplayAction.run(GLCanvas.java:873)
   at jogamp.opengl.GLDrawableHelper.invokeGL(GLDrawableHelper.java:363)
   at javax.media.opengl.awt.GLCanvas$DisplayOnEventDispatchThreadAction.run(GLCanvas.java:890)
   at java.awt.event.InvocationEvent.dispatch(Unknown Source)
   at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
   at java.awt.EventQueue.access$000(Unknown Source)
   at java.awt.EventQueue$1.run(Unknown Source)
   at java.awt.EventQueue$1.run(Unknown Source)
   at java.security.AccessController.doPrivileged(Native Method)
   at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
   at java.awt.EventQueue.dispatchEvent(Unknown Source)
   at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
   at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
   at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
   at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
   at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
   at java.awt.EventDispatchThread.run(Unknown Source)

and updated code for realmain is below
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
58  
59  
60  
61  
62  
63  
64  
65  
66  
67  
68  
69  
70  
71  
72  
73  
74  
75  
76  
77  
78  
79  
80  
81  
82  
83  
84  
85  
86  
87  
88  
89  
90  
91  
92  
93  
94  
95  
96  
97  
98  
99  
100  
101  
102  
103  
104  
105  
106  
107  
108  
109  
110  
111  
112  
113  
114  
115  
116  
117  
118  
119  
120  
121  
122  
import javax.media.opengl.DebugGL3;
import javax.media.opengl.GL;
import javax.media.opengl.GL2;
import javax.media.opengl.GL3;
import javax.media.opengl.GLAutoDrawable;
import javax.media.opengl.GLCapabilities;
import javax.media.opengl.GLEventListener;
import javax.media.opengl.GLProfile;
import javax.media.opengl.awt.GLCanvas;
import javax.media.opengl.glu.GLU;
import javax.swing.*;

import com.jogamp.opengl.util.FPSAnimator;

import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;

public class RealMain{    
   public static void main(String[] args)    {        
      JFrame frame = new JFrame("JOGL test");
      frame.setSize(640, 480);
      GLProfile glProfile = GLProfile.getDefault();
      GLCapabilities glCapabilities = new GLCapabilities(glProfile);
      GLCanvas canvas = new GLCanvas(glCapabilities);        
      frame.add(canvas);      
      canvas.addGLEventListener(new JOGLRenderer());  
      FPSAnimator animator = new FPSAnimator(canvas, 60);  
      animator.add(canvas);
      animator.start();      
      frame.addWindowListener(new WindowAdapter(){          
         public void windowClosing(WindowEvent e)            {  
            System.exit(0);            }        });  
      frame.setVisible(true);  
   }  
   private static class JOGLRenderer implements GLEventListener    {
      ShaderProgram shader;
      public void init(GLAutoDrawable drawable){



         shader = new ShaderProgram(drawable, new File("bin/vert.txt"), new File("bin/frag.txt"));

         //setup opengl        
        DebugGL3 gl = new DebugGL3( drawable.getGL().getGL3());
         gl.glClearColor(0.2f, 0.2f, 0.0f, 0.0f);        
         gl.glClearDepth(1.0f);          
         gl.glEnable(GL3.GL_DEPTH_TEST);        

         // Create vertex data        
        float[] vertexData = new float[]{
               -1f, 1f, -2.0f, //0
              1f, 1f, -2.0f, //1
              -1f, -1f, -2.0f, //2
              1f, -1f, -2.0f, //3
        };
         ByteBuffer vertexByteBuffer = ByteBuffer.allocateDirect(3 * 4 * 4);            
         vertexByteBuffer.order(ByteOrder.nativeOrder());      
         FloatBuffer vertexBuffer = vertexByteBuffer.asFloatBuffer();          
         vertexBuffer.put(vertexData);

         // Create vertex buffer              
        int[] vertexBufferId = new int[1];        
         gl.glGenBuffers(1, vertexBufferId, 0);        
         gl.glBindBuffer(GL3.GL_ARRAY_BUFFER, vertexBufferId[0]);      
         gl.glBufferData(GL3.GL_ARRAY_BUFFER, 48, (ByteBuffer)null, GL3.GL_DYNAMIC_DRAW);
         // Load vertex data into vertex buffer        
        gl.glBufferSubData(GL3.GL_ARRAY_BUFFER, 0, vertexByteBuffer.capacity(), vertexByteBuffer);

         // Create index data          
        int[] indexData = new int[]{0, 1, 2, 3};

         ByteBuffer indexByteBuffer = ByteBuffer.allocateDirect(4 * 4);
         indexByteBuffer.order(ByteOrder.nativeOrder());
         IntBuffer indexBuffer = indexByteBuffer.asIntBuffer();
         indexBuffer.put(indexData);

         // Create index buffer    
        int[] indexBufferId = new int[1];
         gl.glGenBuffers(1, indexBufferId, 0);
         gl.glBindBuffer(GL3.GL_ELEMENT_ARRAY_BUFFER, indexBufferId[0]);          
         gl.glBufferData(GL3.GL_ELEMENT_ARRAY_BUFFER, 16, (ByteBuffer)null, GL3.GL_DYNAMIC_DRAW);      
         // Load index data into index buffer          
        gl.glBufferSubData(GL3.GL_ELEMENT_ARRAY_BUFFER, 0, indexByteBuffer.capacity(), indexByteBuffer);

         

      }
      public void dispose(GLAutoDrawable drawable){}
      public void display(GLAutoDrawable drawable){        
         DebugGL3 gl = new DebugGL3( drawable.getGL().getGL3());
         gl.glClear(GL3.GL_COLOR_BUFFER_BIT | GL3.GL_DEPTH_BUFFER_BIT);      


         //gl.glMatrixMode(GL2.GL_MODELVIEW);
        //gl.glLoadIdentity();          
        int stride = 3 * 4; //3 floats per vert * 4 bytes per float


         
         gl.glVertexAttribPointer(gl.glGetAttribLocation(shader.p, "vertex"), 3, GL3.GL_FLOAT, false, 20, 0);
         System.out.println(gl.glGetError());
         
         //shader code
        gl.glUseProgram(shader.p);
         gl.glDrawRangeElements(GL3.GL_TRIANGLE_STRIP, 0, 3, 4, GL3.GL_UNSIGNED_INT, 0); //start render at 0 verts go to 3 for a count of 4
        gl.glUseProgram(0);
      }    


      public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height)        {          
         GL3 gl = drawable.getGL().getGL3();    
         GLU glu = new GLU();
         gl.glViewport(0, 0, width, height);  
         glu.gluPerspective(45.0f, (float) width / (float) height, 0.1f, 100.0f);  
      }
   }
}

Right now I'm looking into the fact that my string for glGetAttribLocation is not null teminated
Offline foota

Senior Newbie





« Reply #5 - Posted 2011-08-02 01:14:31 »

So in my ShaderProgram code I was assigning the program handle to a local variable *facepalm* but my program is still not working correctly, new error below
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
Exception in thread "Timer-0" javax.media.opengl.GLException: javax.media.opengl.GLException: Thread[AWT-EventQueue-0,6,main] glGetError() returned the following error codes after a call to glGetAttribLocation(<int> 0x1, <java.lang.String>): GL_INVALID_OPERATION ( 1282 0x502), 
   at jogamp.opengl.awt.AWTThreadingPlugin.invokeOnOpenGLThread(AWTThreadingPlugin.java:98)
   at jogamp.opengl.ThreadingImpl.invokeOnOpenGLThread(ThreadingImpl.java:197)
   at javax.media.opengl.Threading.invokeOnOpenGLThread(Threading.java:164)
   at javax.media.opengl.awt.GLCanvas.maybeDoSingleThreadedWorkaround(GLCanvas.java:767)
   at javax.media.opengl.awt.GLCanvas.display(GLCanvas.java:388)
   at com.jogamp.opengl.util.AWTAnimatorImpl.display(AWTAnimatorImpl.java:74)
   at com.jogamp.opengl.util.AnimatorBase.display(AnimatorBase.java:140)
   at com.jogamp.opengl.util.FPSAnimator$1.run(FPSAnimator.java:125)
   at java.util.TimerThread.mainLoop(Unknown Source)
   at java.util.TimerThread.run(Unknown Source)
Caused by: javax.media.opengl.GLException: Thread[AWT-EventQueue-0,6,main] glGetError() returned the following error codes after a call to glGetAttribLocation(<int> 0x1, <java.lang.String>): GL_INVALID_OPERATION ( 1282 0x502),
   at javax.media.opengl.DebugGL3.checkGLGetError(DebugGL3.java:12595)
   at javax.media.opengl.DebugGL3.glGetAttribLocation(DebugGL3.java:5641)
   at RealMain$JOGLRenderer.display(RealMain.java:105)
   at jogamp.opengl.GLDrawableHelper.display(GLDrawableHelper.java:191)
   at javax.media.opengl.awt.GLCanvas$DisplayAction.run(GLCanvas.java:873)
   at jogamp.opengl.GLDrawableHelper.invokeGL(GLDrawableHelper.java:363)
   at javax.media.opengl.awt.GLCanvas$DisplayOnEventDispatchThreadAction.run(GLCanvas.java:890)
   at java.awt.event.InvocationEvent.dispatch(Unknown Source)
   at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
   at java.awt.EventQueue.access$000(Unknown Source)
   at java.awt.EventQueue$1.run(Unknown Source)
   at java.awt.EventQueue$1.run(Unknown Source)
   at java.security.AccessController.doPrivileged(Native Method)
   at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
   at java.awt.EventQueue.dispatchEvent(Unknown Source)
   at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
   at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
   at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
   at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
   at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
   at java.awt.EventDispatchThread.run(Unknown Source)

This makes me think that my shader program is not compiling successfully,  but I'm not quite sure how to check that.
Offline lhkbob

JGO Knight


Medals: 32



« Reply #6 - Posted 2011-08-02 02:21:56 »

Here is the URL to the glGetAttribLocation documentation: http://www.opengl.org/sdk/docs/man/xhtml/glGetAttribLocation.xml.  In brief, you can get the GL_INVALID_OPERATION if the program wasn't created by OpenGL, if it hasn't been successfully linked (e.g. compiled) or if you're calling it between glBegin and glEnd. 

It sounds like you fixed the bug that would have made it the first cause, you can't be doing the third, so you're correct that you're not getting your programs to link correctly.

Here is a link to my code for handling shaders: http://code.google.com/p/ferox-gl/source/browse/trunk/ferox-jogl/src/com/ferox/renderer/impl/jogl/JoglGlslShaderResourceDriver.java.  It is part of an engine, but should be pretty easy to take what you need from it.  You should pay the most attention to the glLinkProgram and glCompileShader methods defined in it.

Basically, you need to look up the compile status of each shader object, and the link status of the program object.  The code also shows you how to query the information logs for both so you know why they might fail.  The call glValidateProgram theoretically could be used to check if a program fails to link because it would fail to validate, but failing validation does not raise an opengl error that you can check with glGetError(), you'd have to check the VALIDATION_STATUS similarly to how I check the LINK_STATUS in the linked code.

Offline foota

Senior Newbie





« Reply #7 - Posted 2011-08-02 03:20:47 »

Wow, that was super helpful, thank you very much.
So here's the code that is compiled for each shader followed by the error it produces.
Since they both give the same error I'm thinking there's something wrong with the way I'm reading in and feeding the code to openGL.
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
#version 150
in vec3 vertex;
void
main()
{
    gl_Position = vec4(vertex,1.0);
}
";
v: Vertex shader failed to compile with the following errors:
ERROR: 7:2: error(#90) Syntax error ERROR___CPP_EOL_IN_STRING
ERROR: 7:2: error(#132) Syntax error: '<' parse error
ERROR: error(#273) 2 compilation errors.  No code generated

#version 150
out vec4 fragmentColor;
void
main()
{
    fragmentColor = vec4(0.0, 1.0, 0.0, 1.0);
}
"
;
f: Fragment shader failed to compile with the following errors:
ERROR: 7:2: error(#90) Syntax error ERROR___CPP_EOL_IN_STRING
ERROR: 7:2: error(#132) Syntax error: '<' parse error
ERROR: error(#273) 2 compilation errors.  No code generated

for reference here's my code that handles compiling the shaders (I commented out the linking related things for now)
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
58  
59  
60  
61  
62  
63  
64  
65  
66  
67  
68  
69  
70  
71  
72  
73  
74  
75  
76  
77  
78  
79  
80  
81  
82  
83  
84  
85  
86  
87  
88  
89  
90  
91  
92  
93  
94  
95  
96  
97  
98  
99  
100  
101  
102  
103  
104  
105  
106  
107  
108  
public ShaderProgram(GLAutoDrawable drawable, File vertf, File fragf) {
      this.vertf = vertf;
      this.fragf = fragf;        
      DebugGL3 gl = new DebugGL3( drawable.getGL().getGL3());

      p = gl.glCreateProgram();

      //VERTEX STUFF
     int v = gl.glCreateShader(gl.GL_VERTEX_SHADER);

      ArrayList <String> vSourceA = new ArrayList<String>();
      Scanner vert = null;
      try {
         vert = new Scanner(vertf);
      } catch (FileNotFoundException e) {
         System.out.println("Vertex shader file was not found");
      }

      vert.useDelimiter("\n");

      while(vert.hasNext()){
         String temp = vert.next() + "\n";
         vSourceA.add(temp);
         System.out.print(temp);
      }

      String[] vSource = new String[vSourceA.size()];
      vSource = vSourceA.toArray(vSource);
      int [] lengths= new int[vSource.length];
      for(int i = 0; i < vSource.length; i++){
         lengths[i] = vSource[i].length();
      }

      gl.glShaderSource(v, lengths.length, vSource, lengths, 0);        
      gl.glCompileShader(v);

      // query compile status and possibly read log
     int[] status = new int[1];
      gl.glGetShaderiv(v, GL3.GL_COMPILE_STATUS, status, 0);
      if (status[0] == GL.GL_TRUE){
         System.out.println("v: succesful");
         // everything compiled successfully, no log
     }else{
         // compile failed, read the log and return it
        gl.glGetShaderiv(v, GL3.GL_INFO_LOG_LENGTH, status, 0);
         int maxLogLength = status[0];
         if (maxLogLength > 0) {
            byte[] log = new byte[maxLogLength];
            gl.glGetShaderInfoLog(v, maxLogLength, status, 0, log, 0);

            System.out.println("v: " + new String(log, 0, status[0]));
         } else
            System.out.println("v: "+ "unknown compilation error");
      }
      //FRAGMENT SHADER CODE
     int f = gl.glCreateShader(gl.GL_FRAGMENT_SHADER);

      ArrayList <String> fSourceA = new ArrayList<String>();

      Scanner frag = null;
      try {
         frag = new Scanner(fragf);
      } catch (FileNotFoundException e) {
         System.out.println("Fragment shader file was not found");
      }


      frag.useDelimiter("\n");
      while(frag.hasNext()){
         String temp = frag.next() + "\n";
         fSourceA.add(temp);
         System.out.print(temp);
      }

      String[] fSource = new String[fSourceA.size()];
      fSource = fSourceA.toArray(fSource);
      lengths= new int[fSource.length];
      for(int i = 0; i < fSource.length; i++){
         lengths[i] = fSource[i].length();
      }

      gl.glShaderSource(f, lengths.length, fSource, lengths, 0);        
      gl.glCompileShader(f);

      // query compile status and possibly read log
     status = new int[1];
      gl.glGetShaderiv(f, GL3.GL_COMPILE_STATUS, status, 0);
      if (status[0] == GL.GL_TRUE){
         System.out.println("f: succesful");
         // everything compiled successfully, no log
     }else{
         // compile failed, read the log and return it
        gl.glGetShaderiv(f, GL3.GL_INFO_LOG_LENGTH, status, 0);
         int maxLogLength = status[0];
         if (maxLogLength > 0) {
            byte[] log = new byte[maxLogLength];
            gl.glGetShaderInfoLog(f, maxLogLength, status, 0, log, 0);
            System.out.println("f: " + new String(log, 0, status[0]));
         } else
            System.out.println("f: " + "unknown compilation error");
      }
      //PROGRAM CODE
     //gl.glLinkProgram(p);      
     //gl.glValidateProgram(p);


      valid = true;
   }
Offline foota

Senior Newbie





« Reply #8 - Posted 2011-08-02 06:30:23 »

So I got the vertex and fragment shaders to compile by taking out the extra newline char I was adding in *oops* and taking out the #version line at the top. But now I have a different problem than before with glVertexAttribPointer
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
Exception in thread "Timer-0" javax.media.opengl.GLException: javax.media.opengl.GLException: Thread[AWT-EventQueue-0,6,main] glGetError() returned the following error codes after a call to glVertexAttribPointer(<int> 0xFFFFFFFF, <int> 0x3, <int> 0x1406, <boolean>, <int> 0x0, <long>): GL_INVALID_VALUE ( 1281 0x501), 
   at jogamp.opengl.awt.AWTThreadingPlugin.invokeOnOpenGLThread(AWTThreadingPlugin.java:98)
   at jogamp.opengl.ThreadingImpl.invokeOnOpenGLThread(ThreadingImpl.java:197)
   at javax.media.opengl.Threading.invokeOnOpenGLThread(Threading.java:164)
   at javax.media.opengl.awt.GLCanvas.maybeDoSingleThreadedWorkaround(GLCanvas.java:767)
   at javax.media.opengl.awt.GLCanvas.display(GLCanvas.java:388)
   at com.jogamp.opengl.util.AWTAnimatorImpl.display(AWTAnimatorImpl.java:74)
   at com.jogamp.opengl.util.AnimatorBase.display(AnimatorBase.java:140)
   at com.jogamp.opengl.util.FPSAnimator$1.run(FPSAnimator.java:125)
   at java.util.TimerThread.mainLoop(Unknown Source)
   at java.util.TimerThread.run(Unknown Source)
Caused by: javax.media.opengl.GLException: Thread[AWT-EventQueue-0,6,main] glGetError() returned the following error codes after a call to glVertexAttribPointer(<int> 0xFFFFFFFF, <int> 0x3, <int> 0x1406, <boolean>, <int> 0x0, <long>): GL_INVALID_VALUE ( 1281 0x501),
   at javax.media.opengl.DebugGL3.checkGLGetError(DebugGL3.java:12595)
   at javax.media.opengl.DebugGL3.glVertexAttribPointer(DebugGL3.java:8895)
   at RealMain$JOGLRenderer.display(RealMain.java:103)
   at jogamp.opengl.GLDrawableHelper.display(GLDrawableHelper.java:191)
   at javax.media.opengl.awt.GLCanvas$DisplayAction.run(GLCanvas.java:873)
   at jogamp.opengl.GLDrawableHelper.invokeGL(GLDrawableHelper.java:363)
   at javax.media.opengl.awt.GLCanvas$DisplayOnEventDispatchThreadAction.run(GLCanvas.java:890)
   at java.awt.event.InvocationEvent.dispatch(Unknown Source)
   at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
   at java.awt.EventQueue.access$000(Unknown Source)
   at java.awt.EventQueue$1.run(Unknown Source)
   at java.awt.EventQueue$1.run(Unknown Source)
   at java.security.AccessController.doPrivileged(Native Method)
   at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
   at java.awt.EventQueue.dispatchEvent(Unknown Source)
   at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
   at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
   at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
   at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
   at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
   at java.awt.EventDispatchThread.run(Unknown Source)

current realmain code is below
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
58  
59  
60  
61  
62  
63  
64  
65  
66  
67  
68  
69  
70  
71  
72  
73  
74  
75  
76  
77  
78  
79  
80  
81  
82  
83  
84  
85  
86  
87  
88  
89  
90  
91  
92  
93  
94  
95  
96  
97  
98  
99  
100  
101  
102  
103  
104  
105  
106  
107  
108  
109  
110  
111  
112  
113  
114  
115  
116  
117  
118  
119  
import javax.media.opengl.DebugGL3;
import javax.media.opengl.GL;
import javax.media.opengl.GL2;
import javax.media.opengl.GL3;
import javax.media.opengl.GLAutoDrawable;
import javax.media.opengl.GLCapabilities;
import javax.media.opengl.GLEventListener;
import javax.media.opengl.GLProfile;
import javax.media.opengl.awt.GLCanvas;
import javax.media.opengl.glu.GLU;
import javax.swing.*;

import com.jogamp.opengl.util.FPSAnimator;

import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;

public class RealMain{    
   public static void main(String[] args)    {        
      JFrame frame = new JFrame("JOGL test");
      frame.setSize(640, 480);
      GLProfile glProfile = GLProfile.getDefault();
      GLCapabilities glCapabilities = new GLCapabilities(glProfile);
      GLCanvas canvas = new GLCanvas(glCapabilities);        
      frame.add(canvas);      
      canvas.addGLEventListener(new JOGLRenderer());  
      FPSAnimator animator = new FPSAnimator(canvas, 60);  
      animator.add(canvas);
      animator.start();      
      frame.addWindowListener(new WindowAdapter(){          
         public void windowClosing(WindowEvent e)            {  
            System.exit(0);            }        });  
      frame.setVisible(true);  
   }  
   private static class JOGLRenderer implements GLEventListener    {
      ShaderProgram shader;
      public void init(GLAutoDrawable drawable){



         shader = new ShaderProgram(drawable, new File("bin/vert.txt"), new File("bin/frag.txt"));

         //setup opengl        
        DebugGL3 gl = new DebugGL3( drawable.getGL().getGL3());
         gl.glClearColor(0.2f, 0.2f, 0.0f, 0.0f);        
         gl.glClearDepth(1.0f);          
         gl.glEnable(GL3.GL_DEPTH_TEST);        

         // Create vertex data        
        float[] vertexData = new float[]{
               -1f, 1f, -2.0f, //0
              1f, 1f, -2.0f, //1
              -1f, -1f, -2.0f, //2
              1f, -1f, -2.0f, //3
        };
         ByteBuffer vertexByteBuffer = ByteBuffer.allocateDirect(3 * 4 * 4);            
         vertexByteBuffer.order(ByteOrder.nativeOrder());      
         FloatBuffer vertexBuffer = vertexByteBuffer.asFloatBuffer();          
         vertexBuffer.put(vertexData);

         // Create vertex buffer              
        int[] vertexBufferId = new int[1];        
         gl.glGenBuffers(1, vertexBufferId, 0);        
         gl.glBindBuffer(GL3.GL_ARRAY_BUFFER, vertexBufferId[0]);      
         gl.glBufferData(GL3.GL_ARRAY_BUFFER, 48, (ByteBuffer)null, GL3.GL_DYNAMIC_DRAW);
         // Load vertex data into vertex buffer        
        gl.glBufferSubData(GL3.GL_ARRAY_BUFFER, 0, vertexByteBuffer.capacity(), vertexByteBuffer);

         // Create index data          
        int[] indexData = new int[]{0, 1, 2, 3};

         ByteBuffer indexByteBuffer = ByteBuffer.allocateDirect(4 * 4);
         indexByteBuffer.order(ByteOrder.nativeOrder());
         IntBuffer indexBuffer = indexByteBuffer.asIntBuffer();
         indexBuffer.put(indexData);

         // Create index buffer    
        int[] indexBufferId = new int[1];
         gl.glGenBuffers(1, indexBufferId, 0);
         gl.glBindBuffer(GL3.GL_ELEMENT_ARRAY_BUFFER, indexBufferId[0]);          
         gl.glBufferData(GL3.GL_ELEMENT_ARRAY_BUFFER, 16, (ByteBuffer)null, GL3.GL_DYNAMIC_DRAW);      
         // Load index data into index buffer          
        gl.glBufferSubData(GL3.GL_ELEMENT_ARRAY_BUFFER, 0, indexByteBuffer.capacity(), indexByteBuffer);



      }
      public void dispose(GLAutoDrawable drawable){}
      public void display(GLAutoDrawable drawable){        
         DebugGL3 gl = new DebugGL3( drawable.getGL().getGL3());
         gl.glClear(GL3.GL_COLOR_BUFFER_BIT | GL3.GL_DEPTH_BUFFER_BIT);      


         //gl.glMatrixMode(GL2.GL_MODELVIEW);
        //gl.glLoadIdentity();          
        int stride = 3 * 4; //3 floats per vert * 4 bytes per float

         gl.glVertexAttribPointer(gl.glGetAttribLocation(shader.p, "vertex"), 3, GL3.GL_FLOAT, false, 0, 0);

         //shader code
        gl.glUseProgram(shader.p);
         gl.glDrawRangeElements(GL3.GL_TRIANGLE_STRIP, 0, 3, 4, GL3.GL_UNSIGNED_INT, 0); //start render at 0 verts go to 3 for a count of 4
        gl.glUseProgram(0);
      }    


      public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height)        {          
         GL3 gl = drawable.getGL().getGL3();    
         GLU glu = new GLU();
         gl.glViewport(0, 0, width, height);  
         glu.gluPerspective(45.0f, (float) width / (float) height, 0.1f, 100.0f);  
      }
   }
}
Offline lhkbob

JGO Knight


Medals: 32



« Reply #9 - Posted 2011-08-02 17:36:52 »

In the stack trace, you can see that the glVertexAttribPointer was called with the value 0xffffff for the attribute index.  This is equal to -1, which is an invalid value for glVertexAttribPointer.  It also means that
1  
glGetAttribLocation(shader.p, "vertex")

is returning -1, so there is still a problem with your shader code since OpenGL doesn't think that "vertex" is an active attribute.

My hunch is that it is because you removed the version identifier.  Unless you also updated the syntax of your shader, your syntax won't quite match that of the default version 1.2 for GLSL shaders.  Mainly, they don't have "in vec3" you would need "attribute vec3".  It's only a hunch, though, because I would have thought your card would fail to compile it.

However, I think I noticed an issue with your shader code that should allow you to put back the version identifier.  In each vertex and fragment shader, you have the line: "; at the very end, which is invalid syntax.  If you remove that, you should be able to compile the program fine with
1  
#version 150

added back in.  Of course, you might not support GLSL 1.5, but you should get error logs that report that instead of error logs saying that it failed to parse.

Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline ra4king

JGO Kernel


Medals: 341
Projects: 2
Exp: 5 years


I'm the King!


« Reply #10 - Posted 2011-08-02 23:43:03 »

In each vertex and fragment shader, you have the line: "; at the very end, which is invalid syntax.
Wow, you beat me to it! I was about to point that out T_T

Offline foota

Senior Newbie





« Reply #11 - Posted 2011-08-03 02:17:09 »

Okay so I fixed my shaders by removing the trailing ;, and modified my shader reading code to use nextline and added on \n to the end of each string in the source array and that made the shaders compiled without error, however when I try to attach the shaders and compile the program it says this:

Vertex shader(s) failed to link, fragment shader(s) failed to link.
ERROR: error(#280) Not all shaders have valid object code
ERROR: error(#280) Not all shaders have valid object code

Current shader code look like this
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
58  
59  
60  
61  
62  
63  
64  
65  
66  
67  
68  
69  
70  
71  
72  
73  
74  
75  
76  
77  
78  
79  
80  
81  
82  
83  
84  
85  
86  
87  
88  
89  
90  
91  
92  
93  
94  
95  
96  
97  
98  
99  
100  
101  
102  
103  
104  
105  
106  
107  
108  
109  
110  
111  
112  
113  
114  
115  
116  
117  
118  
119  
120  
121  
122  
123  
124  
125  
126  
127  
128  
129  
130  
131  
132  
133  
134  
135  
136  
137  
138  
139  
140  
141  
142  
143  
144  
145  
146  
147  
148  
149  
150  
151  
152  
153  
154  
155  
156  
157  
158  
159  
160  
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.Scanner;

import javax.media.opengl.DebugGL3;
import javax.media.opengl.GL;
import javax.media.opengl.GL2;
import javax.media.opengl.GL3;
import javax.media.opengl.GLAutoDrawable;

public class ShaderProgram {

   public ShaderProgram(GLAutoDrawable drawable, File vertf, File fragf) {
      this.vertf = vertf;
      this.fragf = fragf;        
      DebugGL3 gl = new DebugGL3( drawable.getGL().getGL3());

      p = gl.glCreateProgram();

      //VERTEX STUFF
     int v = gl.glCreateShader(gl.GL_VERTEX_SHADER);

      ArrayList <String> vSourceA = new ArrayList<String>();
      Scanner vert = null;
      try {
         vert = new Scanner(vertf);
      } catch (FileNotFoundException e) {
         System.out.println("Vertex shader file was not found");
      }

      vert.useDelimiter("\n");
      while(vert.hasNextLine()){
         String temp = vert.nextLine() + "\n";
         vSourceA.add(temp);
         System.out.print(temp);
      }

      String[] vSource = new String[vSourceA.size()];
      vSource = vSourceA.toArray(vSource);
      int [] lengths= new int[vSource.length];
      for(int i = 0; i < vSource.length; i++){
         lengths[i] = vSource[i].length();
      }

      gl.glShaderSource(v, 1, vSource, lengths, 0);        
      gl.glCompileShader(v);
      gl.glAttachShader(p,v);

      // query compile status and possibly read log
     int[] status = new int[1];
      gl.glGetShaderiv(v, GL3.GL_COMPILE_STATUS, status, 0);
      if (status[0] == GL.GL_TRUE){
         System.out.println("v: succesful");
         // everything compiled successfully, no log
     }else{
         // compile failed, read the log and return it
        gl.glGetShaderiv(v, GL3.GL_INFO_LOG_LENGTH, status, 0);
         int maxLogLength = status[0];
         if (maxLogLength > 0) {
            byte[] log = new byte[maxLogLength];
            gl.glGetShaderInfoLog(v, maxLogLength, status, 0, log, 0);

            System.out.println("v: " + new String(log, 0, status[0]));
         } else
            System.out.println("v: "+ "unknown compilation error");
      }




      //FRAGMENT SHADER CODE
     int f = gl.glCreateShader(gl.GL_FRAGMENT_SHADER);

      ArrayList <String> fSourceA = new ArrayList<String>();

      Scanner frag = null;
      try {
         frag = new Scanner(fragf);
      } catch (FileNotFoundException e) {
         System.out.println("Fragment shader file was not found");
      }


      frag.useDelimiter("\n");
      while(frag.hasNextLine()){
         String temp = frag.nextLine() + "\n";
         fSourceA.add(temp);
         System.out.print(temp);
      }

      String[] fSource = new String[fSourceA.size()];
      fSource = fSourceA.toArray(fSource);
      lengths= new int[fSource.length];
      for(int i = 0; i < fSource.length; i++){
         lengths[i] = fSource[i].length();
      }

      gl.glShaderSource(f, 1, fSource, lengths, 0);        
      gl.glCompileShader(f);
      gl.glAttachShader(p,f);

      // query compile status and possibly read log
     status = new int[1];
      gl.glGetShaderiv(f, GL3.GL_COMPILE_STATUS, status, 0);
      if (status[0] == GL.GL_TRUE){
         System.out.println("f: succesful");
         // everything compiled successfully, no log
     }else{
         // compile failed, read the log and return it
        gl.glGetShaderiv(f, GL3.GL_INFO_LOG_LENGTH, status, 0);
         int maxLogLength = status[0];
         if (maxLogLength > 0) {
            byte[] log = new byte[maxLogLength];
            gl.glGetShaderInfoLog(f, maxLogLength, status, 0, log, 0);
            System.out.println("f: " + new String(log, 0, status[0]));
         } else
            System.out.println("f: " + "unknown compilation error");
      }


      //PROGRAM CODE
     gl.glLinkProgram(p);      



      // check link status
     int[] query = new int[1];
      gl.glGetProgramiv(p, GL3.GL_LINK_STATUS, query, 0);
      if (query[0] == GL.GL_TRUE){
         System.out.println("P: successful"); // program linked successfully
        valid = true;
      }else{
         // link failed, read the log and return it
        gl.glGetProgramiv(p, GL3.GL_INFO_LOG_LENGTH, query, 0);
         int maxLogLength = query[0];
         if (maxLogLength > 0) {
            byte[] log = new byte[maxLogLength];
            gl.glGetProgramInfoLog(p, maxLogLength, query, 0, log, 0);

            valid = false;
            System.out.println(new String(log, 0, query[0]));
         } else{
            valid = false;
            System.out.println("unknown link error");
         }
      }
   }

   int p;
   boolean valid = false;

   File vertf;
   File fragf;

}
Offline ra4king

JGO Kernel


Medals: 341
Projects: 2
Exp: 5 years


I'm the King!


« Reply #12 - Posted 2011-08-03 03:06:55 »

I do believe that error code is talking about your shader code, aka the C code.

Offline foota

Senior Newbie





« Reply #13 - Posted 2011-08-03 03:11:54 »

I thought they were correct, they look like this:
vertex shader code
1  
2  
3  
4  
5  
6  
7  
#version 150
in vec3 vertex;
void
main()
{
    gl_Position = vec4(vertex,1.0);
}

fragment shader code
1  
2  
3  
4  
5  
6  
7  
#version 150
out vec4 fragmentColor;
void
main()
{
    fragmentColor = vec4(0.0, 1.0, 0.0, 1.0);
}
Offline ra4king

JGO Kernel


Medals: 341
Projects: 2
Exp: 5 years


I'm the King!


« Reply #14 - Posted 2011-08-03 03:25:34 »

I barely know any C, but in the first one, where is vec3 used?
Also if vec4 is a function, where does it exist?

Offline foota

Senior Newbie





« Reply #15 - Posted 2011-08-03 03:42:35 »

vec3 is the type of the input value vertex, and it's used to set the position of the vertex.
And vec4 is saying that there is an output that has 4 pieces of data.
Offline lhkbob

JGO Knight


Medals: 32



« Reply #16 - Posted 2011-08-03 18:07:55 »

@ra4king: GLSL shader code is not C code, it has C like syntax.  vec3 and vec4 are primitive data types in GLSL that represent 3 and 4 dimensional vectors. vec4(0.0, 1.0, 0.0, 1.0) does not call a function per se, it's calling the constructor for the vec4.

When googling for "not all shaders have valid object code", everyone who fixed it solved it by editing whitespace and newlines in their code.  Every time this should not have made any difference, so its likely a bad compiler in the driver.  I would suggest moving "void" and "main()" onto the same line and see if that gets you anywhere.

Offline foota

Senior Newbie





« Reply #17 - Posted 2011-08-03 21:13:05 »

Yeah that doesn't change anything, still getting the same
Vertex shader(s) failed to link, fragment shader(s) failed to link.
ERROR: error(#280) Not all shaders have valid object code
ERROR: error(#280) Not all shaders have valid object code
after the shaders report compiling successfully. *sigh*
I guess I'll try updating my drivers and running it on a different computer.

EDIT:
The problem is definitely in the way I read in my shaders; hardcoding in the shaders as a string array makes everything compile fine (although I still need to figure out how to use them to draw)
Offline foota

Senior Newbie





« Reply #18 - Posted 2011-08-03 23:39:11 »

So I fixed my shader compiling/linking/etc code and now glGetAttribLocation returns 0 (the first index) and the program compiles and runs without complaint, however all I'm getting right now is a screen drawn to the clearcolor.
Here's my shader loading code for anyone trying to follow in my footsteps.
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
58  
59  
60  
61  
62  
63  
64  
65  
66  
67  
68  
69  
70  
71  
72  
73  
74  
75  
76  
77  
78  
79  
80  
81  
82  
83  
84  
85  
86  
87  
88  
89  
90  
91  
92  
93  
94  
95  
96  
97  
98  
99  
100  
101  
102  
103  
104  
105  
106  
107  
108  
109  
110  
111  
112  
113  
114  
115  
116  
117  
118  
119  
120  
121  
122  
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.nio.CharBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Scanner;

import javax.media.opengl.DebugGL3;
import javax.media.opengl.GL;
import javax.media.opengl.GL2;
import javax.media.opengl.GL3;
import javax.media.opengl.GLAutoDrawable;

public class ShaderProgram {


   int p;
   boolean valid = false;

   File vertf;
   File fragf;
   
   String []vertS = {"#version 150\nin vec3 vertex;\nvoid main()\n{\ngl_Position = vec4(vertex,1.0);\n}"};
   String []fragS = {"#version 150\nout vec4 fragmentColor;\nvoid main()\n{\nfragmentColor = vec4(0.0, 1.0, 0.0, 1.0);\n}"};
   
   public ShaderProgram(GLAutoDrawable drawable, File vertf, File fragf) {
      this.vertf = vertf;
      this.fragf = fragf;        
      DebugGL3 gl = new DebugGL3( drawable.getGL().getGL3());

      p = gl.glCreateProgram();

      int v = gl.glCreateShader(gl.GL_VERTEX_SHADER);      
      int f = gl.glCreateShader(gl.GL_FRAGMENT_SHADER);
      readAndCompileShader(v, vertf, gl);
      readAndCompileShader(f, fragf, gl);

      gl.glLinkProgram(p);      



      // check link status
     int[] query = new int[1];
      gl.glGetProgramiv(p, GL3.GL_LINK_STATUS, query, 0);
      if (query[0] == GL.GL_TRUE){
         System.out.println("P: successful"); // program linked successfully
        valid = true;
      }else{
         // link failed, read the log and return it
        gl.glGetProgramiv(p, GL3.GL_INFO_LOG_LENGTH, query, 0);
         int maxLogLength = query[0];
         if (maxLogLength > 0) {
            byte[] log = new byte[maxLogLength];
            gl.glGetProgramInfoLog(p, maxLogLength, query, 0, log, 0);

            valid = false;
            System.out.println(new String(log, 0, query[0]));
         } else{
            valid = false;
            System.out.println("unknown link error");
         }
      }
   }
   
   void readAndCompileShader(int shader, File sourceF, DebugGL3 gl){
      String [] source = new String[1];
      try {
         source[0] = readFile(sourceF);
      } catch (IOException e) {
         System.out.println("Could not find shader file");
      }
      source[0] = source[0].replaceAll("\r\n", "\n");
      //System.out.print(source[0]);
     
      int[] lengths = new int[]{source[0].length()};

      gl.glShaderSource(shader, 1, source, lengths, 0);        
      gl.glCompileShader(shader);
      gl.glAttachShader(p,shader);

      // query compile status and possibly read log
     int[] status = new int[1];
      gl.glGetShaderiv(shader, GL3.GL_COMPILE_STATUS, status, 0);
      if (status[0] == GL.GL_TRUE){
         System.out.println("shader: succesful");
         // everything compiled successfully, no log
     }else{
         // compile failed, read the log and return it
        gl.glGetShaderiv(shader, GL3.GL_INFO_LOG_LENGTH, status, 0);
         int maxLogLength = status[0];
         if (maxLogLength > 0) {
            byte[] log = new byte[maxLogLength];
            gl.glGetShaderInfoLog(shader, maxLogLength, status, 0, log, 0);

            System.out.println("shader: " + new String(log, 0, status[0]));
         } else
            System.out.println("shader: "+ "unknown compilation error");
      }
   }
   
   private static String readFile(File file) throws IOException {
        FileInputStream stream = new FileInputStream(file);
        try {
          FileChannel fc = stream.getChannel();
          MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
          /* Instead of using default, pass in a decoder. */
          return Charset.forName("UTF-8").decode(bb).toString();
        }
        finally {
          stream.close();
        }
      }
}
Offline lhkbob

JGO Knight


Medals: 32



« Reply #19 - Posted 2011-08-04 00:25:42 »

It might not be showing up because I think your modelview and project matrices are setup incorrectly.  Before you call gluPerspective, you should call glMatrixMode(GL_PROJECTION); glLoadIdentity().  Then after that call to gluPerspective, you should call glMatrixMode(GL_MODELVIEW) to switch back.

Having the projection matrix embedded in the modelview matrix usually screws things up and puts the vertices somewhere entirely unexpected.

Offline foota

Senior Newbie





« Reply #20 - Posted 2011-08-04 01:08:04 »

Mm yeah I tried what I think you suggested and it still didn't work, I think I'm going to try looking at the code here: http://www.spacesimulator.net/wiki/index.php/Tutorials:OpenGL_and_Glut_(OpenGL3.3) and porting the matrix related things over.
On a side note, how do you specify the link text for a link on this forum?
Offline lhkbob

JGO Knight


Medals: 32



« Reply #21 - Posted 2011-08-04 02:22:53 »

Alright I figured out what was going wrong with your code.  There were multiple issues.

1. In your vertex shader, you assign vec4(vertex, 1.0) to gl_Position.  However, you're responsible for projecting and transforming the vertex into camera space before you write it to gl_Position.  This gives you incorrect results, because you have specified z = -2, which is outside the viewable region after projection (which is what OpenGL assumes you have done).

To fix this part, you will need to multiply the vertex by the projection and modelview matrices.  This is easiest when using older versions of OpenGL if you don't have the 4x4 matrices lying around in memory.  To do it that way, use the GL2 profile and the built-in uniforms gl_ProjectionMatrix and gl_ModelViewMatrix and change the vertex shader to (note besides switching from GL3 to GL2, I've switched shader versions to 1.2):
1  
2  
3  
4  
5  
#version 120
attribute vec3 vertex;
void main() {
   gl_Position = gl_ProjectionMatrix * gl_ModelViewMatrix * vec4(vertex, 1.0);
}


If you want to do the same thing with shader 1.5 and OpenGL 3.0, you'll have to declare some uniform mat4 variables for the projection and modelview, compute what the matrices should be manually (instead of using gluPerspective, for example) and assign the uniform values before rendering with the shader.  This is a lot of trouble, so I'd suggest stepping down to an older version of OpenGL until you get used to things more.

2. You were not enabling the vertex attribute index that you wanted to use to send values to the 'vertex' in variable.  You need to add a call:
1  
gl.glEnableVertexAttribArray(gl.glGetAttribLocation(shader.p, "vertex"));

before you call glVertexAttribPointer.

3. In your glVertexAttribPointer, you should not set the stride to 20, the way you've built your vertex data, it has a stride of 0.

4. When building your vertex VBO, you are getting an OpenGL error generated by your call to glBufferSubData because your vertex nio buffer's capacity is 112 (or 7 * 4 * 4) and you created the VBO to have a size of 48.  You can fix this by creating the nio buffer with a capacity of vertexData.length * 4.

5. Your call to glDrawRangeElements has parameters that don't make sense with your indices.  You're still passing in 4 indices even though you're using triangle strips and you have indices that range from 0 to 3.  Currently you're claiming that your indices range from 0 to 2 and that you pass in 3 indices.  So change the draw call to:
1  
glDrawRangeElements(GL2.GL_TRIANGLE_STRIP, 0, 3, 4, GL2.GL_UNSIGNED_INT, 0);


I think that was everything that was buggy that I had to change to make it work.  I don't have OpenGL 3.0 on my laptop so I had to rewrite your shaders to use version 1.20 and switch every GL3 to a GL2.  This means that I went with the gl_ProjectionMatrix and gl_ModelViewMatrix solution to getting your vertices to display correctly.  It also means that you'll still have to set the matrix mode and load identity matrices as I mentioned before.

I found most of these bugs (except for the triangle strip and projection/modelview bugs) by adding DebugGL wrappers to the GL instances you use in your RealMain class, since you had only added them to your ShaderProgram class.  My advice would be to always remember that tool and make sure you're using it rigorously when you're encountering unexpected errors with OpenGL.

Offline foota

Senior Newbie





« Reply #22 - Posted 2011-08-04 02:51:11 »

Ok yeah I'd fixed some of the nonsensical values for drawRangeElements (or so I though I had) in the latest paste of the code, but I really had no idea what to do to convert the coordinates to screen coordinates. And on a side note it works Smiley Thank you very much everyone for your help. And ihkbob do you have any recommendation for future reference for where to learn how to deal with openGL matrices?
Offline lhkbob

JGO Knight


Medals: 32



« Reply #23 - Posted 2011-08-04 17:34:12 »

Here is a link to a forum post I wrote about matrices: http://www.java-gaming.org/topics/matrices-and-some-random-opengl-3-x-questions/24545/msg/206908/view.html#msg206908.  I would google around for linear algebra tutorials or choose math classes that cover linear algebra if you're in college.  The Redbook from OpenGL has a good coverage of how they use matrices and I found it really helpful in understanding their approach and camera model.

Offline foota

Senior Newbie





« Reply #24 - Posted 2011-08-04 22:05:33 »

Okay thank you, I plan on getting the red book at some point; maybe I should make some point now.
Offline lhkbob

JGO Knight


Medals: 32



« Reply #25 - Posted 2011-08-04 23:34:06 »

I think you can get old versions online at opengl.org for free.

Pages: [1]
  ignore  |  Print  
 
 
You cannot reply to this message, because it is very, very old.

 

Add your game by posting it in the WIP section,
or publish it in Showcase.

The first screenshot will be displayed as a thumbnail.

CogWheelz (16 views)
2014-07-30 21:08:39

Riven (22 views)
2014-07-29 18:09:19

Riven (15 views)
2014-07-29 18:08:52

Dwinin (12 views)
2014-07-29 10:59:34

E.R. Fleming (33 views)
2014-07-29 03:07:13

E.R. Fleming (12 views)
2014-07-29 03:06:25

pw (43 views)
2014-07-24 01:59:36

Riven (42 views)
2014-07-23 21:16:32

Riven (30 views)
2014-07-23 21:07:15

Riven (31 views)
2014-07-23 20:56:16
List of Learning Resources
by SilverTiger
2014-07-31 13:54:12

HotSpot Options
by dleskov
2014-07-08 03:59:08

Java and Game Development Tutorials
by SwordsMiner
2014-06-14 00:58:24

Java and Game Development Tutorials
by SwordsMiner
2014-06-14 00:47:22

How do I start Java Game Development?
by ra4king
2014-05-17 11:13:37

HotSpot Options
by Roquen
2014-05-15 09:59:54

HotSpot Options
by Roquen
2014-05-06 15:03:10

Escape Analysis
by Roquen
2014-04-29 22:16:43
java-gaming.org is not responsible for the content posted by its members, including references to external websites, and other references that may or may not have a relation with our primarily gaming and game production oriented community. inquiries and complaints can be sent via email to the info‑account of the company managing the website of java‑gaming.org
Powered by MySQL Powered by PHP Powered by SMF 1.1.18 | SMF © 2013, Simple Machines | Managed by Enhanced Four Valid XHTML 1.0! Valid CSS!