city-generation/Game/Assets/Scripts/Business/Generator/TerrainGenerator.cs

72 lines
2.1 KiB
C#
Raw Normal View History

2015-03-13 15:36:12 +00:00
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using TransportGame.Business;
using TransportGame.Model;
using TransportGame.Noise;
using TransportGame.Utils;
using TransportGame.Utils.Algorithms;
using UnityEngine;
namespace TransportGame.Generator
{
public class TerrainGenerator
{
2015-03-23 19:17:09 +00:00
/// <summary>
/// Gets or sets the underlying noise generator
/// </summary>
2015-03-13 15:36:12 +00:00
public NoiseGenerator Noise { get; set; }
private System.Random random = new System.Random();
2015-03-23 19:17:09 +00:00
2015-03-13 15:36:12 +00:00
public TerrainGenerator()
{
Noise = new PerlinNoiseGenerator();
2015-06-03 20:54:22 +00:00
if (ConfigManager.Tergen == null)
throw new Exception("Not initialized!");
2015-03-13 15:36:12 +00:00
2015-06-03 20:54:22 +00:00
Noise.Octaves = ConfigManager.Tergen.NoiseOctaves;
Noise.NonLinearPower = ConfigManager.Tergen.NoiseNonLinearPower;
Noise.Scale = ConfigManager.Tergen.ElevationScale;
2015-03-13 15:36:12 +00:00
}
2015-06-17 09:07:02 +00:00
public CityMap Generate(int width, int height)
2015-03-13 15:36:12 +00:00
{
// Create map
2015-06-17 09:07:02 +00:00
CityMap map = new CityMap(width, height);
2015-03-13 15:36:12 +00:00
// Pick a random biome
map.Biome = PickBiome();
Logger.Info("Picked biome: {0}", map.Biome.Name);
// Generate elevation
GenerateElevation(map);
// Generate water level
2015-06-17 11:06:54 +00:00
float waterAmount = random.NextSingle(map.Biome.Moisture.Min, map.Biome.Moisture.Max);
2015-06-03 20:54:22 +00:00
map.WaterLevel = Mathf.Pow(waterAmount, ConfigManager.Tergen.WaterNonLinearPower) * map.Biome.Height;
2015-03-19 10:34:58 +00:00
2015-03-13 15:36:12 +00:00
return map;
}
private Biome PickBiome()
{
int biomeCount = BiomeManager.Biomes.Count();
int biome = random.Next(biomeCount);
return BiomeManager.Biomes.ElementAt(biome);
}
2015-06-17 09:07:02 +00:00
private void GenerateElevation(CityMap map)
2015-03-13 15:36:12 +00:00
{
for (int x = 0; x < map.Width; ++x)
for (int y = 0; y < map.Height; ++y)
2015-05-20 08:26:46 +00:00
map.Heightmap[x, y] = Noise.Generate(x, y, 0, 1);
2015-03-13 15:36:12 +00:00
}
}
}