Reputation: 499
I am currently trying to use an arraybuffer with views, to combine 3 float32 (x,y,z) and 4 uint8 (r,g,b,a) into a single data stream that I can pass to my web gl application.
Problem is the when I use the array buffer nothing works, code as follows:
var buffer = new ArrayBuffer(nbrOfVertices * 16);
var positionView = new DataView(buffer);
for (var j = 0; j < nbrOfVertices; j++)
{
positionView.setFloat32((j*16),meshVertexPositions[(j*7)]);
positionView.setFloat32((j*16)+4,meshVertexPositions[(j*7)+1]);
positionView.setFloat32((j*16)+8,meshVertexPositions[(j*7)+2]);
}
gl.bufferData(gl.ARRAY_BUFFER,buffer,gl.STATIC_DRAW);
I know all the other code is correct, because when I use this instead it works:
var buffer = new Float32Array(nbrOfVertices * 4);
for (var j = 0; j < nbrOfVertices; j++)
{
buffer[(j*4)] = meshVertexPositions[(j*7)];
buffer[(j*4)+1] = meshVertexPositions[(j*7)+1];
buffer[(j*4)+2] = meshVertexPositions[(j*7)+2];
}
gl.bufferData(gl.ARRAY_BUFFER,buffer,gl.STATIC_DRAW);
Any idea why my arraybuffer code (first example) isn't working? Just for clarification, when I say it doesn't work, I mean nothing renders, although I don't see any errors when I run it (in chrome developer console or in webgl inspector)
Upvotes: 2
Views: 1498
Reputation:
You should not use a DataView
for this. You'd use multiple views on the same buffer like this
var buffer = new ArrayBuffer(nbrOfVertices * 16);
var floatView = new Float32Array(buffer);
var uint8View = new Uint8Array(buffer);
for (var j = 0; j < nbrOfVertices; ++j) {
var floatVertexOffset = j * 4;
floatView[floatVertexOffset + 0] = meshVertexPositions[?? + 0];
floatView[floatVertexOffset + 1] = meshVertexPositions[?? + 1];
floatView[floatVertexOffset + 2] = meshVertexPositions[?? + 2];
var uint8ColorOffset = j * 16 + 12;
unit8View[uint8ColorOffset + 0] = meshVertexColors[?? + 0];
unit8View[uint8ColorOffset + 1] = meshVertexColors[?? + 1];
unit8View[uint8ColorOffset + 2] = meshVertexColors[?? + 2];
unit8View[uint8ColorOffset + 3] = meshVertexColors[?? + 3];
}
The reason you would not use a DataView
is because you want the native float and RGBA formats for GPU data. DataView
is for reading/writing data in a specific endian format regardless of the native platform's endianess.
In other words, if you use DataView
you'll end up uploading the wrong type of data to the GPU. You use DataView
to read into native format or convert native data to specific binary formats.
Upvotes: 3