Tenemos la intención de cambiar la representación de JavaScript de una matriz de valores float32 a una matriz de uint8 bytes. Está implícito que hacerlo podría ayudarnos a transferir los datos de manera más eficiente a través de solicitudes HTTP.
Para ello, hemos probado:
var vertexBuffer = ...; // Float32Array console.log('vertex buffer =', vertexBuffer); console.log('vertex buffer byte length = ', vertexBuffer.byteLength) var arr = new Uint8Array(vertexBuffer); console.log('converted to Uint8Array: ', arr); console.log('Byte length = ', arr.byteLength); console.log('Byte length / 4 = ', arr.byteLength / 4);Los registros son:
¡El tamaño de Float32Array es 84942 y eso es lo mismo para el Uint8Array resultante!
¡Lo que significa que cada valor de float32 se convierte en un solo uint8 ! ¡Qué no es lo que pretendemos hacer! ¿Derecha?
Pretendemos interpretar cada float32 como cuatro valores uint8 . ¿Cómo podemos hacerlo de la manera más eficiente? El cambio de interpretación no debería requerir ningún cálculo, ¿verdad?
Está implícito que hacerlo podría ayudarnos a transferir los datos de manera más eficiente a través de solicitudes HTTP.
Ese no es el caso a menos que realmente desee truncar la precisión de los valores de coma flotante a enteros de 8 bits. Simplemente envíe el vertexArray.buffer (un ArrayBuffer), los "datos sin procesar" de la matriz, por cualquier método que desee. (Por supuesto, puede comprimir los datos antes de enviarlos, si ese es su problema).
A continuación, puede reconstruir un Float32Array de un ArrayBuffer que reciba pasándolo al constructor Float32Array .
Para demostrar estas conversiones:
> arr = new Float32Array([Math.sqrt(2), Math.sqrt(3)]) // An array of 2 floats, 4 bytes each Float32Array(2) [1.4142135381698608, 1.7320507764816284, buffer: ArrayBuffer(8), byteLength: 8, byteOffset: 0, length: 2] > bytes = new Uint8Array(arr.buffer) // The same floats but interpreted as 8-bit values (8 integers, 1 byte each) Uint8Array(8) [243, 4, 181, 63, 215, 179, 221, 63, buffer: ArrayBuffer(8), byteLength: 8, byteOffset: 0, length: 8] > bytes[1] = 123 // Modifying the byte array // (since an ArrayBuffer is just opaque memory, it can't be modified, // but we can modify the byte interpretation of it) 123 > new Float32Array(bytes.buffer) // (this step is not strictly necessary; // modifying `bytes` will have changed the underlying buffer // used by the original `Float32Array` since we didn't copy it) // Reinterpreting the modified bytes as floats // (see how the first value has slightly changed) Float32Array(2) [1.4178451299667358, 1.7320507764816284, buffer: ArrayBuffer(8), byteLength: 8, byteOffset: 0, length: 2]