I'm trying to figure out how exactly buffers work in WebGL and I'm a little stuck here. Below will be my guesses - please confirm or deny it.
const positions = new Float32Array([
-1, 1,
-0.5, 0,
-0.25, 0.25,
]);
let buffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
gl.bufferData(gl.ARRAY_BUFFER, positions, gl.STATIC_DRAW);
gl.bindBuffer(gl.ARRAY_BUFFER, null);
- We create an array of floats on RAM via JS.
- WebGL creates an empty buffer directly on GPU and returns a reference on this buffer to JS. Now variable
buffer
is a pointer. - Set pointer on the buffer to
gl.ARRAY_BUFFER
. - Now we copy data from RAM to GPU buffer.
- Unbind buffer from
gl.ARRAY_BUFFER
( but the buffer is still available on GPU and we can rebind it more times).
So why we can't just call createBuffer()
with positions
instead of using ARRAY_BUFFER
as a bridge between JS and GPU? Are these only limitations of OpenGL API or we have some strong reason to don't do this? Correct me if I'm wrong, but the allocation of memory with the known size is faster than allocating some memory and reallocation with positions
size after we call bufferData
.