Advertisement
haowan

CG: Packing 3 floats into 1 for shaders

Jan 9th, 2015
229
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.78 KB | None | 0 0
  1. // Modification of Cameron.'s code from http://forum.unity3d.com/threads/can-i-send-data-as-w-via-vertex-data.114111/#post-769621
  2. // by Alex May 2015
  3.  
  4. // Packs a normalised direction vector into a single float
  5. float PackVector3(Vector3 vector3)
  6. {  
  7.     // Scale  Bias values to 8 bit bytes in range of 0 to 255
  8.     int x = PackFloat(vector3.x);
  9.     int y = PackFloat(vector3.y);
  10.     int z = PackFloat(vector3.z);
  11.    
  12.     uint  packedByte  = (uint)((x << 20) | (y << 10) | z);
  13.     float packedFloat = (float)((double)packedByte / (double)(1<<30));
  14.    
  15.     return packedFloat;
  16. }
  17.    
  18. // UnPack normal from float
  19. Vector3 UnPackVector3(float src)
  20. {
  21.     Vector3 output = Vector3.zero;
  22.    
  23.     // Unpack to 0...1 range
  24.     output.x = Frac(src);
  25.     output.y = Frac(src * 1024.0f);
  26.     output.z = Frac(src * 1048576.0f);
  27.    
  28.     // Bias to -1..1 range
  29.     output = (output * 2f) - Vector3.one;
  30.    
  31.     return output;     
  32. }
  33.    
  34.    
  35.    
  36. void TestPackVector3(Vector3 normal)
  37. {
  38.     normal.Normalize();
  39.    
  40.     float f = PackVector3(normal);
  41.     Vector3 result = UnPackVector3(f).normalized;
  42.     Vector3 error  = normal - result;
  43.    
  44.     string s = "";
  45.    
  46.     s += "Testing: (" + normal.x + ", " + normal.y + ", " + normal.z + ")\n";
  47.     s += "Result : (" + result.x + ", " + result.y + ", " + result.z + ")\n";
  48.     s += "Error  : (" + error.x  + ", " + error.y  + ", " + error.z  + ")\n";
  49.    
  50.     Debug.Log(s);      
  51. }
  52.    
  53.    
  54. // Helper method that converts a float in the
  55. // range(-1..1) to a 10 bit int in range(0..1023)
  56. int PackFloat(float x)
  57. {
  58.     x = (x + 1.0f) * 0.5f;   // Bias
  59.  
  60.     return (int)(x*1023.0f); // Scale  
  61. }
  62.    
  63.    
  64. // Helper method to emulate CG's frac(x)
  65. float Frac(float x)
  66. {      
  67.     return x - Mathf.Floor(x); 
  68. }
  69.  
  70.  
  71. /* Cg code for your shader
  72.  
  73. inline float3 UnPackVector3(float src) {
  74.     return (frac(float3(1.0f, 1024.0f, 1048576.0f) * src) * 2) - 1;
  75. }
  76.  
  77. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement