How can I encode four unsigned bytes (0-255) to and from the float using HLSL?

I came across a problem when one of my hlsl shaders requires multiple texture searches per pixel. My 2-dimensional textures are fixed at 256 * 256, so in order to access any given texel with this limitation in mind, two bytes should be enough. My idea is to put two xy coordinates in each float, giving me eight xy coordinates in the pixel space when they are packed in a Vector4 format image. These eight coordinates are then used to select another texture (s).

The reason for this is the preservation of graphic memory and an attempt to optimize the processing time, since then I do not need to repeatedly search for textures.

By the way: does anyone know if encoding / decoding 16 bytes from / to 4 floats using 1 sample is slower than 4 samples with non-encoded data?


Edit: this is for Shader Model 3

+3
source share
1 answer

If you are aiming for SM 4.0-SM 5.0, you can use Binary Castsand Bitwise operations:

uint4 myUInt4 = asuint(myFloat4);

uint x0 = myUInt4.x & 0x000000FF; //extract two xy-coordinates (x0,y0), (x1,y1)
uint y0 = (myUInt4.x & 0x0000FF00) >> 8;
uint x1 = (myUInt4.x & 0x00FF0000) >> 16;
uint y1 = (myUInt4.x & 0xFF000000) >> 24;

//repeat operation for .y .z and .w coordinates

For previous shader models, I think this can be more complicated as it depends on FP accuracy.

+1
source

Source: https://habr.com/ru/post/1746703/


All Articles