PlasmaFractal script for Unity (C#) great for heightmaps


SUBMITTED BY: KaiMolan

DATE: Aug. 21, 2015, 9 p.m.

UPDATED: Aug. 21, 2015, 9:16 p.m.

FORMAT: C#

SIZE: 3.3 kB

HITS: 930

  1. using System;
  2. namespace Assets.Scripts.LevelGeneration
  3. {
  4. public class PlasmaFractal
  5. {
  6. public double Roughness { get; private set; }
  7. public double BigSize { get; private set; }
  8. private readonly Random _random = new Random();
  9. // generates and returns the plasma fractal
  10. public double[,] Generate(int width, int height, double roughness)
  11. {
  12. var points = new double[width + 1, height + 1];
  13. var c1 = _random.NextDouble();
  14. var c2 = _random.NextDouble();
  15. var c3 = _random.NextDouble();
  16. var c4 = _random.NextDouble();
  17. Roughness = roughness;
  18. BigSize = width + height;
  19. DivideGrid(ref points, 0, 0, width, height, c1, c2, c3, c4);
  20. return points;
  21. }
  22. private void DivideGrid(ref double[,] points, double x, double y,
  23. double width, double height,
  24. double c1, double c2, double c3, double c4)
  25. {
  26. var newWidth = Math.Floor(width / 2);
  27. var newHeight = Math.Floor(height / 2);
  28. if (width > 1 || height > 1)
  29. {
  30. var middle = ((c1 + c2 + c3 + c4) / 4) + Displace(newWidth + newHeight);
  31. var edge1 = ((c1 + c2) / 2);
  32. var edge2 = ((c2 + c3) / 2);
  33. var edge3 = ((c3 + c4) / 2);
  34. var edge4 = ((c4 + c1) / 2);
  35. middle = Rectify(middle);
  36. edge1 = Rectify(edge1);
  37. edge2 = Rectify(edge2);
  38. edge3 = Rectify(edge3);
  39. edge4 = Rectify(edge4);
  40. DivideGrid(ref points, x, y, newWidth, newHeight,
  41. c1, edge1, middle, edge4);
  42. DivideGrid(ref points, x + newWidth, y,
  43. width - newWidth, newHeight,
  44. edge1, c2, edge2, middle);
  45. DivideGrid(ref points, x + newWidth, y + newHeight,
  46. width - newWidth, height - newHeight,
  47. middle, edge2, c3, edge3);
  48. DivideGrid(ref points, x, y + newHeight,
  49. newWidth, height - newHeight,
  50. edge4, middle, edge3, c4);
  51. }
  52. else
  53. {
  54. var c = (c1 + c2 + c3 + c4) / 4;
  55. points[(int)x, (int)y] = c;
  56. if (width == 2)
  57. {
  58. points[(int)x + 1, (int)y] = c;
  59. }
  60. if (height == 2)
  61. {
  62. points[(int)x, (int)y + 1] = c;
  63. }
  64. if (width == 2 && height == 2)
  65. {
  66. points[(int)x + 1, (int)y + 1] = c;
  67. }
  68. }
  69. }
  70. private static double Rectify(double number)
  71. {
  72. if (number < 0)
  73. {
  74. number = 0;
  75. }
  76. else if (number > 1.0)
  77. {
  78. number = 1.0;
  79. }
  80. return number;
  81. }
  82. private double Displace(double smallSize)
  83. {
  84. var max = smallSize / BigSize * Roughness;
  85. return (_random.NextDouble() - 0.5) * max;
  86. }
  87. }
  88. }

comments powered by Disqus