Ruslan
Ruslan

Reputation: 31

Convert 4 uint8 (byte) to float32 in GLSL

I have a vertex buffer object containing vertex data for a model. However the layout is a bit weird. The vertex uses 4 x uint_8 for the position and 4 x int_8 for the normal data. The texture position data is appended at the end, with 4 x uint_8 representing a float value, that I can access with a offset value. Using 8 bytes would give me 2 float values that i can use in a vec2 for texture coordinates.

The layout is basically [ [4 x uint_8 (vertex pos)] | [ 4 x int_8 (vertex_normal) ] | ... (alternating pos and norm) | [ 4x uint_8 ] (byte data for float value)].

In my hit shader I read the buffer as an array of int_8 and I am able to read the vertex data without problems. However I can't seem to find a way to construct a float value out of the 4 bytes used to represent it.

I can of course change the stucture of the data, but I have legacy code that relies on this structure and changing it would break the rest of the program. I could also create a new vertex buffer, but since I already have the data and can read it without problems it would only take up more space and would be redundant in my opinion.

There is probably a way to define the structure before, so that buffer information has the right format in the shader. I know that you can set a format for the vertex input in a pipeline, but since this is a raytracing pipeline, I possibly cannot use this feature. But maybe I am wrong.

So the final question is: Is it possible to construct a float value out of 4 uint_8 values in a glsl shader, or should I consider changing the vertex buffer? Or is there maybe another way to define the data?

Upvotes: 1

Views: 984

Answers (1)

Ruslan
Ruslan

Reputation: 31

I have found a solution that works for me.

Basically I use two layouts with the same set and binding, except for the textures and normals the buffer is read as an array of int8 values. The buffer in the second layout is read as an array of vec2s. Since the buffer reads the original byte data it can pack it into a vec2 correctly.

So for example the byte data

[31, 133, 27, 63, 84, 224, 75, 63]

would give me a vec2 of

(0.6075, 0.7964)

which is what I wanted.

Of course this solution is not perfect, but for now it is enough. If you know any prettier solutions, feel free to share them!

Upvotes: 1

Related Questions