- Home /
CG shader float3 to float pack/unpack functions
I want to use pack/and unpack functions in a CG shader in Unity. They are listed here: http://http.developer.nvidia.com/Cg/pack.html and here: http://http.developer.nvidia.com/Cg/unpack.html
I want to store a float3 (a normal where precision is not of high importance) in a single float (floating-point RenderTexture) and extract the normal in another shader. Therefore, I want to use a combination of pack4_byte
and unpack_4byte
.
I get shader compiler errors for shader model 2.0, 3.0 and warnings for 4.0 (which are actually the same errors!?)
Do I have to use extensions for that?
I also tried to use DecodeFloatRGBA
and EncodeFloatRGBA
, but I think that they are meant to be used to pack a float value into RGBA low precision render targets. In my case I tried to use them the other way round, but I seem to get wrong values.
Thanks for your help! :-)
EDIT: I found this Nvidia extension: NV_fragment_program
This extension includes pack_4clamp1s
and unpack_4clamp1s
Maybe this would be the correct way to solve my problem? How would I use such extensions?
Answer by Summit_Peak · Jan 03, 2015 at 11:11 PM
Here's a way to pack a float3 into a float and back:
public static float f3_f(float3 c)
{
return dot(round(c * 255), new float3(65536, 256, 1));
}
public static float3 f_f3(float f)
{
return frac(f / new float3(16777216, 65536, 256));
}
Here are the corresponding HLSL/CG #defines:
#define f3_f(c) (dot(round((c) * 255), float3(65536, 256, 1)))
#define f_f3(f) (frac((f) / float3(16777216, 65536, 256)))
For float4, see: http://docs.unity3d.com/$$anonymous$$anual/SL-BuiltinIncludes.html float4 EncodeFloatRGBA (float v) - encodes [0..1) range float into RGBA color, for storage in low precision render target. float DecodeFloatRGBA (float4 enc) - decodes RGBA color into a float.
Your answer
Follow this Question
Related Questions
How to force the compilation of a shader in Unity? 5 Answers
How to determine shader center? 0 Answers
Why does this IOS / OGLES shader not match PC version? 0 Answers
Use multiple materials? 1 Answer