Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /// <summary>
- /// Generates a grayscale image from Voronoi noise, simulating district zones
- /// </summary>
- private void GenerateDistrctsMap()
- {
- // private texture2d
- districtMap = new Texture2D(gridWidth, gridWidth);
- Color[] pix = new Color[gridWidth * gridWidth];
- // private int
- seed = UnityEngine.Random.Range(0, 1000);
- // From a custom Voronoi class
- VoronoiNoise Voronoi = new VoronoiNoise(seed, frequency, amp);
- // Grid width atm is 60
- float[,] arr = new float[gridWidth, gridWidth];
- //Sample the 2D noise and add it into a array.
- for (int y = 0; y < gridWidth; y++)
- {
- for (int x = 0; x < gridWidth; x++)
- {
- float fx = x / (gridWidth - 1.0f);
- float fy = y / (gridWidth - 1.0f);
- arr[x, y] = Voronoi.Sample2D(fx, fy);
- }
- }
- for (int y = 0; y < gridWidth; y++)
- {
- for (int x = 0; x < gridWidth; x++)
- {
- float n = arr[x, y];
- districtMap.SetPixel(x, y, new Color(n, n, n, 1));
- }
- }
- districtMap.Apply();
- // districtBorderMap is a RawImage UI element
- districtBorderMap.texture = districtMap;
- }
- /// <summary>
- /// Floodfills district zones from districtBorderMap, uses borderThreshold for checking greyscale values on Voronoi borders.
- /// </summary>
- private void FloodfillDistricts()
- {
- // colorMap is a private Texture2D
- colorMap = new Texture2D(gridWidth, gridWidth);
- HashSet<Color> colors = new HashSet<Color>();
- Color[] pixels = districtMap.GetPixels();
- int width = colorMap.width;
- int height = colorMap.height;
- Stack<Vector2Int> stack = new Stack<Vector2Int>();
- for (int i = 0; i < pixels.Length; i++)
- {
- if (pixels[i].grayscale > borderThreshold)
- {
- Color color = new Color(UnityEngine.Random.value, UnityEngine.Random.value, UnityEngine.Random.value, 1);
- stack.Push(new Vector2Int(i % width, i / width));
- while (stack.Count > 0)
- {
- Vector2Int pixelPos = stack.Pop();
- int index = pixelPos.y * width + pixelPos.x;
- if (pixels[index].grayscale > borderThreshold && !colors.Contains(pixels[index]))
- {
- pixels[index] = color;
- if (pixelPos.x > 0) stack.Push(new Vector2Int(pixelPos.x - 1, pixelPos.y));
- if (pixelPos.x < width - 1) stack.Push(new Vector2Int(pixelPos.x + 1, pixelPos.y));
- if (pixelPos.y > 0) stack.Push(new Vector2Int(pixelPos.x, pixelPos.y - 1));
- if (pixelPos.y < height - 1) stack.Push(new Vector2Int(pixelPos.x, pixelPos.y + 1));
- }
- }
- colors.Add(color);
- }
- }
- colorMap.SetPixels(pixels);
- colorMap.Apply();
- districtColorMap.texture = colorMap;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement