Reputation: 187
When I use FloatBuffers, they take up more and more memory over time. I use a float buffer to put a transormation matrix in it, and then I upload it to the shader. So I call the method, which creates the float buffer, every frame.
private static FloatBuffer matrixBuffer;
public void uploadUniformMatrix4f(String name, Matrix4f matrix4f)
{
// Create a float buffer and put the matrix in it
matrixBuffer = BufferUtils.createFloatBuffer(16);
matrix4f.get(matrixBuffer);
// Upload the float buffer as a matrix
GL20.glUniformMatrix4fv(getUniformLocation(name), false, matrixBuffer);
}
I already tried memFree(matrixBuffer);
and matrixBuffer.clear();
but nothing worked.
Upvotes: 2
Views: 360
Reputation: 2937
BufferUtils.createFloatBuffer(16) creates new buffer each time your are calling it, outside of JVM heap. I.e. java garbage collector only have reference to the ByteBuffer object, and not for it's data unlike an float[] data = new float[16];
so GC will clear native memory at time it need to clear JVM heap.
BufferUtils approach is not recommended by lwjgl.
LWJGL versions before 3 relied exclusively on allocateDirect(), via the org.lwjgl.BufferUtils class. This class is still there in 3, for backwards-compatibility, but its use is highly discouraged. The reason is simple, allocateDirect() is horrible:
You can use following approach to transfer OpenGL matrices effectively.
import static org.lwjgl.opengl.GL20.glUniformMatrix4fv;
......
try (MemoryStack stack = MemoryStack.stackPush()) {
final FloatBuffer matrixBuffer = stack.mallocFloat(16);
// if you have more matrices like mvp, model, view, projection, normal
// you don't have to create new memory stack for them
// simply call stack.mallocFloat(16) as many times as you need
matrix4f.get(matrixBuffer);
glUniformMatrix4fv(getUniformLocation(name), false, matrixBuffer);
// call OpenGL shader program code here.
// When this try block ends - matrixBuffer native memory will be invalid. And OpenGL will crash when accessing the uniform memory already freed
}
Upvotes: 2