Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * The Terrain Generator class produces random generated terrains.
- * @author avasopht.blogspot.com
- *
- */
- public class TerrainGenerator {
- /**
- * Returns a square height map in a series of iterations. Each iteration doubles the size
- * of the map until the map meets the minimum size requirements.
- * @param roughness between 0.0 and 1.0, with 0.0 being rough and 1.0 being smooth
- */
- public static HeightMap GenerateHeightMap(int minimumWidth, int minimumHeight, float roughness){
- float displacementMagnitude = 1.0f;
- // Create map with a random height
- HeightMap map = new HeightMap(1,1);
- map.setValue(0,0,0);
- // For each iteration
- while(map.getWidth() < minimumWidth && map.getHeight() < minimumHeight) {
- // Create a new map twice the size of the current map
- // Copy old map height data to new map
- map = map.GetDoubleSized();
- // (Diamond step): for each square
- for(int x = 0; x < map.getWidth(); x += 2) {
- for(int y = 0; y < map.getHeight(); y += 2) {
- // Calculate average value of square
- float average = GetSquareAverage(map,x,y);
- // Produce midpoint displacement value
- float midpoint = average + CreateRandomValue(displacementMagnitude);
- map.setValue(x + 1, y + 1, midpoint);
- }
- }
- // (Square step): for each diamond
- for(int x = 0; x < map.getWidth(); x += 2) {
- for(int y = 0; y < map.getHeight(); y += 2) {
- // Calculate average value of corners
- // Produce midpoint displacement value
- CalculateDiamond(map, x+1, y, displacementMagnitude);
- CalculateDiamond(map, x, y+1, displacementMagnitude);
- }
- }
- // Update displacement magnitude
- displacementMagnitude = displacementMagnitude * (1.0f - (roughness * 0.5f));
- }
- // Return height map
- return map.GetNormalized();
- }
- /**
- * Calculates new value inside of a diamond.
- */
- private static void CalculateDiamond(HeightMap map, int x, int y, float magnitude) {
- float sum = 0;
- // Calculate average value of corners
- sum += map.getValue(x-1,y);
- sum += map.getValue(x+1,y);
- sum += map.getValue(x,y+1);
- sum += map.getValue(x,y-1);
- float average = sum / 4.0f;
- // Produce midpoint displacement value
- float midpoint = average + CreateRandomValue(magnitude);
- map.setValue(x,y,midpoint);
- }
- /**
- * Calculates the average value of the corners in a 3x3 square.
- */
- private static float GetSquareAverage(HeightMap map, int x, int y) {
- float sum = 0;
- for(int readX = 0; readX < 2; readX++) {
- for(int readY = 0; readY < 2; readY++) {
- sum += map.getValue(x + readX * 2, y + readY * 2);
- }
- }
- return sum / 4.0f;
- }
- /**
- * Returns a random value between -magnitude and magnitude.
- */
- private static float CreateRandomValue(float magnitude) {
- return (float)(magnitude * ((2.0f * Math.random()) - 1.0f));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment