private void initShaders(GL3 gl) { final String[] vertSrc = new String[] { "#version 150\n", "in vec4 vPosition;\n", "in vec4 vColor;\n", "out vec4 pColor;\n", "void main() {\n", " pColor = vColor;\n", " gl_Position = vPosition;\n", "}\n" }; vertID = createShader(gl, GL3.GL_VERTEX_SHADER, vertSrc); final String[] fragSrc = new String[] { "#version 150\n", "in vec4 pColor;\n", "void main() {\n", " gl_FragColor = pColor;\n", "}\n" }; fragID = createShader(gl, GL3.GL_FRAGMENT_SHADER, fragSrc); // We're done with the compiler gl.glReleaseShaderCompiler(); progID = gl.glCreateProgram(); assert progID > 0; gl.glAttachShader(progID, vertID); gl.glAttachShader(progID, fragID); gl.glLinkProgram(progID); gl.glValidateProgram(progID); }
/** * Update this VBO with (potentially) new data. * * @param gl The global openGL instance. * @param attribs One or more attributes that represent this VBO, @see GLSLAttrib */ public void update(GL3 gl, GLSLAttrib... attribs) { this.attribs = attribs; gl.glBindVertexArray(this.vboPointer.get(0)); gl.glBindBuffer(GL3.GL_ARRAY_BUFFER, this.bufferPointer.get(0)); // Allocate enough memory int size = 0; for (final GLSLAttrib attrib : attribs) { size += attrib.buffer.capacity() * Buffers.SIZEOF_FLOAT; } gl.glBufferData(GL3.GL_ARRAY_BUFFER, size, (Buffer) null, GL3.GL_STATIC_DRAW); // Copy the GLSL Attribute data into the internal OpenGL buffer int nextStart = 0; for (final GLSLAttrib attrib : attribs) { gl.glBufferSubData( GL3.GL_ARRAY_BUFFER, nextStart, attrib.buffer.capacity() * Buffers.SIZEOF_FLOAT, attrib.buffer); nextStart += attrib.buffer.capacity() * Buffers.SIZEOF_FLOAT; } }
/** * Initialization method for any shader. Compiles and checks code. * * @param gl The global openGL instance. * @throws CompilationFailedException If the compilation of the GLSL code generated any errors. */ public void init(GL3 gl) throws CompilationFailedException { try { // First, give the source to OpenGL and compile gl.glShaderSource(getShaderPointer(), 1, source, (int[]) null, 0); gl.glCompileShader(getShaderPointer()); // Receive compilation status IntBuffer buf = Buffers.newDirectIntBuffer(1); gl.glGetShaderiv(getShaderPointer(), GL3.GL_COMPILE_STATUS, buf); int status = buf.get(0); // Check the status if (status == GL3.GL_FALSE) { // Prepare for additional information gl.glGetShaderiv(getShaderPointer(), GL3.GL_INFO_LOG_LENGTH, buf); int logLength = buf.get(0); byte[] reason = new byte[logLength]; // Get additional information gl.glGetShaderInfoLog(getShaderPointer(), logLength, null, 0, reason, 0); throw new CompilationFailedException( "Compilation of " + filename + " failed, " + new String(reason)); } } catch (UninitializedException e) { logger.error(e.getMessage()); } }
@Override public void reshape(GLAutoDrawable glad, int x, int y, int w, int h) { System.out.println("reshape() x: " + x + " y: " + y + " width: " + w + " height: " + h); GL3 gl3 = glad.getGL().getGL3(); gl3.glViewport(x, y, w, h); }
/** This method is called at the beginning of each frame, i.e., before scene drawing starts. */ private void beginFrame() { // Set the active shader as default for this frame gl.glUseProgram(activeShaderID); // Clear color and depth buffer for the new frame gl.glClear(GL3.GL_COLOR_BUFFER_BIT); gl.glClear(GL3.GL_DEPTH_BUFFER_BIT); }
private void displayVBOVAO(final GL3 gl) { try { gl.glBindVertexArray(vao); gl.glDrawElements(GL3.GL_TRIANGLES, 3, GL3.GL_UNSIGNED_SHORT, 0L); gl.glBindVertexArray(0); } catch (GLException ex) { Logger.getLogger(TestBug692GL3VAONEWT.class.getName()).log(Level.SEVERE, null, ex); } }
@Override public void init(GLAutoDrawable drawable) { super.init(drawable); GL3 gl = drawable.getGL().getGL3(); gl.glClearColor(1, 1, 1, 1); // Hintergrundfarbe (RGBA) fpsAnimator = new FPSAnimator(drawable, 60, true); fpsAnimator.start(); }
@Override public void dispose(GLAutoDrawable drawable) { final GL3 gl = drawable.getGL().getGL3(); gl.glDeleteBuffers(2, new int[] {vbo, ibo}, 0); gl.glDetachShader(progID, fragID); gl.glDetachShader(progID, vertID); gl.glDeleteProgram(progID); gl.glDeleteShader(fragID); gl.glDeleteShader(vertID); }
@Override public void display(GLAutoDrawable glad) { System.out.println("display"); GL3 gl3 = glad.getGL().getGL3(); gl3.glClearColor(1.0f, 1.0f, 1.0f, 1.0f); gl3.glClear(GL3.GL_COLOR_BUFFER_BIT); programObject.bind(gl3); { programObject.setUniform(gl3, "offset", new float[] {0.5f, 0.5f}, 2); gl3.glBindBuffer(GL3.GL_ARRAY_BUFFER, vertexBufferObject[0]); gl3.glEnableVertexAttribArray(0); gl3.glEnableVertexAttribArray(1); { gl3.glVertexAttribPointer(0, 4, GL3.GL_FLOAT, false, 0, 0); gl3.glVertexAttribPointer(1, 4, GL3.GL_FLOAT, false, 0, 36 * 4 * 4); gl3.glDrawArrays(GL3.GL_TRIANGLES, 0, 36); } gl3.glDisableVertexAttribArray(0); gl3.glDisableVertexAttribArray(1); } programObject.unbind(gl3); glad.swapBuffers(); }
private static int createShader(final GL3 gl, int type, final String[] srcLines) { int shaderID = gl.glCreateShader(type); assert shaderID > 0; int[] lengths = new int[srcLines.length]; for (int i = 0; i < srcLines.length; i++) { lengths[i] = srcLines[i].length(); } gl.glShaderSource(shaderID, srcLines.length, srcLines, lengths, 0); gl.glCompileShader(shaderID); return shaderID; }
private void initializeVertexBuffer(GL3 gl3) { gl3.glGenBuffers(1, IntBuffer.wrap(vertexBufferObject)); gl3.glBindBuffer(GL3.GL_ARRAY_BUFFER, vertexBufferObject[0]); { FloatBuffer buffer = GLBuffers.newDirectFloatBuffer(vertexData); gl3.glBufferData(GL3.GL_ARRAY_BUFFER, vertexData.length * 4, buffer, GL3.GL_STATIC_DRAW); } gl3.glBindBuffer(GL3.GL_ARRAY_BUFFER, 0); }
@Override public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) { GL3 gl = drawable.getGL().getGL3(); // Set the viewport to be the entire window gl.glViewport(0, 0, width, height); float aspect = (float) height / width; bottom = aspect * left; top = aspect * right; // ----- Projektionsmatrix festlegen ----- setOrthogonalProjection(gl, left, right, bottom, top, near, far); }
@Override public void init(GLAutoDrawable drawable) { final GL3 gl = drawable.getGL().getGL3(); gl.glEnable(GL3.GL_DEPTH_TEST); gl.glDisable(GL3.GL_CULL_FACE); initBuffers(gl); initShaders(gl); vao = initVAO(gl); gl.setSwapInterval(1); }
public BackgroundShader(GL3 gl) { super(gl, "/shaders/background"); // get indices of named attributes vertexPositionID = gl.glGetAttribLocation(shaderProgram, "VertexPosition"); vertexTexCoord = gl.glGetAttribLocation(shaderProgram, "VertexTexCoord"); // get indices of uniform variables modelViewProjectionMatrixID = gl.glGetUniformLocation(shaderProgram, "ModelViewProjectionMatrix"); textureID = gl.glGetUniformLocation(shaderProgram, "Tex"); this.validateShader(); }
public void draw(GL3 gl, ShaderProgram program) { vbo.bind(gl); program.linkAttribs(gl, vbo.getAttribs()); gl.glDrawArrays(GL3.GL_POINTS, 0, numParticles); }
/** * Activate and use a given shader. * * @param s the shader to be activated */ @Override public void useShader(Shader s) { if (s != null) { activeShaderID = ((GLShader) s).programId(); gl.glUseProgram(activeShaderID); } }
/** * This constructor is called by {@link GLRenderPanel}. * * @param drawable the OpenGL rendering context. All OpenGL calls are directed to this object. */ public GLRenderContext(GLAutoDrawable drawable) { // Some OpenGL initialization gl = drawable.getGL().getGL3(); gl.glEnable(GL3.GL_DEPTH_TEST); gl.glClearColor(0.0f, 0.0f, 0.0f, 0.0f); // Load and use the default shader defaultShader = (GLShader) makeShader(); try { defaultShader.load("../jrtr/shaders/default.vert", "../jrtr/shaders/default.frag"); } catch (Exception e) { System.out.print("Problem with shader:\n"); System.out.print(e.getMessage()); } useDefaultShader(); }
@Override public void display(GLAutoDrawable drawable) { GL3 gl = drawable.getGL().getGL3(); gl.glClear(GL3.GL_COLOR_BUFFER_BIT | GL3.GL_DEPTH_BUFFER_BIT); // ------ Kamera-System ------- loadIdentity(gl); setColor(0, 0, 0); setShadingLevel(gl, 0); setCameraSystem(gl, dCam, elevation, azimut); drawAxis(gl, 50, 50, 50); setColor(Color.RED); t.add(new Vec3(sat1.x[0], sat1.x[1], sat1.x[2])); sat1.draw(gl); setColor(Color.BLUE); t.draw(this, gl); sat1.move(dt); }
private void initBuffers(GL3 gl) { // IDs for 2 buffers int[] buffArray = new int[2]; gl.glGenBuffers(buffArray.length, buffArray, 0); vbo = buffArray[0]; assert vbo > 0; // Bind buffer and upload data gl.glBindBuffer(GL3.GL_ARRAY_BUFFER, vbo); gl.glBufferData( GL3.GL_ARRAY_BUFFER, vertexColorData.length * Buffers.SIZEOF_FLOAT, vertexColorDataBuffer, GL3.GL_STATIC_DRAW); gl.glBindBuffer(GL3.GL_ARRAY_BUFFER, 0); // Buffer with the 3 indices required for one triangle ibo = buffArray[1]; assert ibo > 0; gl.glBindBuffer(GL3.GL_ELEMENT_ARRAY_BUFFER, ibo); gl.glBufferData( GL3.GL_ELEMENT_ARRAY_BUFFER, indices.length * Buffers.SIZEOF_SHORT, indicesBuffer, GL3.GL_STATIC_DRAW); gl.glBindBuffer(GL3.GL_ELEMENT_ARRAY_BUFFER, 0); }
private void setTransformation(Matrix4f transformation) { // Compute the modelview matrix by multiplying the camera matrix and // the transformation matrix of the object Matrix4f modelview = new Matrix4f(sceneManager.getCamera().getCameraMatrix()); modelview.mul(transformation); // Set modelview and projection matrices in shader gl.glUniformMatrix4fv( gl.glGetUniformLocation(activeShaderID, "modelview"), 1, false, transformationToFloat16(modelview), 0); gl.glUniformMatrix4fv( gl.glGetUniformLocation(activeShaderID, "projection"), 1, false, transformationToFloat16(sceneManager.getFrustum().getProjectionMatrix()), 0); }
@Override public void init(GLAutoDrawable glad) { System.out.println("init"); canvas.setAutoSwapBufferMode(false); GL3 gl3 = glad.getGL().getGL3(); buildShaders(gl3); programObject.bind(gl3); { programObject.setUniform(gl3, "frustumScale", new float[] {1.0f}, 1); programObject.setUniform(gl3, "zNear", new float[] {1.0f}, 1); programObject.setUniform(gl3, "zFar", new float[] {3.0f}, 1); } programObject.unbind(gl3); initializeVertexBuffer(gl3); gl3.glGenVertexArrays(1, IntBuffer.wrap(vertexArrayObject)); gl3.glBindVertexArray(vertexArrayObject[0]); gl3.glEnable(GL3.GL_CULL_FACE); gl3.glCullFace(GL3.GL_BACK); gl3.glFrontFace(GL3.GL_CW); }
private void setTransformation(Matrix4f transformation) { // Compute the modelview matrix by multiplying the camera matrix and // the transformation matrix of the object Matrix4f modelview = new Matrix4f(sceneManager.getCamera().getCameraMatrix()); modelview.mul(transformation); // Set modelview and projection matrices in shader gl.glUniformMatrix4fv( gl.glGetUniformLocation(activeShaderID, "modelview"), 1, false, transformationToFloat16(modelview), 0); gl.glUniformMatrix4fv( gl.glGetUniformLocation(activeShaderID, "projection"), 1, false, transformationToFloat16(sceneManager.getFrustum().getProjectionMatrix()), 0); int id = gl.glGetUniformLocation(activeShaderID, "camera"); if (id != -1) { Vector3f cop = sceneManager.getCamera().getCenterOfProjection(); gl.glUniform4f(id, cop.x, cop.y, cop.z, 0); } // } else // System.out.println("Could not get location of uniform variable camera"); }
/** * This method is called by the GLRenderPanel to redraw the 3D scene. The method traverses the * scene using the scene manager and passes each object to the rendering method. */ public void display(GLAutoDrawable drawable) { // Get reference to the OpenGL rendering context gl = drawable.getGL().getGL3(); gl.glPolygonMode(GL3.GL_FRONT_AND_BACK, GL3.GL_POINT); // Do some processing at the beginning of the frame beginFrame(); // Traverse scene manager and draw everything SceneManagerIterator iterator = sceneManager.iterator(); while (iterator.hasNext()) { RenderItem r = iterator.next(); if (r.getShape() != null && r.getShape() .checkBoundingSphere(sceneManager.getFrustum(), sceneManager.getCamera(), r.getT())) { draw(r); } } // Do some processing at the end of the frame endFrame(); }
/** * A utility method to load vertex data into an OpenGL "vertex array object" (VAO) for efficient * rendering. The VAO stores several "vertex buffer objects" (VBOs) that contain the vertex * attribute data. * * @param data reference to the vertex data to be loaded into a VAO */ private void initArrayBuffer(GLVertexData data) { // Make a vertex array object (VAO) for this vertex data // and store a reference to it GLVertexArrayObject vao = new GLVertexArrayObject(gl, data.getElements().size() + 1); data.setVAO(vao); // Bind (activate) the VAO for the vertex data in OpenGL. // The subsequent OpenGL operations on VBOs will be recorded (stored) // in the VAO. vao.bind(); // Store all vertex attributes in vertex buffer objects (VBOs) ListIterator<VertexData.VertexElement> itr = data.getElements().listIterator(0); data.getVAO().rewindVBO(); while (itr.hasNext()) { VertexData.VertexElement e = itr.next(); // Bind the vertex buffer object (VBO) gl.glBindBuffer(GL3.GL_ARRAY_BUFFER, data.getVAO().getNextVBO()); // Upload vertex data gl.glBufferData( GL3.GL_ARRAY_BUFFER, e.getData().length * 4, FloatBuffer.wrap(e.getData()), GL3.GL_DYNAMIC_DRAW); } // Bind the default vertex buffer objects gl.glBindBuffer(GL3.GL_ARRAY_BUFFER, 0); // Store the vertex data indices into the last vertex buffer gl.glBindBuffer(GL3.GL_ELEMENT_ARRAY_BUFFER, data.getVAO().getNextVBO()); gl.glBufferData( GL3.GL_ELEMENT_ARRAY_BUFFER, data.getIndices().length * 4, IntBuffer.wrap(data.getIndices()), GL3.GL_DYNAMIC_DRAW); // Bind the default vertex array object. This "deactivates" the VAO // of the vertex data gl.glBindVertexArray(0); }
/** * The main rendering method. * * @param renderItem the object that needs to be drawn */ private void draw(RenderItem renderItem) { // Set the material of the shape to be rendered setMaterial(renderItem.getShape().getMaterial()); // Get reference to the vertex data of the render item to be rendered GLVertexData vertexData = (GLVertexData) renderItem.getShape().getVertexData(); // Check if the vertex data has been uploaded to OpenGL via a // "vertex array object" (VAO). The VAO will store the vertex data // in several "vertex buffer objects" (VBOs) on the GPU. We do this // only once for performance reasons. Once the data is in the VBOs // asscociated with a VAO, it is stored on the GPU and rendered more // efficiently. if (vertexData.getVAO() == null) { initArrayBuffer(vertexData); } // Set modelview and projection matrices in shader (has to be done in // every step, since they usually have changed) setTransformation(renderItem.getT()); // Bind the VAO of this shape. This activates the VBOs that we // associated with the VAO. We already loaded the vertex data into the // VBOs on the GPU, so we do not have to send them again. vertexData.getVAO().bind(); // Try to connect the vertex buffers to the corresponding variables // in the current vertex shader. // Note: This is not part of the vertex array object, because the active // shader may have changed since the vertex array object was initialized. // We need to make sure the vertex buffers are connected to the right // variables in the shader ListIterator<VertexData.VertexElement> itr = vertexData.getElements().listIterator(0); vertexData.getVAO().rewindVBO(); while (itr.hasNext()) { VertexData.VertexElement e = itr.next(); int dim = e.getNumberOfComponents(); // Bind the next vertex buffer object gl.glBindBuffer(GL3.GL_ARRAY_BUFFER, vertexData.getVAO().getNextVBO()); // Tell OpenGL which "in" variable in the vertex shader corresponds // to the current vertex buffer object. // We use our own convention to name the variables, i.e., // "position", "normal", "color", "texcoord", or others if // necessary. int attribIndex = -1; switch (e.getSemantic()) { case POSITION: attribIndex = gl.glGetAttribLocation(activeShaderID, "position"); break; case NORMAL: attribIndex = gl.glGetAttribLocation(activeShaderID, "normal"); break; case COLOR: attribIndex = gl.glGetAttribLocation(activeShaderID, "color"); break; case TEXCOORD: attribIndex = gl.glGetAttribLocation(activeShaderID, "texcoord"); break; } gl.glVertexAttribPointer(attribIndex, dim, GL3.GL_FLOAT, false, 0, 0); gl.glEnableVertexAttribArray(attribIndex); } // Render the vertex buffer objects gl.glDrawElements( GL3.GL_TRIANGLES, renderItem.getShape().getVertexData().getIndices().length, GL3.GL_UNSIGNED_INT, 0); // We are done with this shape, bind the default vertex array gl.glBindVertexArray(0); cleanMaterial(renderItem.getShape().getMaterial()); }
/** This method is called at the end of each frame, i.e., after scene drawing is complete. */ private void endFrame() { // Flush the OpenGL pipeline gl.glFlush(); }
/** * Delete this VBO properly. * * @param gl The global openGL instance. */ public void delete(GL3 gl) { gl.glBindVertexArray(0); gl.glDeleteVertexArrays(1, this.vboPointer); gl.glDeleteBuffers(1, this.bufferPointer); }
/** * Bind the VBO, so that it is ready for use. * * @param gl The global openGL instance. */ public void bind(GL3 gl) { gl.glBindVertexArray(this.vboPointer.get(0)); gl.glBindBuffer(GL3.GL_ARRAY_BUFFER, bufferPointer.get(0)); }
/** * Set up a material for rendering. Activate its shader, and pass the material properties, * textures, and light sources to the shader. * * @param m the material to be set up for rendering */ private void setMaterial(Material m) { // Set up the shader for the material, if it has one if (m != null && m.shader != null) { // Identifier for shader variables int id; // Activate the shader useShader(m.shader); // Activate the diffuse texture, if the material has one if (m.diffuseMap != null) { // OpenGL calls to activate the texture gl.glActiveTexture(GL3.GL_TEXTURE0); // Work with texture unit 0 gl.glEnable(GL3.GL_TEXTURE_2D); gl.glBindTexture(GL3.GL_TEXTURE_2D, ((GLTexture) m.diffuseMap).getId()); gl.glTexParameteri(GL3.GL_TEXTURE_2D, GL3.GL_TEXTURE_MAG_FILTER, GL3.GL_LINEAR); gl.glTexParameteri(GL3.GL_TEXTURE_2D, GL3.GL_TEXTURE_MIN_FILTER, GL3.GL_LINEAR); // We assume the texture in the shader is called "myTexture" id = gl.glGetUniformLocation(activeShaderID, "myTexture"); gl.glUniform1i( id, 0); // The variable in the shader needs to be set to the desired texture unit, i.e., 0 } // Pass a default light source to shader String lightString = "lightDirection[" + 0 + "]"; id = gl.glGetUniformLocation(activeShaderID, lightString); if (id != -1) gl.glUniform4f(id, 0, 0, 1, 0.f); // Set light direction else System.out.print("Could not get location of uniform variable " + lightString + "\n"); int nLights = 1; // Iterate over all light sources in scene manager (overwriting the default light source) Iterator<Light> iter = sceneManager.lightIterator(); Light l; if (iter != null) { nLights = 0; while (iter.hasNext() && nLights < 8) { l = iter.next(); // Pass light direction to shader, we assume the shader stores it in an array // "lightDirection[]" lightString = "lightDirection[" + nLights + "]"; id = gl.glGetUniformLocation(activeShaderID, lightString); if (id != -1) gl.glUniform4f( id, l.direction.x, l.direction.y, l.direction.z, 0.f); // Set light direction else System.out.print("Could not get location of uniform variable " + lightString + "\n"); nLights++; } // Pass number of lights to shader, we assume this is in a variable "nLights" in the shader id = gl.glGetUniformLocation(activeShaderID, "nLights"); if (id != -1) gl.glUniform1i(id, nLights); // Set number of lightrs // Only for debugging // else // System.out.print("Could not get location of uniform variable nLights\n"); } } }
/** * Deletes this Texture from memory. * * @param gl The current OpenGL instance. */ public void delete(GL3 gl) { gl.glDeleteTextures(1, pointer); }