noise2D.cs 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. //
  2. // Description : Array and textureless GLSL 2D simplex noise function.
  3. // Author : Ian McEwan, Ashima Arts.
  4. // Maintainer : stegu
  5. // Lastmath.mod : 20110822 (ijm)
  6. // License : Copyright (C) 2011 Ashima Arts. All rights reserved.
  7. // Distributed under the MIT License. See LICENSE file.
  8. // https://github.com/ashima/webgl-noise
  9. // https://github.com/stegu/webgl-noise
  10. //
  11. using static Unity.Mathematics.math;
  12. namespace Unity.Mathematics
  13. {
  14. public static partial class noise
  15. {
  16. public static float snoise(float2 v)
  17. {
  18. float4 C = float4(0.211324865405187f, // (3.0-math.sqrt(3.0))/6.0
  19. 0.366025403784439f, // 0.5*(math.sqrt(3.0)-1.0)
  20. -0.577350269189626f, // -1.0 + 2.0 * C.x
  21. 0.024390243902439f); // 1.0 / 41.0
  22. // First corner
  23. float2 i = floor(v + dot(v, C.yy));
  24. float2 x0 = v - i + dot(i, C.xx);
  25. // Other corners
  26. float2 i1;
  27. //i1.x = math.step( x0.y, x0.x ); // x0.x > x0.y ? 1.0 : 0.0
  28. //i1.y = 1.0 - i1.x;
  29. i1 = (x0.x > x0.y) ? float2(1.0f, 0.0f) : float2(0.0f, 1.0f);
  30. // x0 = x0 - 0.0 + 0.0 * C.xx ;
  31. // x1 = x0 - i1 + 1.0 * C.xx ;
  32. // x2 = x0 - 1.0 + 2.0 * C.xx ;
  33. float4 x12 = x0.xyxy + C.xxzz;
  34. x12.xy -= i1;
  35. // Permutations
  36. i = mod289(i); // Avoid truncation effects in permutation
  37. float3 p = permute(permute(i.y + float3(0.0f, i1.y, 1.0f)) + i.x + float3(0.0f, i1.x, 1.0f));
  38. float3 m = max(0.5f - float3(dot(x0, x0), dot(x12.xy, x12.xy), dot(x12.zw, x12.zw)), 0.0f);
  39. m = m * m;
  40. m = m * m;
  41. // Gradients: 41 points uniformly over a line, mapped onto a diamond.
  42. // The ring size 17*17 = 289 is close to a multiple of 41 (41*7 = 287)
  43. float3 x = 2.0f * frac(p * C.www) - 1.0f;
  44. float3 h = abs(x) - 0.5f;
  45. float3 ox = floor(x + 0.5f);
  46. float3 a0 = x - ox;
  47. // Normalise gradients implicitly by scaling m
  48. // Approximation of: m *= inversemath.sqrt( a0*a0 + h*h );
  49. m *= 1.79284291400159f - 0.85373472095314f * (a0 * a0 + h * h);
  50. // Compute final noise value at P
  51. float gx = a0.x * x0.x + h.x * x0.y;
  52. float2 gyz = a0.yz * x12.xz + h.yz * x12.yw;
  53. float3 g = float3(gx,gyz);
  54. return 130.0f * dot(m, g);
  55. }
  56. }
  57. }