package com.peterhi.ui.gl;
import java.nio.Buffer;
import java.nio.FloatBuffer;
import java.util.Arrays;
import javax.media.opengl.GL;
import javax.media.opengl.GL3;
import javax.media.opengl.GLException;
import com.jogamp.opengl.util.GLBuffers;
public final class GLVertexBuffer extends GLObject {
private float[] data;
public GLVertexBuffer(GL gl) {
super(gl);
int[] id = new int[1];
glInvoke("glGenBuffers",
int.class, 1,
int[].class, id,
int.class, 0
);
setId(id[0]);
}
public GLVertexBuffer(GL gl, float[] data) {
this(gl);
bind();
setData(data);
unbind();
}
public float[] getData() {
if (isDisposed()) {
throw new GLException();
}
return Arrays.copyOf(data, data.length);
}
public void setData(float[] value) {
if (value == null) {
throw new NullPointerException();
}
if (value.length == 0) {
throw new IllegalArgumentException();
}
if (isDisposed()) {
throw new GLException();
}
FloatBuffer buffer = GLBuffers.newDirectFloatBuffer(value);
int fs = Float.SIZE / Byte.SIZE;
glInvoke("glBufferData",
int.class, GL3.GL_ARRAY_BUFFER,
long.class, value.length * fs,
Buffer.class, buffer,
int.class, GL3.GL_STATIC_DRAW
);
data = Arrays.copyOf(value, value.length);
}
public void bind() {
if (isDisposed()) {
throw new GLException();
}
glInvoke("glBindBuffer",
int.class, GL3.GL_ARRAY_BUFFER,
int.class, getId()
);
}
public void unbind() {
if (isDisposed()) {
throw new GLException();
}
glInvoke("glBindBuffer",
int.class, GL3.GL_ARRAY_BUFFER,
int.class, 0
);
}
@Override
public void dispose() {
if (isDisposed()) {
return;
}
glInvoke("glDeleteBuffers",
int.class, 1,
int[].class, new int[] { getId() },
int.class, 0
);
super.dispose();
}
}