Advertisement
Guest User

Unity Stochastic Texture Sampling

a guest
Oct 14th, 2019
8,056
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.37 KB | None | 0 0
  1. //hash for randomness
  2. float2 hash2D2D (float2 s)
  3. {
  4. //magic numbers
  5. return frac(sin(fmod(float2(dot(s, float2(127.1,311.7)), dot(s, float2(269.5,183.3))), 3.14159))*43758.5453);
  6. }
  7.  
  8. //stochastic sampling
  9. float4 tex2DStochastic(sampler2D tex, float2 UV)
  10. {
  11. //triangle vertices and blend weights
  12. //BW_vx[0...2].xyz = triangle verts
  13. //BW_vx[3].xy = blend weights (z is unused)
  14. float4x3 BW_vx;
  15.  
  16. //uv transformed into triangular grid space with UV scaled by approximation of 2*sqrt(3)
  17. float2 skewUV = mul(float2x2 (1.0 , 0.0 , -0.57735027 , 1.15470054), UV * 3.464);
  18.  
  19. //vertex IDs and barycentric coords
  20. float2 vxID = float2 (floor(skewUV));
  21. float3 barry = float3 (frac(skewUV), 0);
  22. barry.z = 1.0-barry.x-barry.y;
  23.  
  24. BW_vx = ((barry.z>0) ?
  25. float4x3(float3(vxID, 0), float3(vxID + float2(0, 1), 0), float3(vxID + float2(1, 0), 0), barry.zyx) :
  26. float4x3(float3(vxID + float2 (1, 1), 0), float3(vxID + float2 (1, 0), 0), float3(vxID + float2 (0, 1), 0), float3(-barry.z, 1.0-barry.y, 1.0-barry.x)));
  27.  
  28. //calculate derivatives to avoid triangular grid artifacts
  29. float2 dx = ddx(UV);
  30. float2 dy = ddy(UV);
  31.  
  32. //blend samples with calculated weights
  33. return mul(tex2D(tex, UV + hash2D2D(BW_vx[0].xy), dx, dy), BW_vx[3].x) +
  34. mul(tex2D(tex, UV + hash2D2D(BW_vx[1].xy), dx, dy), BW_vx[3].y) +
  35. mul(tex2D(tex, UV + hash2D2D(BW_vx[2].xy), dx, dy), BW_vx[3].z);
  36. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement