Javascript how to reproduce GLSL floating point matrix operation on CPU Uint8array

128 views Asked by At

I have some data in a Uint8array, ( a list of 3d x,y,z coordinates). I need to perform some floating point operations on. (matrix rotation transform multiplication) on this 3d vectors. I am using the http://glmatrix.net/ library for the calculations.

The data is coming from a 3rd party API that packages it as Uint8Array The vertex data is formatted in sets of 8 [x,y,z,w,r,g,b,a]

Up until now, I have been performing this operation on the GPU, passing this Uint8array and the rotation matrix to GLSL. I am moving the operation to a CPU based script that is executed offline.

Update Another piece of the equation. The offline script is a node.js CLI script that writes the final buffer to stdout and eventually to a file using the unix > operator. I then load this in the final app and wrap the arrayBuffer with a typedArray constructor.

When executed in GLSL, the operation looks like:

matrix * vec4(vert.x, vert.y, vert.z, 1.0)

and my results look like: enter image description here

Now on the CPU My current code attempt is:

  const vertData = getVertDataUint8();
  const rotation = mat4.fromRotation(mat4.identity([]), -Math.PI/2, [1,0,0]);
  var i = 0;
  while(i<vertData.length){
    const rotatedVerts = vec4.transformMat4([],
                                            vec4.clone([vertData[i],vertData[i+1],vertData[i+2], 1]),
                                            rotation);

    vertData[i] = rotatedVerts[0];
    vertData[i+1] = rotatedVerts[1];
    vertData[i+2] = rotatedVerts[2];
    i+=8;
  }

and my results look like: enter image description here

I noticed that when re assigning the values to the vertData, specifically negative values they were being cast as ints. example -10 ~= 246

you can reproduce in a browser console with:

var u = new Uint8Array(1)
undefined
u[0] = -10
-10
u[0]
246

I have tried converting the Uint8Array into a Float32Array by wrapping it in the Float32Array constructor and using Float32Array.from but it seems to produce the same results.

1

There are 1 answers

2
Bellian On BEST ANSWER

First of all: Consider using the Float32Array for your vertex information. Otherwise there can be massive problems. Or at least use non unsigned data formats.

Now your Problem:

Since Uint8Array is a unsigned data format it will only save positive 8-bit values. All negative values will be interpreted as positives (10000000 as signed integer is -128 but as unsigned it is 128)

But i guess the real problem is another one. From the code i assume that you are saving the vertex information like this:

[X1,Y1,Z1,...] or [X1,Y1,Z1,W1,...]

Your loop will iterate over the array in steps of 8 since i+=8;. Therefore at least every second vertex will be skipped in your script.