cellular2x2.cs 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. // Cellular noise ("Worley noise") in 2D in GLSL.
  2. // Copyright (c) Stefan Gustavson 2011-04-19. All rights reserved.
  3. // This code is released under the conditions of the MIT license.
  4. // See LICENSE file for details.
  5. // https://github.com/stegu/webgl-noise
  6. using static Unity.Mathematics.math;
  7. namespace Unity.Mathematics
  8. {
  9. public static partial class noise
  10. {
  11. // Cellular noise, returning F1 and F2 in a float2.
  12. // Speeded up by umath.sing 2x2 search window instead of 3x3,
  13. // at the expense of some strong pattern artifacts.
  14. // F2 is often wrong and has sharp discontinuities.
  15. // If you need a smooth F2, use the slower 3x3 version.
  16. // F1 is sometimes wrong, too, but OK for most purposes.
  17. public static float2 cellular2x2(float2 P)
  18. {
  19. const float K = 0.142857142857f; // 1/7
  20. const float K2 = 0.0714285714285f; // K/2
  21. const float jitter = 0.8f; // jitter 1.0 makes F1 wrong more often
  22. float2 Pi = mod289(floor(P));
  23. float2 Pf = frac(P);
  24. float4 Pfx = Pf.x + float4(-0.5f, -1.5f, -0.5f, -1.5f);
  25. float4 Pfy = Pf.y + float4(-0.5f, -0.5f, -1.5f, -1.5f);
  26. float4 p = permute(Pi.x + float4(0.0f, 1.0f, 0.0f, 1.0f));
  27. p = permute(p + Pi.y + float4(0.0f, 0.0f, 1.0f, 1.0f));
  28. float4 ox = mod7(p) * K + K2;
  29. float4 oy = mod7(floor(p * K)) * K + K2;
  30. float4 dx = Pfx + jitter * ox;
  31. float4 dy = Pfy + jitter * oy;
  32. float4 d = dx * dx + dy * dy; // d11, d12, d21 and d22, squared
  33. // Sort out the two smallest distances
  34. // Do it right and find both F1 and F2
  35. d.xy = (d.x < d.y) ? d.xy : d.yx; // Swap if smaller
  36. d.xz = (d.x < d.z) ? d.xz : d.zx;
  37. d.xw = (d.x < d.w) ? d.xw : d.wx;
  38. d.y = min(d.y, d.z);
  39. d.y = min(d.y, d.w);
  40. return sqrt(d.xy);
  41. }
  42. }
  43. }