package de.lv.jvoxgl.render;
import java.nio.FloatBuffer;
import java.util.ArrayList;
import java.util.List;
import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL15;
import org.lwjgl.opengl.GL20;
import org.lwjgl.opengl.GL30;
public class Renderer {
private List<TexturedVertex> vertices = new ArrayList<TexturedVertex>();
private int vbo,vao,vertice_count,size;
private ShaderProgram shader;
public Renderer(ShaderProgram shader){
//Create Buffers
vbo = GL15.glGenBuffers();
vao = GL30.glGenVertexArrays();
this.setShader(shader);
setSize(1);
}
/**
* Add Vertices
* @param vertices
*/
public void addVertices(List<TexturedVertex> vertices){
this.vertices.addAll(vertices);
}
/**
* Fills the Buffer with the Vertices
*/
public void fill(){
this.vertice_count = this.vertices.size();
FloatBuffer fb = BufferUtils.createFloatBuffer(vertice_count*3); //Create Float-Buffer
for(TexturedVertex tv: vertices){ //Loop to all Vertices and put into FloatBuffer
fb.put(tv.getX()*size);
fb.put(tv.getY()*size);
fb.put(tv.getZ()*size);
}
fb.flip(); //Flips the FloatBuffer
//Bind the Buffers
GL30.glBindVertexArray(vao);
GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, vbo);
//Put Vertex Information into the Buffer
GL15.glBufferData(GL15.GL_ARRAY_BUFFER, fb, GL15.GL_STATIC_DRAW);
//Unbind the Buffers
GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);
GL30.glBindVertexArray(0);
fb.clear();
this.vertices.clear();
}
/**
* Renders the Vertices
*/
public void render(){
if(shader != null)shader.bind(); //Binds the Shaders
//Bind the Buffers
GL30.glBindVertexArray(vao);
GL20.glEnableVertexAttribArray(0);
GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, vbo);
//Render
GL20.glVertexAttribPointer(0, 3, GL11.GL_FLOAT, false, 0, 0);
GL11.glDrawArrays(GL11.GL_QUADS, 0, vertice_count);
//Unbind the Buffers
GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);
GL20.glDisableVertexAttribArray(0);
GL30.glBindVertexArray(0);
if(shader != null)shader.unbind(); //Unbinds the Shader
}
/**
* Clears the Buffers
*/
public void destroy(){
GL15.glDeleteBuffers(this.vao);
GL15.glDeleteBuffers(this.vbo);
vertices.clear();
}
/**
* @return the size
*/
public int getSize() {
return size;
}
/**
* @param size the size to set
*/
public void setSize(int size) {
this.size = size;
}
/**
* @return the shader
*/
public ShaderProgram getShader() {
return shader;
}
/**
* @param shader the shader to set
*/
public void setShader(ShaderProgram shader) {
this.shader = shader;
}
}