Beispiel #1
0
    private void Calculate()
    {
        if (perlin == null)
        {
            perlin = new Perlin();
        }
        fractal = new FractalNoise(h, lacunarity, octaves, perlin);

        for (int y = 0; y < height; y++)
        {
            for (int x = 0; x < width; x++)
            {
                if (gray)
                {
                    float value = fractal.HybridMultifractal(x * scale + Time.time, y * scale + Time.time, offset);
                    texture.SetPixel(x, y, new Color(value, value, value, value));
                }
                else
                {
                    offsetPos = Time.time;
                    float valuex = fractal.HybridMultifractal(x * scale + offsetPos * 0.6f, y * scale + offsetPos * 0.6f, offset);
                    float valuey = fractal.HybridMultifractal(x * scale + 161.7f + offsetPos * 0.2f, y * scale + 161.7f + offsetPos * 0.3f, offset);
                    float valuez = fractal.HybridMultifractal(x * scale + 591.1f + offsetPos, y * scale + 591.1f + offsetPos * 0.1f, offset);
                    texture.SetPixel(x, y, new Color(valuex, valuey, valuez, 1));
                }
            }
        }
        texture.Apply();
    }
Beispiel #2
0
        // Select the right noise
        public virtual void SetUpNoise(int seed)
        {
            _offsetX = Random.Range(minOffset, maxOffset);
            _offsetY = Random.Range(minOffset, maxOffset);
            switch (noiseType)
            {
            case NOISE_TYPE.PERLIN:
                _noise = new PerlinNoise(seed, scale);
                break;

            case NOISE_TYPE.VALUE:
                _noise = new ValueNoise(seed, scale);
                break;

            case NOISE_TYPE.SIMPLEX:
                _noise = new SimplexNoise(seed, scale);
                break;

            case NOISE_TYPE.VORONOI:
                _noise = new VoronoiNoise(seed, scale);
                break;

            case NOISE_TYPE.WORLEY:
                _noise = new WorleyNoise(seed, scale, amplitude);
                break;

            default:
                _noise = new PerlinNoise(seed, scale);
                break;
            }
            _fractalNoise = new FractalNoise(_noise, octaves, 1f); // Should use frequency here ?
        }
    void Calculate()
    {
        if (perlin == null)
        {
            perlin = new Perlin();
        }

        fractal = new FractalNoise(h, lacunarity, octaves, perlin);

        for (int y = 0;y<height;y++)
        {
            for (int x = 0;x<width;x++)
            {
                if (gray)
                {
                    float val = fractal.HybridMultifractal(x*scale + Time.time, y * scale + Time.time, offset);
                    texture.SetPixel(x, y, new Color(val, val, val, val));
                }
                else
                {
                    offsetPos = Time.time;
                    float valuex = fractal.HybridMultifractal((float)(x*scale + offsetPos * 0.6), (float)(y*scale + offsetPos * 0.6), (float)offset);
                    float valuey = fractal.HybridMultifractal((float)(x*scale + 161.7 + offsetPos * 0.2), (float)(y*scale + 161.7 + offsetPos * 0.3), (float)offset);
                    float valuez = fractal.HybridMultifractal((float)(x*scale + 591.1 + offsetPos), (float)(y*scale + 591.1 + offsetPos * 0.1), (float)offset);
                    texture.SetPixel(x, y, new Color (valuex, valuey, valuez, 1));
                }
            }
        }

        texture.Apply();
    }
Beispiel #4
0
    public override void NodeGUI()
    {
        base.NodeGUI();

        GUILayout.BeginHorizontal();
        GUILayout.BeginVertical();
        GUILayout.Label("octaves:");
        GUILayout.Label("frequency:");
        GUILayout.Label("amplitude:");
        GUILayout.EndVertical();
        GUILayout.BeginVertical();
        octaves   = RTEditorGUI.IntField(octaves);
        frequency = RTEditorGUI.FloatField(frequency);
        amplitude = RTEditorGUI.FloatField(amplitude);
        GUILayout.EndVertical();
        GUILayout.EndHorizontal();


        noiseFunction = noiseGUI.Display();

        if (GUI.changed || noiseGUI.changed)
        {
            fractalNoise = new FractalNoise(noiseFunction, octaves, frequency, amplitude);
            noiseDesc    = noiseGUI.noiseDesc();
            NodeEditor.curNodeCanvas.OnNodeChange(this);
        }
    }
Beispiel #5
0
        private Vector3[] WarpVertices(Vector3[] inputVertices)
        {
            Vector3[]     vertices = inputVertices;
            System.Random random   = new System.Random();
            int           seed     = random.Next(0, int.MaxValue);
            INoise        perlin   = new PerlinNoise(seed, 2.0f);
            FractalNoise  fractal  = new FractalNoise(perlin, 3, 1.0f);

            for (int i = 0; i < vertices.Length; i++)
            {
                Vector3 vec3 = vertices[i];

                float x = vec3.x + (vec3.x * 5 * random.Next(100, 140) / 100);
                float y = vec3.y - (vec3.x * 7 * random.Next(100, 140) / 100);
                float z = vec3.z - (vec3.y * 4.5f * random.Next(100, 140) / 100);

                vec3 = new Vector3(x, y, z).normalized;

                float scale = 50f;
                int   sign  = random.Next(1, 2) == 1 ? 1 : -1;
                x = vec3.x + sign * (fractal.Sample1D(vec3.x) * scale);
                y = vec3.y + sign * (fractal.Sample1D(vec3.y) * scale);
                z = vec3.z + sign * (fractal.Sample1D(vec3.z) * scale);

                vertices[i] = new Vector3(x, y, z).normalized;
            }

            return(vertices);
        }
    public float Calculate(Vector2 texturePosition, float scaleInput, int x, int y, int z)
    {
        perlin = new Perlin(seed);

        fractal = new FractalNoise(h, lacunarity, octaves, perlin);

        float value = 0;

        switch (noiseType)
        {
        case NoiseType.Brownian:
            value = fractal.BrownianMotion(x * scale * scaleInput + texturePosition.x, y * scale * scaleInput, z * scale * scaleInput + texturePosition.y);
            break;

        case NoiseType.HybridMultifractal:
            value = fractal.HybridMultifractal(x * scale * scaleInput + texturePosition.x, y * scale * scaleInput, z * scale * scaleInput + texturePosition.y, offset);
            break;

        case NoiseType.RidgedMultifractal:
            value = fractal.RidgedMultifractal(x * scale * scaleInput + texturePosition.x, y * scale * scaleInput, z * scale * scaleInput + texturePosition.y, offset, gain);
            break;

        case NoiseType.Perlin:
            value = perlin.Noise(x * scale * scaleInput + texturePosition.x, y * scale * scaleInput, z * scale * scaleInput + texturePosition.y);
            break;
        }

        return(value);
    }
Beispiel #7
0
 private static FractalNoise Get()
 {
     if (s_Noise == null)
     {
         s_Noise = new FractalNoise(1.27F, 2.04F, 8.36F);
     }
     return(s_Noise);
 }
    public float[,] Calculate(Vector2 texturePosition, float scaleInput, float[,] heightMap, int iterater)
    {
        if (enabled == false)
        {
            return(new float[height, width]);
        }

        perlin = new Perlin(seed);

        fractal = new FractalNoise(h, lacunarity, octaves, perlin);

        float[,] hMA = new float[width, height];

        for (var y = 0; y < height; y++)
        {
            for (var x = 0; x < width; x++)
            {
                float value = 0;

                switch (noiseType)
                {
                case NoiseType.Brownian:
                    value = fractal.BrownianMotion(x * scale * scaleInput + texturePosition.x, y * scale * scaleInput + texturePosition.y);
                    break;

                case NoiseType.HybridMultifractal:
                    value = fractal.HybridMultifractal(x * scale * scaleInput + texturePosition.x, y * scale * scaleInput + texturePosition.y, offset);
                    break;

                case NoiseType.RidgedMultifractal:
                    value = fractal.RidgedMultifractal(x * scale * scaleInput + texturePosition.x, y * scale * scaleInput + texturePosition.y, offset, gain);
                    break;

                case NoiseType.Perlin:
                    value = perlin.Noise(x * scale * scaleInput + texturePosition.x, y * scale * scaleInput + texturePosition.y);
                    break;
                }

                //Blending
                if (iterater == 0)
                {
                    hMA[x, y] = value;
                }
                else if (blendType == BlendType.Accumulative)
                {
                    hMA[x, y] = Mathf.Lerp(heightMap[x, y], value, 0.5f);
                }
                else if (blendType == BlendType.Iterative)
                {
                    hMA[x, y] = (value + heightMap[x, y]) / 2;
                }
            }
        }

        return(hMA);
    }
Beispiel #9
0
    private static FractalNoise Get()
    {
        bool flag = SmoothRandom.s_Noise == null;

        if (flag)
        {
            SmoothRandom.s_Noise = new FractalNoise(1.27f, 2.04f, 8.36f);
        }
        return(SmoothRandom.s_Noise);
    }
Beispiel #10
0
    void Start()
    {
        texture = new Texture2D(width, height, TextureFormat.RGB24, false);
        GetComponent <Renderer> ().material.mainTexture = texture;

        if (perlin == null)
        {
            perlin = new Perlin();
        }
        fractal = new FractalNoise(h, lacunarity, octaves, perlin);
    }
Beispiel #11
0
    public void changeSeed(int newseed)
    {
        seed = newseed;
        INoise perlin = new PerlinNoise(seed, 2f);

        //fractal = new FractalNoise(perlin, 3, 1.0f);
        fractalT = new FractalNoise(perlin, fractalOctavesT, fractalfrequencyT, fractalamplitudeT);
        voronoiT = new ValueNoise(seed, fractalOctavesT);
        perlin   = new PerlinNoise(seed + HseedOffset, 2f);
        voronoiH = new ValueNoise(seed + HseedOffset, fractalOctavesT);
        //print("hi");
        fractalH = new FractalNoise(perlin, fractalOctavesH, fractalfrequencyH, fractalamplitudeH);
    }
    Texture2D createNoiseTexture(int heightmapWidth, int heightmapHeight, float h, float lacunarity, float octaves, float offset, float scale)
    {
        //Creates a 2D Texture
        Texture2D texture = new Texture2D(heightmapWidth, heightmapHeight, TextureFormat.RGB24, false);
        //Perlin and FractalNoise are a custom class in Perlin.cs
        Perlin       perlin  = new Perlin();
        FractalNoise fractal = new FractalNoise(h, lacunarity, octaves, perlin);

        for (int y = 0; y < heightmapHeight; y++)
        {
            for (int x = 0; x < heightmapWidth; x++)
            {
                float value  = fractal.HybridMultifractal(x * scale, y * scale, offset);
                Color colour = new Color(value / 10, value, value / 3, value);
                texture.SetPixel(x, y, colour);
            }
        }
        texture.Apply();
        return(texture);
    }
Beispiel #13
0
        private float[] GenerateFractalVoxels(int width, int height, int length)
        {
            INoise       perlin  = new PerlinNoise(seed, 2.0f);
            FractalNoise fractal = new FractalNoise(perlin, 3, .5f);

            float[] voxels = new float[width * height * length];
            for (int x = 0; x < width; x++)
            {
                for (int y = 0; y < height; y++)
                {
                    for (int z = 0; z < length; z++)
                    {
                        float fx = x / (width - 1f);
                        float fy = y / (height - 1f);
                        float fz = z / (length - 1f);

                        int idx = x + y * width + z * width * height;

                        voxels[idx] = fractal.Sample3D(fx, fy, fz);
                    }
                }
            }
            return(voxels);
        }
Beispiel #14
0
    void GenMap()
    {
        //print("GenMap");
        int     col, row;
        Color   cellColor;
        float   temp;          // temp in celcius
        float   elevation;     // elevation in meters
        float   percipitation; // annual percepitation in cm
        Vector3 worldPos;
        Vector2 uv;
        HexCell hexCell;
        Hex     hex;
        float   percipGraph;

        float[,] compressionArray;
        float[,] bluredCompressionArray;


        temperatureArray = new float[columns, rows];
        plateArray       = new int[columns, rows];
        edgeDistArray    = new float[columns, rows];
        biomeArray       = new Biomes[columns, rows];
        terrainArray     = new Terrain[columns, rows];


        Random.InitState(seed);

        if (m_icons != null)
        {
            // Clear All Icons
            foreach (GameObject icon in m_icons)
            {
                Destroy(icon);
            }
            m_icons.Clear();
        }
        m_icons = new List <GameObject>();

        // Create Voronoi points
        //   remove existing dots
        if (m_dots != null)
        {
            foreach (GameObject dot in m_dots)
            {
                Destroy(dot);
            }
        }

        Plate[] plates;

        // Calulate Plates
        plates = GeneratePlates();

        Vector2 plateNoiseOffset;

        plateNoiseOffset.x = Random.value * 1000;
        plateNoiseOffset.y = Random.value * 1000;

        elevationArray   = new float[columns, rows];
        compressionArray = new float[columns, rows];



        for (col = 0; col < columns; col++)
        {
            for (row = 0; row < rows; row++)
            {
                hex      = OffsetToHex(col, row);
                worldPos = HexToWorld(hex);
                uv       = HexToUniform(hex);
                Vector2 modifiedUV;

                // Determin plate id
                float closestDist       = 1000000;
                float secondClosestDist = 1000000;
                float dist;
                int   firstCellID  = -1;
                int   secondCellID = -1;

                Vector2 noiseCoord = uv + plateNoiseOffset;
                float   noiseValX  = FM.Noise(noiseCoord.x, noiseCoord.y, m_plateNoiseFreq, 1, 2, 0.5f, m_plateNoiseOctives);
                float   noiseValY  = FM.Noise(noiseCoord.x + 3417, noiseCoord.y, m_plateNoiseFreq, 1, 2, 0.5f, m_plateNoiseOctives);
                modifiedUV = uv + (new Vector2(noiseValX, noiseValY) - new Vector2(0.5f, 0.5f)) * m_plateNoiseAmp;
                Vector2 realUV    = UniformToUV(modifiedUV);
                int     sampleCol = Mathf.FloorToInt(realUV.x * cellColumns);
                int     sampleRow = Mathf.FloorToInt(realUV.y * cellRows);

                // This code might be f****d.
                for (int i = 0; i < 3; i++)
                {
                    for (int j = 0; j < 3; j++)
                    {
                        // offset to check neighbors
                        int cellCol = sampleCol + (i - 1);
                        int cellRow = sampleRow + (j - 1);
                        if (cellRow < 0 || cellRow >= cellRows)                         // row is above/below map
                        {
                            continue;
                        }
                        int wrapOffset = (cellCol / cellColumns);
                        cellCol = (cellCol + cellColumns) % cellColumns;



                        int     plateIndex = cellCol * cellRows + cellRow;
                        Hex     vhex       = plates[plateIndex].hexLocation;
                        Vector2 plateUV    = HexToUniform(vhex);
                        plateUV.x += wrapOffset;

                        //Vector3 vWorld = HexToWorld(vhex);
                        bool useHexDistance = false;
                        if (useHexDistance)
                        {
                            dist = HexDistance(hex, vhex);
                        }
                        else
                        {
                            dist = Vector2.Distance(modifiedUV, plateUV);
                        }


                        if (dist < closestDist)
                        {
                            secondCellID      = firstCellID;
                            secondClosestDist = closestDist;
                            firstCellID       = plateIndex;
                            closestDist       = dist;
                        }
                        else if (dist < secondClosestDist)
                        {
                            secondCellID      = plateIndex;
                            secondClosestDist = dist;
                        }
                    }
                }


                // calculate compression
                plateArray[col, row] = firstCellID;
                Plate firstPlate  = plates[firstCellID];
                Plate secondPlate = plates[secondCellID];

//				if (m_debug)
//				{
//					Vector2 firstPlatePostion = HexToUniform(firstPlate.hexLocation);
//					Vector2 secondPlatePostion = HexToUniform(secondPlate.hexLocation);
//					Vector2 midPoint = (firstPlatePostion + secondPlatePostion)/2f;
//					Vector2 axis = (secondPlatePostion - firstPlatePostion);
//					//float edgeToCenterDist = axis.magnitude /2;
//					axis.Normalize(); // normalize vector for further math;
//					float edgeDist = Vector3.Dot((modifiedUV - midPoint),-axis); // find the distance from the edge with vector projection.
//					//edgeDist /= edgeToCenterDist; // normalize edgeDist;
//					//float dotProd = Vector2.Dot(firstPlate.force,secondPlate.force);
//					//float divergence = Utils.Map(dotProd,-1,0,1,0); // remap from -1:1 to 1:0
//					float compression = (Vector2.Dot(axis,firstPlate.force) + Vector2.Dot(-axis,secondPlate.force))/2;
//					//compression *= divergence;
//					float ridgeDistance = Mathf.Max(0.001f, m_techtonicBorderWidth/10 * Mathf.Abs(compression));
//					float edgeWeight = Mathf.Clamp01(1-edgeDist/ridgeDistance);
//					edgeWeight = Mathf.Pow(edgeWeight,2);
//					compression *= edgeWeight;
//					compressionArray[col,row] = compression;
//
//					edgeDistArray[col,row] = edgeWeight;
//				}


//				bool isContinental = plates[firstCellID].isContinental;
//				if (isContinental == true)
//				{
//					height = Mathf.Lerp(0.05f, 0.15f, Random.value); // land height
//				}
//				else
//				{
//					height = Mathf.Lerp(-0.15f, -0.05f, Random.value); // water height
//				}

                elevationArray[col, row] = firstPlate.elevation;
            }
        }


        // Calculate Elevation


        Hex     sampleHex;
        Vector2 direction;

        if (!m_debug)
        {
            for (col = 0; col < columns; col++)
            {
                for (row = 0; row < rows; row++)
                {
                    hex = OffsetToHex(col, row);

                    Plate firstPlate, secondPlate;
                    int   cellID = plateArray[col, row];
                    firstPlate = plates[cellID];


                    float compression = 0;
                    int   sampleCount = 0;
                    int   secondCellID;
                    foreach (Hex dir in directions)
                    {
                        sampleHex = new Hex(hex.q + dir.q, hex.r + dir.r);
                        if (IsHexValid(sampleHex))
                        {
                            OffsetCoords coords = HexToOffset(sampleHex);
                            secondCellID = plateArray[coords.column, coords.row];
                            sampleCount++;

                            if (secondCellID == cellID)
                            {
                                continue;
                            }

                            secondPlate  = plates[secondCellID];
                            direction    = (Vector2)HexToWorld(dir, false).normalized;
                            compression += Vector2.Dot(firstPlate.force, direction);
                            compression += Vector2.Dot(secondPlate.force, direction * -1);
                        }
                    }
                    compression /= sampleCount;
                    if (firstPlate.isContinental)
                    {
                        compression *= 1.5f;
                    }

                    compressionArray[col, row] = compression;
                }
            }
        }

        bluredCompressionArray = new float[columns, rows];
        convolveHexArray(compressionArray, bluredCompressionArray, 3);
        convolveHexArray(compressionArray, compressionArray, 1);       // convovle base a little;
        convolveHexArray(elevationArray, elevationArray, 3);


        // randomize noiseOffset
        Vector2 noiseOffset;

        noiseOffset.x = Random.value * gridWidth * 10;
        noiseOffset.y = Random.value * gridHeight * 10;

        // deform elevation based on compression and noise
        for (col = 0; col < columns; col++)
        {
            for (row = 0; row < rows; row++)
            {
                hex      = OffsetToHex(col, row);
                worldPos = HexToWorld(hex);
                hexCell  = GetHexCell(hex);
                uv       = HexToUniform(hex);

                //int cellID = plateArray[col,row];
                //Plate firstPlate = plates[cellID];

                float height = elevationArray[col, row];

                Vector3 noisePos = worldPos + new Vector3(worldOffset.x, worldOffset.y, 0) * -1.5f + new Vector3(noiseOffset.x, noiseOffset.y, 0);
                float   noiseVal = FM.Noise(noisePos.x, noisePos.y, frequency, 1, lacunarity, gain, octaves);
                height += Utils.Map(noiseVal, 0, 1, -1f, 1f) * amplitude;


                float totalMountainHeight = 0;
                float localMountainHeight = 0;
                bool  isMountain          = false;
                if (m_doTechtonicCompression)
                {
                    float bluredCompression   = bluredCompressionArray[col, row];
                    float originalCompression = compressionArray[col, row];
                    float modifiedCompression = Mathf.Max(bluredCompression, originalCompression);
                    bluredCompressionArray[col, row] = modifiedCompression;                    // for visulization purposes
                    //bluredCompression *= 1f;
                    //bluredCompression = Mathf.Pow(Mathf.Abs(bluredCompression),1.3f) * Mathf.Sign(bluredCompression); // pow 2
                    totalMountainHeight += modifiedCompression * m_mountainBaseHeight * noiseVal;

                    // Mountain peaks should be random looking in elevation;
                    float mountainRandom = Mathf.Pow(Random.value, 2);
                    localMountainHeight  = m_mountainHeight * modifiedCompression * mountainRandom;
                    totalMountainHeight += localMountainHeight;
                    isMountain           = mountainRandom > Utils.Map(originalCompression, 0.001f, 0.2f, 1, 0);            // magic numbers
                    height += totalMountainHeight;
                }



                elevation = Utils.Map(height, -1, 1, -10000, 10000);             // elevation in  meters
                if (elevation > 3000)
                {
                    isMountain = true;
                }

                if (isMountain)                 // add mountain icon to compressed areas
                {
                    GameObject mountainIconSelection = null;
                    if (elevation < 0)
                    {
                        mountainIconSelection = oceanicMountainIcon;
                    }
                    else if (elevation > 600)
                    {
                        mountainIconSelection = mountainIcon;
                    }

                    if (mountainIconSelection != null)
                    {
                        GameObject mountain = Instantiate(mountainIconSelection, worldPos, Quaternion.identity, transform) as GameObject;
                        m_icons.Add(mountain);
                    }
                }


                if (elevation < 0)
                {
                    terrainArray[col, row] = Terrain.Ocean;
                }
                else if (isMountain)
                {
                    terrainArray[col, row] = Terrain.Mountains;
                }
                else
                {
                    terrainArray[col, row] = Terrain.Plains;
                }

                elevationArray[col, row] = elevation;
                hexCell.elevation        = elevation;
            }
        }

        // calculate temp
        for (col = 0; col < columns; col++)
        {
            for (row = 0; row < rows; row++)
            {
                hex      = OffsetToHex(col, row);
                worldPos = HexToWorld(hex);
                hexCell  = GetHexCell(hex);
                uv       = HexToUV(hex);

                elevation = elevationArray[col, row];

                // Calculate Temperature
                float latitude = uv.y * 180 - 90;
                float temp01   = Mathf.Cos(latitude * Mathf.Deg2Rad);
                temp = Utils.Map(temp01, 0, 1, minTemp, maxTemp);

                //Temp by Elevation
                if (elevation > 0)
                {
                    temp = temp - lapseRate * (elevation / 1000);
                }
                temperatureArray[col, row] = temp;
            }
        }

        // Calculate Climate
        CalculatePercipitation();



        // Final Calculations
        for (col = 0; col < columns; col++)
        {
            for (row = 0; row < rows; row++)
            {
                hex      = OffsetToHex(col, row);
                worldPos = HexToWorld(hex);
                hexCell  = GetHexCell(hex);
                uv       = HexToUV(hex);

                elevation = elevationArray[col, row];

                temp = temperatureArray[col, row];

                //				//Calculate Moisture
                //				waterCells = 0;
                //				int sampleCol;
                //				for (int i = 1; i<=percipSearchDist; i++)
                //				{
                //					sampleCol = (col +i) % columns;
                //					sampleHex = OffsetToHex(sampleCol,row);
                //					sampleCell = GetHexCell(sampleHex);
                //					if (sampleCell.elevation <= 0)
                //					{
                //						waterCells ++;
                //					}
                //				}
                //				percipitation = Utils.Map(waterCells,0,percipSearchDist,0,450);
                //				// Modulate percipitation by temperature;
                //				percipitation *= Utils.Map (temp,-10,30,0,1);

                percipitation = percipArray[col, row] * 450;


                if (biomeMap)
                {
                    elevation     = 1;
                    temp          = Utils.Map(uv.x, 0, 1, 30, -30);
                    percipitation = Utils.Map(uv.y, 0, 1, 0, 450);
                }


                Biomes biome;
                if (elevation > 0)
                {
                    // Calculate Biome
                    biome = CalcBiome(temp, percipitation);

                    switch (biome)
                    {
                    case Biomes.Grassland:
                        cellColor = grasslandColor;
                        break;

                    case Biomes.TropicalRainForest:
                        cellColor = tropicalRainForestColor;
                        break;

                    case Biomes.Forrest:
                        cellColor = forrestColor;
                        break;

                    case Biomes.Taiga:
                        cellColor = TaigaColor;
                        break;

                    case Biomes.Tundra:
                        cellColor = tundraColor;
                        break;

                    case Biomes.Desert:
                        cellColor = desertColor;
                        break;

                    case Biomes.Snow:
                        cellColor = snowColor;
                        break;

                    default:
                        cellColor = Color.red;
                        break;
                    }

                    cellColor = Color.Lerp(cellColor, Color.white, (elevation - 750) / 5000);
                }
                else                     // hex is oceanic

                {
                    biome = Biomes.Oceanic;
                    float lerpValue = Utils.Map(elevation, -10000, 0, 0, 1);
                    cellColor = Color.Lerp(WaterColorBottom, WaterColorTop, lerpValue);
                }
                biomeArray[col, row] = biome;

                float  humidity    = humidityArray[col, row];
                string biomeString = biome == Biomes.TropicalRainForest ? "RainForest" : biome.ToString();
                string displayText = string.Format("{0,5:f1}c, {1,5:f0} p, {2,5:f2} h, {3,8:f1} elv, {4}", temp, percipitation, humidity, elevation, biomeString);
                //displayText = hex.ToString();

                hexCell.SetText(displayText);

                //				cellColor = new Color(uv.x,uv.y,0);
                float tempGraph = Utils.Map(temp, -30, 30, 0, 1);
                percipGraph = Utils.Map(percipitation, 0, 450, 0, 1);

                if (showTemp || showPercip)
                {
                    cellColor = Color.black;
                    if (showTemp)
                    {
                        cellColor.r = tempGraph;
                    }
                    if (showPercip)
                    {
                        cellColor.g = percipGraph;
                    }
                }
                if (showPlates)
                {
                    int   cellID = plateArray[col, row];
                    Plate plate  = plates[cellID];
                    float value  = (cellID * 18241.845f) % 1;
                    cellColor = Color.black;
                    if (plate.isContinental)
                    {
                        cellColor.g = Mathf.Lerp(0.3f, 1, value);
                    }
                    else
                    {
                        cellColor.b = Mathf.Lerp(0.3f, 1, value);
                    }
                    cellColor.r = ((value * 3.23f + 0.42f) % 1) / 3;

                    //cellColor = Color.HSVToRGB(value,0.8f,0.8f);
                }

                else if (showElevation)
                {
                    float relElevation = Utils.Map(elevation, -10000, 10000, 0, 1);
                    cellColor = Color.black;
                    if (elevation > 0 || true)
                    {
                        cellColor.r = relElevation;
                        cellColor.g = relElevation;
                        cellColor.b = relElevation;
                    }
                    else
                    {
                        cellColor.b = relElevation * 2;
                    }
                }

                else if (showCompression)
                {
                    float compression = bluredCompressionArray[col, row];
                    cellColor.r = compression;
                    cellColor.g = 0;
                    cellColor.b = compression * -1;
                }


                else if (showEdgeDist)
                {
                    float edgeDist = edgeDistArray[col, row];
                    cellColor.r = edgeDist;
                    cellColor.g = cellColor.r;
                    cellColor.b = cellColor.r;
                }

                hexCell.SetColor(cellColor);
                if (showText == true)
                {
                    hexCell.ShowText();
                }
                else
                {
                    hexCell.HideText();
                }
            }
        }

        // Send event to signal map generation
        if (OnMapGeneration != null)
        {
            OnMapGeneration();
        }
    }
Beispiel #15
0
        void Start()
        {
            INoise       perlin  = new PerlinNoise(seed, 2.0f);
            FractalNoise fractal = new FractalNoise(perlin, 3, 1.0f);

            //Set the mode used to create the mesh.
            //Cubes is faster and creates less verts, tetrahedrons is slower and creates more verts but better represents the mesh surface.
            Marching marching = null;

            if (mode == MARCHING_MODE.TETRAHEDRON)
            {
                marching = new MarchingTertrahedron();
            }
            else
            {
                marching = new MarchingCubes();
            }

            //Surface is the value that represents the surface of mesh
            //For example the perlin noise has a range of -1 to 1 so the mid point is where we want the surface to cut through.
            //The target value does not have to be the mid point it can be any value with in the range.
            marching.Surface = 0.0f;

            //The size of voxel array.
            int width  = 32;
            int height = 32;
            int length = 10;

            float[] voxels = new float[width * height * length];

            //Fill voxels with values. Im using perlin noise but any method to create voxels will work.
            for (int x = 0; x < width; x++)
            {
                for (int y = 0; y < height; y++)
                {
                    for (int z = 0; z < length; z++)
                    {
                        float fx = x / (width - 1.0f);
                        float fy = y / (height - 1.0f);
                        float fz = z / (length - 1.0f);

                        int idx = x + y * width + z * width * height;

                        voxels[idx] = fractal.Sample3D(fx, fy, fz);
                    }
                }
            }

            List <Vector3> verts   = new List <Vector3>();
            List <int>     indices = new List <int>();

            //The mesh produced is not optimal. There is one vert for each index.
            //Would need to weld vertices for better quality mesh.
            marching.Generate(voxels, width, height, length, verts, indices);

            //A mesh in unity can only be made up of 65000 verts.
            //Need to split the verts between multiple meshes.

            int maxVertsPerMesh = 30000; //must be divisible by 3, ie 3 verts == 1 triangle
            int numMeshes       = verts.Count / maxVertsPerMesh + 1;

            for (int i = 0; i < numMeshes; i++)
            {
                List <Vector3> splitVerts   = new List <Vector3>();
                List <int>     splitIndices = new List <int>();

                for (int j = 0; j < maxVertsPerMesh; j++)
                {
                    int idx = i * maxVertsPerMesh + j;

                    if (idx < verts.Count)
                    {
                        splitVerts.Add(verts[idx]);
                        splitIndices.Add(j);
                    }
                }

                if (splitVerts.Count == 0)
                {
                    continue;
                }

                Mesh mesh = new Mesh();
                mesh.SetVertices(splitVerts);
                mesh.SetTriangles(splitIndices, 0);
                mesh.RecalculateBounds();
                mesh.RecalculateNormals();

                GameObject go = new GameObject("Mesh");
                go.transform.parent = transform;
                go.AddComponent <MeshFilter>();
                go.AddComponent <MeshRenderer>();
                go.GetComponent <Renderer>().material = m_material;
                go.GetComponent <MeshFilter>().mesh   = mesh;
                go.transform.localPosition            = new Vector3(-width / 2, -height / 2, -length / 2);

                meshes.Add(go);
            }
        }
Beispiel #16
0
 protected void SetNoise(int seed, int octaves, float pnFreq, float pnAmp, float frFreq, float frAmp)
 {
     Noise = new FractalNoise(new PerlinNoise(seed, pnFreq, pnAmp), octaves, frFreq, frAmp);
 }
Beispiel #17
0
        public void Generate()
        {
            noiseSmall = new FractalNoise(new PerlinNoise(m_seed, groundSmall.x), Mathf.FloorToInt(groundSmall.y), groundSmall.z, groundSmall.w);
            noiseBig   = new FractalNoise(new PerlinNoise(m_seed, groundBig.x), Mathf.FloorToInt(groundBig.y), groundBig.z, groundBig.w);

            m_treeNoise   = new FractalNoise(new PerlinNoise(m_seed + 1, m_treeFrq), 6, 1.0f);
            m_detailNoise = new FractalNoise(new PerlinNoise(m_seed + 2, m_detailFrq), Mathf.FloorToInt(detailNoise.x), detailNoise.y);

            m_heightMapSize = Mathf.ClosestPowerOfTwo(m_heightMapSize) + 1;
            m_alphaMapSize  = Mathf.ClosestPowerOfTwo(m_alphaMapSize);
            m_detailMapSize = Mathf.ClosestPowerOfTwo(m_detailMapSize);

            if (m_detailResolutionPerPatch < 8)
            {
                m_detailResolutionPerPatch = 8;
            }

            float[,] htmap = new float[m_heightMapSize, m_heightMapSize];

            m_terrain = new Terrain[m_tilesX, m_tilesZ];

            //this will center terrain at origin
            m_offset = new Vector2(-m_terrainSize * m_tilesX * 0.5f, -m_terrainSize * m_tilesZ * 0.5f);

            CreateProtoTypes();
            //underlay
            TerrainData terrainData = new TerrainData();

            terrainData.heightmapResolution = m_heightMapSize;
            terrainData.SetHeights(0, 0, new float[0, 0]);
            terrainData.size             = new Vector3(underlaySize.x, m_terrainHeight, underlaySize.y);
            terrainData.splatPrototypes  = m_splatPrototypes;
            terrainData.treePrototypes   = m_treeProtoTypes;
            terrainData.detailPrototypes = m_detailProtoTypes;
            addTextures(terrainData);
            GameObject o = Terrain.CreateTerrainGameObject(terrainData);

            o.name             = "Underlay";
            o.transform.parent = transform;
            Terrain t = o.GetComponent <Terrain>();

            t.materialType       = Terrain.MaterialType.Custom;
            t.materialTemplate   = customMaterial;
            t.transform.position = transform.position - new Vector3(underlaySize.x / 2, 1000, underlaySize.y / 2);
            tiles.Add(o);


            for (int x = 0; x < m_tilesX; x++)
            {
                for (int z = 0; z < m_tilesZ; z++)
                {
                    FillHeights(htmap, x, z);

                    terrainData = new TerrainData();

                    terrainData.heightmapResolution = m_heightMapSize;
                    terrainData.SetHeights(0, 0, htmap);
                    terrainData.size             = new Vector3(m_terrainSize, m_terrainHeight, m_terrainSize);
                    terrainData.splatPrototypes  = m_splatPrototypes;
                    terrainData.treePrototypes   = m_treeProtoTypes;
                    terrainData.detailPrototypes = m_detailProtoTypes;

                    //FillAlphaMap(terrainData);
                    addTextures(terrainData);

                    o                                   = Terrain.CreateTerrainGameObject(terrainData);
                    o.name                              = "TerrainTile " + x + "/" + z;
                    o.transform.parent                  = transform;
                    m_terrain[x, z]                     = o.GetComponent <Terrain>();
                    m_terrain[x, z].materialType        = Terrain.MaterialType.Custom;
                    m_terrain[x, z].materialTemplate    = customMaterial;
                    m_terrain[x, z].transform.position  = transform.position + new Vector3(m_terrainSize * x + m_offset.x, 0, m_terrainSize * z + m_offset.y);
                    m_terrain[x, z].heightmapPixelError = m_pixelMapError;
                    m_terrain[x, z].basemapDistance     = m_baseMapDist;
                    m_terrain[x, z].castShadows         = false;
                    tiles.Add(o);

                    FillTreeInstances(m_terrain[x, z], x, z);
                    FillDetailMap(m_terrain[x, z], x, z);
                }
            }

            //Set the neighbours of terrain to remove seams.
            for (int x = 0; x < m_tilesX; x++)
            {
                for (int z = 0; z < m_tilesZ; z++)
                {
                    Terrain right  = null;
                    Terrain left   = null;
                    Terrain bottom = null;
                    Terrain top    = null;

                    if (x > 0)
                    {
                        left = m_terrain[(x - 1), z];
                    }
                    if (x < m_tilesX - 1)
                    {
                        right = m_terrain[(x + 1), z];
                    }

                    if (z > 0)
                    {
                        bottom = m_terrain[x, (z - 1)];
                    }
                    if (z < m_tilesZ - 1)
                    {
                        top = m_terrain[x, (z + 1)];
                    }

                    m_terrain[x, z].SetNeighbors(left, top, right, bottom);
                }
            }
        }
Beispiel #18
0
 public void OnEnable()
 {
     noiseGUI      = new NoiseGUI(noiseDesc);
     noiseFunction = noiseGUI.noiseFunction;
     fractalNoise  = new FractalNoise(noiseFunction, octaves, frequency, amplitude);
 }
    public void InitialiseVoxels()
    {
        if (RockNoiseLayer)
        {
            RockNoiseLayer.Initialise();
        }
        if (DirtNoiseLayer)
        {
            DirtNoiseLayer.Initialise();
        }

        INoise       noise        = GetNoise(m_noiseType, 0, m_frequency, m_amplitude);
        FractalNoise fractalNoise = new FractalNoise(noise, m_octaves, m_frequency, m_amplitude);

        for (int x = 0; x < chunkSizeXZ; x++)
        {
            for (int z = 0; z < chunkSizeXZ; z++)
            {
                float bedrockHeight = 2;
                float rockHeight    = 0;
                float dirtHeight    = 0;
                //float sandHeight = 12;

                if (RockNoiseLayer)
                {
                    rockHeight += RockNoiseLayer.SampleValue(
                        x / (float)(m_worldResolution - 1),
                        z / (float)(m_worldResolution - 1)
                        );
                }

                if (DirtNoiseLayer)
                {
                    dirtHeight += DirtNoiseLayer.SampleValue(
                        x / (float)(m_worldResolution - 1),
                        z / (float)(m_worldResolution - 1)
                        );
                }

                for (int y = 0; y < chunkHeight; y++)
                {
                    Voxel v = voxelGrid[x, y, z];

                    if (x == 0 || x == chunkSizeXZ - 1 ||
                        y == 0 || y == chunkHeight - 1 ||
                        z == 0 || z == chunkSizeXZ - 1)
                    {
                        v.VoxelType = 0;
                        v.Value     = 0;
                    }
                    else
                    {
                        if (y <= bedrockHeight)
                        {
                            v.VoxelType = 1;
                        }
                        else if (y <= rockHeight)
                        {
                            v.VoxelType = 2;
                        }
                        else if (y <= dirtHeight)
                        {
                            v.VoxelType = 3;
                        }
                        //else if (y <= sandHeight)
                        //{
                        //	v.VoxelType = 4;
                        //}
                        else
                        {
                            v.VoxelType = 0;
                        }

                        float pointValue = fractalNoise.Sample3D(
                            x / (float)(m_worldResolution - 1),
                            y / (float)(m_worldResolution - 1),
                            z / (float)(m_worldResolution - 1)
                            );

                        v.Value = pointValue;
                    }
                }
            }
        }
    }
 public void Initialise()
 {
     fracNoise = new FractalNoise(GetNoise(NoiseType, Seed, Frequency, NoiseAmplitude), Octaves, Frequency, FractalAmplitude);
 }
        void Start()
        {
            m_groundNoise = new FractalNoise(new PerlinNoise(m_seed, m_groundFrq), 6, 1.0f, 0.1f);
            m_treeNoise   = new FractalNoise(new PerlinNoise(m_seed + 1, m_treeFrq), 6, 1.0f);
            m_detailNoise = new FractalNoise(new PerlinNoise(m_seed + 2, m_detailFrq), 6, 1.0f);

            m_heightMapSize = Mathf.ClosestPowerOfTwo(m_heightMapSize) + 1;
            m_alphaMapSize  = Mathf.ClosestPowerOfTwo(m_alphaMapSize);
            m_detailMapSize = Mathf.ClosestPowerOfTwo(m_detailMapSize);

            m_terrainAltitude = Mathf.Clamp(m_terrainAltitude, 0, m_terrainHeight);

            if (m_detailResolutionPerPatch < 8)
            {
                m_detailResolutionPerPatch = 8;
            }

            float[,] htmap = new float[m_heightMapSize, m_heightMapSize];

            m_terrain = new Terrain[m_tilesX, m_tilesZ];

            //this will center terrain at origin
            m_offset = new Vector2(-m_terrainSize * m_tilesX * 0.5f, -m_terrainSize * m_tilesZ * 0.5f);

            CreateProtoTypes();

            for (int x = 0; x < m_tilesX; x++)
            {
                for (int z = 0; z < m_tilesZ; z++)
                {
                    FillHeights(htmap, x, z);

                    TerrainData terrainData = new TerrainData();

                    terrainData.heightmapResolution = m_heightMapSize;
                    terrainData.SetHeights(0, 0, htmap);
                    terrainData.size             = new Vector3(m_terrainSize, m_terrainHeight, m_terrainSize);
                    terrainData.splatPrototypes  = m_splatPrototypes;
                    terrainData.treePrototypes   = m_treeProtoTypes;
                    terrainData.detailPrototypes = m_detailProtoTypes;

                    FillAlphaMap(terrainData);

                    m_terrain[x, z] = Terrain.CreateTerrainGameObject(terrainData).GetComponent <Terrain>();
                    m_terrain[x, z].transform.position  = new Vector3(m_terrainSize * x + m_offset.x, 0, m_terrainSize * z + m_offset.y);
                    m_terrain[x, z].heightmapPixelError = m_pixelMapError;
                    m_terrain[x, z].basemapDistance     = m_baseMapDist;
                    m_terrain[x, z].castShadows         = false;

                    FillTreeInstances(m_terrain[x, z], x, z);
                    FillDetailMap(m_terrain[x, z], x, z);
                }
            }

            //Set the neighbours of terrain to remove seams.
            for (int x = 0; x < m_tilesX; x++)
            {
                for (int z = 0; z < m_tilesZ; z++)
                {
                    Terrain right  = null;
                    Terrain left   = null;
                    Terrain bottom = null;
                    Terrain top    = null;

                    if (x > 0)
                    {
                        left = m_terrain[(x - 1), z];
                    }
                    if (x < m_tilesX - 1)
                    {
                        right = m_terrain[(x + 1), z];
                    }

                    if (z > 0)
                    {
                        bottom = m_terrain[x, (z - 1)];
                    }
                    if (z < m_tilesZ - 1)
                    {
                        top = m_terrain[x, (z + 1)];
                    }

                    m_terrain[x, z].SetNeighbors(left, top, right, bottom);
                }
            }
        }
Beispiel #22
0
    void Start()
    {
        fracNoise = new FractalNoise (1.27F, 2.04F, 8.36F);
        fracNoiseBig = new FractalNoise (1.27F, 2.04F, 8.36F);

        // Ground
        ConstructGround(
            numPoints,
            0,
            plateWidth,
            10,
            Random.seed,
            groundBiome
            );
    }
Beispiel #23
0
    void Generate()
    {
        DateTime startTime = System.DateTime.Now;

        INoise       perlin  = new PerlinNoise(seed, 2f);
        FractalNoise fractal = new FractalNoise(perlin, 3, 1f);

        MarchingCube marching = new MarchingCube();

        Marching.Surface = 0f;

        width  = sizeScale;
        height = sizeScale;
        length = sizeScale;

        float[] voxels = new float[width * height * length];

        //Fill voxels with values. Im using perlin noise but any method to create voxels will work.
        for (int x = 0; x < width; x++)
        {
            for (int y = 0; y < height; y++)
            {
                for (int z = 0; z < length; z++)
                {
                    float fx = x / (width - 1.0f);
                    float fy = y / (height - 1.0f);
                    float fz = z / (length - 1.0f);

                    int idx = x + y * width + z * width * height;

                    voxels[idx] = fractal.Sample3D(fx, fy, fz);
                }
            }
        }

        verts   = new List <Vector3>();
        indices = new List <int>();


        if (useJobSystem)
        {
            MarchingCubeParallel          marching_p = new MarchingCubeParallel(0);
            MarchingCubeParallel.MarchJob job;
            JobHandle handle = marching_p.Generate(new List <float>(voxels), width, height, length, out job);
            StartCoroutine(Wait4Complete(handle, job));
        }
        else
        {
            marching.Generate(voxels, width, height, length, verts, indices);
            int maxVertsPerMesh = 30000; //must be divisible by 3, ie 3 verts == 1 triangle
            int numMeshes       = verts.Count / maxVertsPerMesh + 1;
            for (int i = 0; i < numMeshes; i++)
            {
                List <Vector3> splitVerts   = new List <Vector3>();
                List <int>     splitIndices = new List <int>();

                for (int j = 0; j < maxVertsPerMesh; j++)
                {
                    int idx = i * maxVertsPerMesh + j;

                    if (idx < verts.Count)
                    {
                        splitVerts.Add(verts[idx]);
                        splitIndices.Add(j);
                    }
                }

                if (splitVerts.Count == 0)
                {
                    continue;
                }

                Mesh mesh = new Mesh();
                mesh.SetVertices(splitVerts);
                mesh.SetTriangles(splitIndices, 0);
                mesh.RecalculateBounds();
                mesh.RecalculateNormals();

                GameObject go = new GameObject("Mesh");
                go.transform.parent = transform;
                go.AddComponent <MeshFilter>();
                go.AddComponent <MeshRenderer>();
                go.GetComponent <Renderer>().material = m_material;
                go.GetComponent <MeshFilter>().mesh   = mesh;
                go.transform.localPosition            = new Vector3(-width / 2, -height / 2, -length / 2);

                meshes.Add(go);
            }
        }
        double timeCost = System.DateTime.Now.Subtract(startTime).TotalMilliseconds;

        print("Time Cost : " + timeCost + " at size " + (8 * sizeScale));
    }
Beispiel #24
0
 void Awake()
 {
     seed = Random.Range (0,256);
     fracNoise = new FractalNoise (1.27F, 2.04F, 8.36F);
 }
Beispiel #25
0
	private static FractalNoise Get () { 
		if (s_Noise == null)
			s_Noise = new FractalNoise (1.27F, 2.04F, 8.36F);
		return s_Noise;		
	 }
 public Noise3DNode()
 {
     perlin  = new PerlinNoise(1337, 2.0f);
     fractal = new FractalNoise(perlin, 3, 1.0f);
 }
        void Start()
        {
            m_mountainNoise = new FractalNoise(new PerlinNoise(m_mountainSeed, m_mountainFrq), 6, 1.0f, 1.0f);

            if (!Mathf.IsPowerOfTwo(m_heightMapSize - 1))
            {
                Debug.Log("height map size must be pow2+1 number");
                m_heightMapSize = Mathf.ClosestPowerOfTwo(m_heightMapSize) + 1;
            }

            if (!Mathf.IsPowerOfTwo(m_alphaMapSize))
            {
                Debug.Log("Alpha map size must be pow2 number");
                m_alphaMapSize = Mathf.ClosestPowerOfTwo(m_alphaMapSize);
            }

            float[,] htmap = new float[m_heightMapSize, m_heightMapSize];

            m_terrain = new Terrain[m_tilesX, m_tilesZ];

            //this will center terrain at origin
            m_offset = new Vector2(-m_terrainSize * m_tilesX * 0.5f, -m_terrainSize * m_tilesZ * 0.5f);

            CreateProtoTypes();

            for (int x = 0; x < m_tilesX; x++)
            {
                for (int z = 0; z < m_tilesZ; z++)
                {
                    FillHeights(htmap, x, z);

                    TerrainData terrainData = new TerrainData();

                    terrainData.heightmapResolution = m_heightMapSize;
                    terrainData.SetHeights(0, 0, htmap);
                    terrainData.size            = new Vector3(m_terrainSize, m_terrainHeight, m_terrainSize);
                    terrainData.splatPrototypes = m_splatPrototypes;

                    FillAlphaMap(terrainData);

                    m_terrain[x, z] = Terrain.CreateTerrainGameObject(terrainData).GetComponent <Terrain>();

                    m_terrain[x, z].transform.parent        = transform;
                    m_terrain[x, z].transform.localPosition = new Vector3(m_terrainSize * x + m_offset.x, 0, m_terrainSize * z + m_offset.y);
                    m_terrain[x, z].heightmapPixelError     = m_pixelMapError;
                    m_terrain[x, z].basemapDistance         = m_baseMapDist;
                }
            }

            //Set the neighbours of terrain to remove seams.
            for (int x = 0; x < m_tilesX; x++)
            {
                for (int z = 0; z < m_tilesZ; z++)
                {
                    Terrain right  = null;
                    Terrain left   = null;
                    Terrain bottom = null;
                    Terrain top    = null;

                    if (x > 0)
                    {
                        left = m_terrain[(x - 1), z];
                    }
                    if (x < m_tilesX - 1)
                    {
                        right = m_terrain[(x + 1), z];
                    }

                    if (z > 0)
                    {
                        bottom = m_terrain[x, (z - 1)];
                    }
                    if (z < m_tilesZ - 1)
                    {
                        top = m_terrain[x, (z + 1)];
                    }

                    m_terrain[x, z].SetNeighbors(left, top, right, bottom);
                }
            }
        }
Beispiel #28
0
        void Start()
        {
            INoise       perlin  = new PerlinNoise(seed, 2.0f);
            FractalNoise fractal = new FractalNoise(perlin, 3, 1.0f);

            //Set the mode used to create the mesh.
            //Cubes is faster and creates less verts, tetrahedrons is slower and creates more verts but better represents the mesh surface.
            Marching marching = null;

            if (mode == MARCHING_MODE.TETRAHEDRON)
            {
                marching = new MarchingTertrahedron();
            }
            else
            {
                marching = new MarchingCubes();
            }

            //Surface is the value that represents the surface of mesh
            //For example the perlin noise has a range of -1 to 1 so the mid point is where we want the surface to cut through.
            //The target value does not have to be the mid point it can be any value with in the range.
            marching.Surface = 0.0f;

            //The size of voxel array.
            int width  = 32;
            int height = 32;
            int length = 32;

            float[] voxels = new float[width * height * length];

            //Fill voxels with values. Im using perlin noise but any method to create voxels will work.
            for (int x = 0; x < width; x++)
            {
                for (int y = 0; y < height; y++)
                {
                    for (int z = 0; z < length; z++)
                    {
                        float fx = x / (width - 1.0f);
                        float fy = y / (height - 1.0f);
                        float fz = z / (length - 1.0f);

                        int idx = x + y * width + z * width * height;

                        voxels[idx] = fractal.Sample3D(fx, fy, fz);
                    }
                }
            }

            List <Vector3> verts   = new List <Vector3>();
            List <int>     indices = new List <int>();

            System.Diagnostics.Stopwatch measure = new System.Diagnostics.Stopwatch();
            measure.Start();

            marching.Generate(voxels, width, height, length, verts, indices);

            verts = MeshUtils.WeldVertices(verts, indices);

            measure.Stop();

            Debug.Log(string.Format("Time elapsed: {0}", measure.Elapsed));

            Mesh mesh = new Mesh();

            mesh.indexFormat = UnityEngine.Rendering.IndexFormat.UInt32;
            mesh.SetVertices(verts);
            mesh.SetTriangles(indices, 0);
            mesh.RecalculateBounds();
            mesh.RecalculateNormals();

            GameObject go = new GameObject("Mesh");

            go.transform.parent = transform;
            go.AddComponent <MeshFilter>();
            go.AddComponent <MeshRenderer>();
            go.GetComponent <Renderer>().material = m_material;
            go.GetComponent <MeshFilter>().mesh   = mesh;
            go.transform.localPosition            = new Vector3(-width / 2, -height / 2, -length / 2);
        }