Example #1
0
    void Awake()
    {
        m_noise     = new Noise (2);
        m_tileSheet = new TileSheet (m_width, m_height);

        m_tileRules = new TileChoise[8];
        m_tileRules [0] = new TileChoise (TileShape.DownRight, TileCriteria.No, TileCriteria.Yes, TileCriteria.No, TileCriteria.Yes);
        m_tileRules [1] = new TileChoise (TileShape.DownLeft, TileCriteria.No, TileCriteria.Yes, TileCriteria.Yes, TileCriteria.No);
        m_tileRules [2] = new TileChoise (TileShape.UpRight, TileCriteria.Yes, TileCriteria.No, TileCriteria.No, TileCriteria.Yes);
        m_tileRules [3] = new TileChoise (TileShape.UpLeft, TileCriteria.Yes, TileCriteria.No, TileCriteria.Yes, TileCriteria.No);
        m_tileRules [4] = new TileChoise (TileShape.Down, TileCriteria.Yes, TileCriteria.No, TileCriteria.DontCare, TileCriteria.DontCare);
        m_tileRules [5] = new TileChoise (TileShape.Up, TileCriteria.No, TileCriteria.DontCare, TileCriteria.DontCare, TileCriteria.DontCare);
        m_tileRules [6] = new TileChoise (TileShape.Left, TileCriteria.DontCare, TileCriteria.DontCare, TileCriteria.No, TileCriteria.Yes);
        m_tileRules [7] = new TileChoise (TileShape.Right, TileCriteria.DontCare, TileCriteria.DontCare, TileCriteria.Yes, TileCriteria.No);

        int textureSize = 2048;
        m_texture = new Texture2D (textureSize, textureSize);
        for (int x = 0; x < textureSize; x++)
          for (int y = 0; y < textureSize; y++)
        m_texture.SetPixel (x, y,  new Color (1, 1, 1, 0)); //(float)x/(float)textureSize, (float)y/(float)textureSize, (float)(x-y)/(float)textureSize));
        m_texture.Apply ();

        SpriteRenderer renderer =  GetComponent<SpriteRenderer>();
        Sprite sprite = new Sprite ();
        sprite = Sprite.Create (m_texture,new Rect(0, 0, textureSize, textureSize), new Vector2 (0,0), 1f);
        renderer.sprite = sprite;
        renderer.sortingLayerName = "Level base";

        m_platformManager = new PlatformManager ();

        GenerateLevel ();
    }
Example #2
0
	public void TriggerNoiseEvent(Noise noise)
	{
		if(OnNoiseMade != null)
		{
			OnNoiseMade(noise);
		}
	}
Example #3
0
 void Awake() 
 {
     instance = this;
     mRands = new int[512];
     for (int x = 0; x < 512; x++) 
     {
         mRands[x] = permutation[ x % 256 ];
     }
 }
	void Start()
	{
		myTransform = this.transform;
		initPos = myTransform.position;
		noiseBigX = new Noise(bigSpeed);
		noiseBigY = new Noise(bigSpeed);
		noiseSmallX = new Noise(smallSpeed);
		noiseSmallY = new Noise(smallSpeed);
	}
Example #5
0
 public Grungy(Size ImageSize)
 {
     _gamma = new Gamma(1.5F);
     _clip = new Clip(25);
     _saturation = new Saturation(-60);
     _contract = new Contracts(5);
     _noise = new Noise(5);
     _vignette = new Vignette(ImageSize, 50, 30);
 }
Example #6
0
        public Vintage(Size ImageSize)
        {
            _greyScale = new GreyScale();
            _contract = new Contracts(5);
            _noice = new Noise(3);
            _Sepia = new Sepia(100);
            _channel = new Channels(Color.FromArgb(8, 4, 2));
            _gamma = new Gamma(0.87F);

            _vignette = new Vignette(ImageSize, 40, 30);
        }
Example #7
0
 void Start()
 {
     //Makes the block index fetch all the BlockDefinition components
     //on this gameobject and add them to the index
     Block.index.GetMissingDefinitions();
     noiseGen = new Noise(worldName);
     terrainGen = gameObject.GetComponent<TerrainGen>();
     terrainGen.noiseGen = noiseGen;
     terrainGen.world = this;
     random = new System.Random();
 }
Example #8
0
    public TerrainLayer SetUpTerrainLayer(World world, Noise noise)
    {
        this.world = world;
        this.noiseGen = noise;
        if (layerType == LayerType.Structure)
        {
            var type = Type.GetType(structureClassName + ", " + typeof(GeneratedStructure).Assembly);
            structure = (GeneratedStructure)Activator.CreateInstance(type);
        }

        return this;
    }
Example #9
0
    private float _onGroundTime; //time to live after first collision

    #endregion Fields

    #region Methods

    void OnCollisionEnter(Collision collision)
    {
        if(!_hasCollided && IsThrown)
        {
            _hasCollided = true;
            Noise noise = new Noise();
            noise.Enabled = true;
            noise.NoiseType = NoiseTypeEnum.Impact;
            noise.Location = collision.contacts[0].point;
            noise.SourceCharacter = null;
            noise.Volume = 0.35f;

            SoundEventHandler.Instance.TriggerNoiseEvent(noise);
        }
    }
Example #10
0
        public RealisticMapGenState( [NotNull] RealisticMapGenParameters genParameters ) {
            if( genParameters == null ) throw new ArgumentNullException( "genParameters" );
            genParams = genParameters;
            genParams.Validate();
            Parameters = genParameters;

            if( !genParams.CustomWaterLevel ) {
                genParams.WaterLevel = (genParams.MapHeight - 1) / 2;
            }

            rand = new Random( genParams.Seed );
            noise = new Noise( genParams.Seed, NoiseInterpolationMode.Bicubic );
            EstimateComplexity();

            ReportsProgress = true;
            SupportsCancellation = true;
        }
Example #11
0
    public static Texture2D Simplex2D(int width, int height, float scale, NoiseStyle style, float min, float max)
    {
        Texture2D noiseTexture = new Texture2D(width, height, TextureFormat.ARGB32, false);

        Noise noise = new Noise();
        noise.addChannel(new Channel("Color", Algorithm.Simplex2d, scale, style, min, max, Edge.Smooth));

        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                Vector3 vector = new Vector3((float)x, 0.0f, (float)y);

                float sample = noise.getNoise(vector, "Color");
                noiseTexture.SetPixel(x, y, new Color(sample, sample, sample, 1.0f));
            }
        }

        noiseTexture.Apply();
        return noiseTexture;
    }
Example #12
0
    // Use this for initialization
    void Start()
    {
        state = GameState.Instance;
        Texture2D oilTex = new Texture2D(640, 640, TextureFormat.ARGB32, false);

        Color[] colors = oilTex.GetPixels();

        Noise noise = new Noise();

        float offsetx = (float)Random.Range(-32f, 32f);
        float offsety = (float)Random.Range(-32f, 32f);

        float pi = 3.14159265359f;
        float twopi = pi * 2f;

        for (int y = 0; y < oilTex.height; y++)
        {
            int row = oilTex.width * y;
            for (int x = 0; x < oilTex.width; x++)
            {
                float theta = twopi * (x / (float)oilTex.width);
                float phi = pi * (y / (float)oilTex.height);

                float x3d = Mathf.Cos(theta) * Mathf.Sin(phi);
                float y3d = Mathf.Sin(theta) * Mathf.Sin(phi);
                float z3d = -Mathf.Cos(phi);

                float color = noise.noise3(x3d * 2f + offsetx, y3d * 2f + offsety,z3d*2f );

                if (color > .3f / state.oilFactor) color = 1;
                colors[row + x] = new Color(color, 0, 0, 1f);

            }
        }

        oilTex.SetPixels(colors);
        oilTex.Apply();
        renderer.material.mainTexture = oilTex;
        state.oilColors = colors;
        state.oilTex = oilTex;
    }
Example #13
0
    // -------------------------------------------------------------------------------------------
    void Awake()
    {
        m_noise = new Noise (3);

        m_spriteRenderer = GetComponent<SpriteRenderer> ();

        Texture2D texture = new Texture2D (m_textureSize, m_textureSize);
        for (int x = 0; x < m_textureSize; x++)
          for (int y = 0; y < m_textureSize; y++)
          texture.SetPixel (x, y, Color.black);

        JustNoise (texture);

        //PlatformNoiseBuilder pnb = new PlatformNoiseBuilder ();
        //pnb.Create (texture, new Vector2 (m_textureSize, m_textureSize));

        texture.Apply ();

        Rect spriteRect = new Rect (0, 0, m_textureSize, m_textureSize);
        m_spriteRenderer.sprite = Sprite.Create (texture, spriteRect, new Vector2 (0.5f, 0.5f));
    }
    void Start()
    {
        groundNoise = new Noise();
        groundNoise.setPermutations (groundSeed);

        mountainNoise = new Noise();
        mountainNoise.setPermutations (mountainSeed);

        treeNoise = new Noise();
        treeNoise.setPermutations (treeSeed);

        detailNoise = new Noise();
        detailNoise.setPermutations (detailSeed);

        if(!Mathf.IsPowerOfTwo(heightMapSize-1))
        {
            heightMapSize = Mathf.ClosestPowerOfTwo(heightMapSize)+1;
        }

        if(!Mathf.IsPowerOfTwo(alphaMapSize))
        {
            alphaMapSize = Mathf.ClosestPowerOfTwo(alphaMapSize);
        }

        if(!Mathf.IsPowerOfTwo(detailMapSize))
        {
            detailMapSize = Mathf.ClosestPowerOfTwo(detailMapSize);
        }

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

        //		terrain = new Terrain[tilesX,tilesZ];

        //this will center terrain at origin

        //populate prototypes
        if(splatDataCreated()){
            Debug.Log("Splats Created");
            if (treeDataCreated ()) {
                Debug.Log ("Trees Created");
                if(detailsDataCreated()){
                    Debug.Log("Details Created");
                }
            }
        }

        Terrain[,] terrain = new Terrain[tilesX, tilesZ];

        //		for(int x = 0; x < tilesX; x++)
        //		{
        //			for(int z = 0; z < tilesZ; z++)
        //			{
        //				GenerateTerrains(x, z, terrain[x,z] );
        //			}
        //		}

        // Get Player's initial position
        startPos = Vector3.zero;
        Debug.Log (startPos);

        // Generate 4 terrains at the beginning
        current = GenerateTerrains(x, z, current );

        if(left == null) {
            int leftX = x-1;
            left = GenerateTerrains(leftX, z, left );
        }
        if(right == null) {
            int rightX = x+1;
            right = GenerateTerrains(rightX, z, right );
        }
        if(top == null) {
            int topZ = z+1;
            top = GenerateTerrains(x, topZ, top );
        }
        if(bottom == null) {
            int botZ = z-1;
            bottom = GenerateTerrains(x, botZ, bottom );
        }

        listX.Add (x);
        listZ.Add (z);

        Debug.Log (listX.Contains(x));
    }
Example #15
0
 public OldTerrainGen(Noise noise)
 {
     noiseGen = noise;
     treeStructure = new StructureTree();
 }
Example #16
0
    void Start()
    {
        worldName = saveName;

        worldSave = Serialization.SaveLocation(worldName) + "/world.txt";
        randomSeed = Random.Range(1000, 10000000);

        //Makes the block index fetch all the BlockDefinition components
        //on this gameobject and add them to the index
        Block.index.GetMissingDefinitions();

        worldArray = new string[,] { { "worldname", worldName }, { "seed", seed }, { "flatland", isFlat } };

        //Check if the world.txt exists, and get the seed from that
        if (File.Exists(worldSave)) {
            CheckSettings();
            seed = ConfigManager.ReadSettings("seed", worldSave);
            isFlat = ConfigManager.ReadSettings("flatland", worldSave);
        } else {
            if (saveSeed != "") {
                worldArray[1, 1] = saveSeed;
            }else{
                worldArray[1, 1] = randomSeed.ToString();
            }

            worldArray[2, 1] = isFlat.ToString();

            //Create the lines
            var sr = File.CreateText(worldSave);
            for (int i = 0; i < worldArray.GetLength(0); i++) {
                sr.WriteLine(worldArray[i, 0] + " = " + worldArray[i, 1]);
            }
            sr.Close();
        }

        noiseGen = new Noise(seed);
    }
Example #17
0
    GameObject BuildChunk(Vec2 coord)
    {
        Vector3[] verts = new Vector3[(GRID_SIZE + 3) * (GRID_SIZE + 3)];
        int[]     tris  = new int[(GRID_SIZE + 2) * (GRID_SIZE + 2) * 6];
        //Vector2[] uvs = new Vector2[verts.Length];
        GameObject go = new GameObject(string.Format("Chunk ({0},{1})", coord.x, coord.y));

        // generate vertices and colors
        List <Vector3> kelpPoints = new List <Vector3>();

        for (int i = 0, y = -1; y <= GRID_SIZE + 1; ++y)
        {
            for (int x = -1; x <= GRID_SIZE + 1; ++x, ++i)
            {
                float   xf = (x + coord.x * GRID_SIZE - GRID_SIZE / 2.0f) * GRID_SCALE;
                float   yf = (y + coord.y * GRID_SIZE - GRID_SIZE / 2.0f) * GRID_SCALE;
                Vector3 p  = GeneratePoint(xf, yf);
                verts[i] = p;

                if (Noise.Billow(new Vector3(xf, yf, 0), 3, 0.02f) > -0.2f)
                {
                    kelpPoints.Add(p);
                }

                if (Random.value < 0.02f)
                {
                    bool isCoral = Random.value < 0.25f;
                    if (isCoral)
                    {
                        GameObject pre  = Instantiate(coralPrefab, p, Random.rotation, go.transform);
                        MeshData   data = MeshGenerator.GenerateIcosphere(3);
                        for (int j = 0; j < data.vertices.Length; ++j)
                        {
                            data.vertices[j] *= 1.0f + Noise.Ridged(data.vertices[j], 3, Random.Range(0.5f, 1.0f)) * 0.5f;
                        }
                        pre.GetComponent <MeshFilter>().sharedMesh = data.CreateMesh();

                        pre.transform.localScale = Vector3.one * (2 + Random.value * 5);
                    }
                    else
                    {
                        GameObject pre  = Instantiate(rockPrefab, p, Random.rotation, go.transform);
                        MeshData   data = MeshGenerator.GenerateIcosphere(1);
                        for (int j = 0; j < data.vertices.Length; ++j)
                        {
                            data.vertices[j] *= 1.0f + Noise.Ridged(data.vertices[j], 3, Random.Range(0.3f, 0.8f)) * 0.3f;
                        }
                        pre.GetComponent <MeshFilter>().sharedMesh = data.CreateMesh();

                        pre.transform.localScale = Vector3.one * (1 + Random.value * 3);
                    }
                }

                if (Random.value < 0.0025f)
                {
                    GameObject g = Instantiate(recyclerPrefab, p + Vector3.up * 0.8f, Quaternion.identity, go.transform);
                }

                if (Random.value < 0.005f)
                {
                    GameObject creature = Instantiate(creatures[Random.Range(0, creatures.Length)], p + Vector3.up * (2.0f + Random.value * 10.0f), Quaternion.identity, go.transform);
                }

                if (Random.value < 0.0015f)
                {
                    GameObject trash = Instantiate(trashes[Random.Range(0, trashes.Length)], new Vector3(p.x, 70 - Random.Range(1.0f, 10.0f), p.z), Random.rotation, go.transform);
                }
            }
        }

        Mesh       kelps  = MeshGenerator.GenerateStrips(kelpPoints);
        GameObject kelpGo = Instantiate(kelpPrefab, Vector3.zero, Quaternion.identity, go.transform);

        kelpGo.GetComponent <MeshFilter>().sharedMesh = kelps;

        // generate triangles
        GenerateTriangles(tris, GRID_SIZE + 2);

        // generate the normals
        Vector3[] normals = new Vector3[verts.Length];
        for (int i = 0; i < tris.Length / 3; ++i)
        {
            int a = tris[i * 3];
            int b = tris[i * 3 + 1];
            int c = tris[i * 3 + 2];

            Vector3 va = verts[a];
            Vector3 vb = verts[b];
            Vector3 vc = verts[c];

            Vector3 norm = Vector3.Cross(vb - va, vc - va);
            normals[a] += norm;
            normals[b] += norm;
            normals[c] += norm;
        }
        for (int i = 0; i < normals.Length; ++i)
        {
            normals[i].Normalize();
        }

        // now slice off extra vert layer
        Vector3[] vs = new Vector3[(GRID_SIZE + 1) * (GRID_SIZE + 1)];
        Vector3[] ns = new Vector3[vs.Length];
        int[]     ts = new int[GRID_SIZE * GRID_SIZE * 6];
        for (int y = 0; y < GRID_SIZE + 1; ++y)
        {
            for (int x = 0; x < GRID_SIZE + 1; ++x)
            {
                int oi = x + y * (GRID_SIZE + 1);
                int ci = (x + 1) + (y + 1) * (GRID_SIZE + 3);
                vs[oi] = verts[ci];
                ns[oi] = normals[ci];
            }
        }

        GenerateTriangles(ts, GRID_SIZE);

        Mesh m = new Mesh();

        m.vertices  = vs;
        m.triangles = ts;
        m.normals   = ns;

        go.transform.parent = transform;

        // build mesh collider from the shared mesh
        go.AddComponent <MeshCollider>().sharedMesh = m;

        m.RecalculateBounds();
        //m.RecalculateNormals();

        go.AddComponent <MeshFilter>().mesh = m;
        MeshRenderer mr = go.AddComponent <MeshRenderer>();

        mr.material          = mat;
        mr.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.TwoSided;

        return(go);
    }
Example #18
0
 public static float GetNoise(int x, int y, int z, float scale, float max)
 {
     //return (Noise.Generate(x * scale, y * scale, z * scale) + 1f) * (max / 2f);
     return(Noise.Generate(x * scale, y * scale, z * scale) * max);
 }
Example #19
0
    public byte GetVoxel(Vector3 pos)
    {
        int yPos = Mathf.FloorToInt(pos.y);

        //      -- IMMUTABLES --

        // Outside the world => air
        if (!IsVoxelInWorld(pos))
        {
            return(0);
        }

        // Bottom of chunk => bedrock
        if (yPos == 0)
        {
            return(1);
        }

        //      -- BIOME SELECT --

        int   solidGroundHeight = 42; // always solid below this level
        float sumOfHeights      = 0f;
        int   counter           = 0;

        (float weight, int biome_index)strongestWeight = (0, 0);

        for (int i = 0; i < biomes.Length; i++)
        {
            float weight = Noise.Get2DPerlin(new Vector2(pos.x, pos.z), biomes[i].offset, biomes[i].scale);
            // Assign a "strongest" weight.
            if (weight > strongestWeight.weight)
            {
                strongestWeight.weight      = weight;
                strongestWeight.biome_index = i;
            }

            // Get biome's terrain height and mult. by weigth.
            float height = biomes[i].terrainHeight * Noise.Get2DPerlin(new Vector2(pos.x, pos.z), 0, biomes[i].terrainScale) * weight;

            if (height > 0)
            {
                sumOfHeights += height;
                counter++;
            }
        }

        BiomeAttributes biome = biomes[strongestWeight.biome_index];

        sumOfHeights /= counter;

        int terrainHeight = Mathf.FloorToInt(sumOfHeights + solidGroundHeight);

        //      -- TERRAIN PASS --

        byte voxelValue = 0;

        if (yPos == terrainHeight)
        {
            voxelValue = biome.surfaceBlock;
        }
        else if (yPos < terrainHeight && yPos > terrainHeight - 4)
        {
            voxelValue = biome.subSurfaceBlock;
        }
        else if (yPos > terrainHeight)
        {
            return(0);
        }
        else
        {
            voxelValue = 2;
        }

        //      -- SECOND PASS --

        if (voxelValue == 2)
        {
            foreach (Lode l in biome.lodes)
            {
                if (yPos > l.minHeight && yPos < l.maxHeight)
                {
                    if (Noise.Get3DPerlin(pos, l.noiseOffset, l.scale, l.threshold))
                    {
                        voxelValue = l.blockID;
                    }
                }
            }
        }

        //      -- FLORA PASS --

        if (yPos == terrainHeight && biome.placeBigFlora)
        {
            if (Noise.Get2DPerlin(new Vector2(pos.x, pos.z), 0, biome.bigFloraZoneScale) > biome.bigFloraZoneTreshold)
            {
                if (Noise.Get2DPerlin(new Vector2(pos.x, pos.z), 0, biome.bigFloraPlacementScale) > biome.bigFloraPlacementThreshold)
                {
                    var test = Structure.GenerateBigFlora(biome.majorFloraIndex, pos, biome.minHeight, biome.maxHeight);
                    modifications.Enqueue(test);
                }
            }
        }

        return(voxelValue);
    }
Example #20
0
        private void Draw(GraphicsDevice graphics, DwarfTime time)
        {
            Bloom.BeginDraw();
            try
            {
                graphics.Clear(Color.SkyBlue);
                DwarfGame.SafeSpriteBatchBegin(SpriteSortMode.Deferred, BlendState.NonPremultiplied, Drawer2D.PointMagLinearMin,
                                               DepthStencilState.Default, RasterizerState.CullNone, null, Matrix.Identity);


                Rectangle screenRect = graphics.Viewport.Bounds;

                int maxX = screenRect.Width / TileSize + 2;
                int maxY = screenRect.Width / TileSize;


                float t = (float)time.TotalRealTime.TotalSeconds;

                float offsetX = t * 2.0f;
                float offsetY = 0.0f;

                float st = (float)Math.Abs(Math.Sin(t));

                float lava     = LavaHeight;
                int   backSize = 2;

                for (int ix = 0; ix < maxX * backSize; ix++)
                {
                    float x = ix + (int)(offsetX * 0.6f);

                    float height = Noise.Noise(x * HeightScale * 3, 0, 100) * 0.5f + 0.6f;
                    for (int iy = 0; iy < maxY * backSize; iy++)
                    {
                        float y           = iy + (int)offsetY;
                        float normalizedY = (1.0f) - (float)y / (float)(maxY * backSize);

                        if (normalizedY < height)
                        {
                            float tileX = ix * (TileSize / backSize) - ((offsetX * 0.6f) * (TileSize / backSize)) % (TileSize / backSize);
                            float tileY = iy * (TileSize / backSize);

                            Drawer2D.FillRect(DwarfGame.SpriteBatch, new Rectangle((int)tileX, (int)tileY, TileSize / backSize, TileSize / backSize),
                                              new Color((int)(Color.SkyBlue.R * normalizedY * 0.8f), (int)(Color.SkyBlue.G * normalizedY * 0.8f),
                                                        (int)(Color.SkyBlue.B * normalizedY)));
                        }
                    }
                }


                for (int ix = 0; ix < maxX; ix++)
                {
                    float x      = ix + (int)offsetX;
                    float height = Noise.Noise(x * HeightScale, 0, 0) * 0.8f + MinHeight;
                    for (int iy = 0; iy < maxY; iy++)
                    {
                        float y           = iy + (int)offsetY;
                        float normalizedY = (1.0f) - (float)y / (float)maxY;

                        if (Math.Abs(normalizedY - height) < 0.01f)
                        {
                            Color tint = new Color(normalizedY, normalizedY, normalizedY);

                            RenderTile(Grass, DwarfGame.SpriteBatch, ix, iy, offsetX, t, tint);
                        }
                        else if (normalizedY > height - 0.1f && normalizedY < height)
                        {
                            Color tint = new Color((float)Math.Pow(normalizedY, 1.5f), (float)Math.Pow(normalizedY, 1.6f),
                                                   normalizedY);

                            RenderTile(Soil, DwarfGame.SpriteBatch, ix, iy, offsetX, t, tint);
                        }
                        else if (normalizedY < height)
                        {
                            float caviness = Noise.Noise(x * CaveScale, y * CaveScale, 0);

                            if (caviness < CaveThreshold)
                            {
                                TerrainElement?oreFound = null;

                                int i = 0;
                                foreach (TerrainElement ore in Ores)
                                {
                                    i++;
                                    float oreNess = Noise.Noise(x * ore.SpawnScale, y * ore.SpawnScale, i);

                                    if (oreNess > ore.SpawnThreshold)
                                    {
                                        oreFound = ore;
                                    }
                                }

                                Color tint = new Color((float)Math.Pow(normalizedY, 1.5f) * 0.5f,
                                                       (float)Math.Pow(normalizedY, 1.6f) * 0.5f, normalizedY * 0.5f);

                                if (oreFound == null)
                                {
                                    RenderTile(Substrate, DwarfGame.SpriteBatch, ix, iy, offsetX, t, tint);
                                }
                                else
                                {
                                    RenderTile(oreFound.Value, DwarfGame.SpriteBatch, ix, iy, offsetX, t, tint);
                                }
                            }
                            else
                            {
                                if (normalizedY < lava)
                                {
                                    float glowiness = Noise.Noise(x * CaveScale * 2, y * CaveScale * 2, t);
                                    RenderTile(Lava, DwarfGame.SpriteBatch, ix, iy, offsetX, t,
                                               new Color(0.5f * glowiness + 0.5f, 0.7f * glowiness + 0.3f * st, glowiness));
                                }
                                else
                                {
                                    RenderTile(Cave, DwarfGame.SpriteBatch, ix, iy, offsetX, t,
                                               new Color((float)Math.Pow(normalizedY, 1.5f) * (1.0f - caviness) * 0.8f,
                                                         (float)Math.Pow(normalizedY, 1.6f) * (1.0f - caviness) * 0.8f,
                                                         normalizedY * (1.0f - caviness)));
                                }
                            }
                        }
                    }
                }
            }
            finally
            {
                DwarfGame.SpriteBatch.End();
            }

            Bloom.Draw(time.ToGameTime());
        }
Example #21
0
    private Texture2D CreateTexture(string face)
    {
        switch (face)
        {
        case "xy": offset = new Vector2(0, 0); break;

        case "xyz":
        case "zy": offset = new Vector2(-gridSize, 0); break;

        case "zyx": offset = new Vector2(gridSize, 0); break;

        case "xz": offset = new Vector2(0, gridSize); break;

        case "xzy": offset = new Vector2(0, -gridSize); break;
        }

        //Generate Noise Map and ColourMap
        int width  = gridSize + 1;
        int height = gridSize + 1;

        noiseMap  = Noise.GenerateNoiseMap(width, height, seed, scale, octaves, persistance, lacunarity, offset, normalizeMode);
        colourMap = new Color[width * height];

        /*for(int i=0; i<10; i++)
         * {
         *  for(int j=0; j<10; j++)
         *  {
         *      noiseMap[i, j] = 1;
         *  }
         * }*/

        if (face == "zy" || face == "xz")
        {
            noiseMap = FLipMatrix(noiseMap, width, height, face);
        }

        for (int i = 0; i < height; i++)
        {
            for (int j = 0; j < width; j++)
            {
                //FalloffMap
                //noiseMap[j, i] = Mathf.Clamp01(noiseMap[j, i] - falloffMap[j, i]);  //?
                //
                float currentHeight = noiseMap[j, i];
                for (int k = 0; k < regions.Length; k++)
                {
                    if (currentHeight >= regions[k].height)
                    {
                        colourMap[i * width + j] = regions[k].colour;
                    }
                    else
                    {
                        colourMap[i * width + j] = regions[k].colour;
                        break;
                    }
                }
            }
        }

        Texture2D texture = TextureGenerator.TextureFromHeightMap(noiseMap, colourMap);

        return(texture);
    }
Example #22
0
    // Update is called once per frame
    void Update()
    {
        PlayerControlAndResponse();
        SimulateCameraEffects();

        // UnLock cursor (DEBUG)
        if (Input.GetKey(KeyCode.Escape))
        {
            Cursor.lockState = CursorLockMode.None;
        }

        // Check if under water-line
        swimming = transform.position.y - Config.PLAYER_HEIGHT / 2.0f < World.SEA_LEVEL + Noise.GetSeaOffset().y;

        // Wait for world to load before starting physics
        // This is crude but works, ideally would check if current chunk below player has loaded.
        if (start_physics || Time.realtimeSinceStartup - start_time > 2.0f)
        {
            start_physics = true;

            if (swimming)
            {
                if (Mathf.Abs(player_rigidbody.velocity.y) > Config.MAX_WATER_VELOCITY)
                {
                    player_rigidbody.velocity = new Vector3(player_rigidbody.velocity.x, Mathf.Sign(player_rigidbody.velocity.y) * Config.MAX_WATER_VELOCITY, player_rigidbody.velocity.z);
                }

                Physics.gravity = new Vector3(0.0f, Config.GRAVITY / 10.0f, 0.0f);
            }
            else
            {
                Physics.gravity = new Vector3(0.0f, Config.GRAVITY, 0.0f);
            }
        }
    }
Example #23
0
 public void Add(Noise n) {
     noises.Add(n);
 }
Example #24
0
 public Field(Noise[] n = null) {
     if (n != null)
         noises.AddRange(n);
 }
Example #25
0
    public byte GetVoxel(Vector3 pos)
    {
        int yPos = Mathf.FloorToInt(pos.y);

        /* Boundary conditions*/
        //if outside world
        if (!IsVoxelInWorld(pos))
        {
            return(0);
        }
        //if bottom block then return bedrock
        if (yPos == 0)
        {
            return(1);
        }

        //BIOME SELECTION PASS
        int   groundHeight        = 42;
        float sumOfHeights        = 0f;
        int   count               = 0;
        float strongestWeight     = 0f;
        int   strongestBiomeIndex = 0;

        for (int i = 0; i < biomes.Length; i++)
        {
            float weight = Noise.Get2DPerlin(new Vector2(pos.x, pos.z), biomes[i].offset, biomes[i].scale);

            if (weight > strongestWeight)
            {
                strongestWeight     = weight;
                strongestBiomeIndex = i;
            }

            //getting the height of the terrain
            float height = biomes[i].terrainHeight * Noise.Get2DPerlin(new Vector2(pos.x, pos.z), 2.5f, biomes[i].terrainScale) * weight;

            if (height > 0)
            {
                sumOfHeights += height;
                count++;
            }
        }

        //Set biome to one with strongest weight
        BiomeAttributes biome = biomes[strongestBiomeIndex];

        //Getting AVG of heights and the final terrain height
        sumOfHeights /= count;
        int terrainHeight = Mathf.FloorToInt(sumOfHeights + groundHeight);


        /*Basic terrain conditions*/
        byte voxelValue = 0;

        if (yPos == terrainHeight)
        {
            voxelValue = biome.surfaceBlock;
        }
        else if (yPos < terrainHeight && yPos > terrainHeight - 4)
        {
            voxelValue = biome.subSurfaceBlock;
        }
        else if (yPos > terrainHeight)
        {
            return(0);
        }
        else
        {
            voxelValue = 2;
        }

        /* Second Pass for dirt and ores */
        if (voxelValue == 2)
        {
            foreach (Lode lode in biome.lodes)
            {
                if (yPos > lode.minHeight && yPos < lode.maxHeight)
                {
                    if (Noise.Get3DPerlin(pos, lode.noiseOffset, lode.scale, lode.threshold))
                    {
                        voxelValue = lode.blockID;
                    }
                }
            }
        }

        /* Third pass for trees */
        if (yPos == terrainHeight && biome.placeFlora)
        {
            if (Noise.Get2DPerlin(new Vector2(pos.x, pos.z), 2.5f, biome.floraZoneScale) > biome.floraThreshhold)
            {
                if (Noise.Get2DPerlin(new Vector2(pos.x, pos.z), 2.5f, biome.floraPlacementScale) > biome.floraPlacementThreshold)
                {
                    mods.Enqueue(Structure.GenerateFlora(biome.floraIndex, pos, biome.HeightMin, biome.HeightMax));
                }
            }
        }

        return(voxelValue);
    }
Example #26
0
        /// <summary>
        /// Génère un modèle 3D en forme de planète à partir de plusieurs bruits.
        /// </summary>
        /// <param name="aabb">Bounding box du morceau de planète généré.</param>
        /// <param name="gridLevelScale">Echelle du morceau de grille à générer. L'échelle est divisée par 2
        /// à chaque étage du quadtree</param>
        /// <param name="gridSize">Taille de la grille à générer.</param>
        /// <param name="highNoise">Bruit "high"</param>
        /// <param name="iBuffer">Index buffer en du mesh créé en sortie.</param>
        /// <param name="initialGridPos">Position du coin supérieur gauche de la grille à générer dans la grille initiale de range [0, 1]</param>
        /// <param name="lowNoise">Bruit "low"</param>
        /// <param name="repNoise">Bruit de répartition</param>
        /// <param name="vBuffer">Vertex buffer en du mesh créé en sortie.</param>
        /// <param name="chunkGeography">Informations de sortie concernant la géographie du morceau généré.</param>
        /// <param name="planetPosition">Position de la planète.</param>
        /// <param name="radius">Rayon de la planète.</param>
        /// <returns></returns>
        public static void GeneratePlanet(Vector3 planetPosition,
            float radius,
            int gridSize, 
            Vector2 initialGridPos,
            float gridLevelScale,
            Noise.NoiseBase lowNoise,
            Noise.NoiseBase highNoise,
            Noise.NoiseBase repNoise,
            out SlimDX.Direct3D11.Buffer vBuffer,
            out BoundingBox aabb,
            out ChunkAltitude geo)
        {
            // Geography
            geo = new ChunkAltitude();

            // Taille du buffer.
            int size = gridSize * gridSize ;
            const bool computeNormals = true;
            Vector3 min = new Vector3(float.MaxValue);
            Vector3 max = new Vector3(float.MinValue);

            // Création du vertex buffer contenant tous les vertex à dessiner.
            VWrapper[] vertexBuffer = new VWrapper[size];

            // Texture noise
            Noise.NoiseMapGenerator.NoiseParameters p = new Noise.NoiseMapGenerator.NoiseParameters()
            {
                Frequency = 128.0f,
                Lacunarity = 2.5f,
                NoiseEnd = new Vector2(initialGridPos.X + gridLevelScale, initialGridPos.Y + gridLevelScale),
                NoiseStart = new Vector2(initialGridPos.X, initialGridPos.Y),
                NoiseType = Noise.NoiseMapGenerator.NoiseParameters.RIDGED_ID,
                Persistence = 0.94f,
                Seed = 456464560
            };
            Noise.NoiseBase texNoise = p.CreateNoise();

            float theta, phi;
            Vector3 transformedPos;
            for (int y = 0; y < gridSize; y++)
            {
                for (int x = 0; x < gridSize; x++)
                {
                    // Cette section a pour but de calculer la normale par rapport au "sol" de la planète, pour cela
                    // Elle calcule les positions des verte
                    Vector2 pos2D = new Vector2(x / ((float)gridSize - 1),
                                    (y / ((float)gridSize - 1)));

                    // Transformation en sphère.
                    float noisePosX = initialGridPos.X + pos2D.X * gridLevelScale;
                    float noisePosY = initialGridPos.Y + pos2D.Y * gridLevelScale;
                    phi = (noisePosX) * (float)Math.PI * 2;
                    theta = (noisePosY) * (float)Math.PI;

                    // TODO : optimiser pour éviter les calculs redondants.
                    transformedPos = Util.SphericalCoords.ToCartesian(theta, phi, radius);//new Vector3(xSph, ySph, zSph);

                    // Création de la normale au sol.
                    Vector3 normal = Vector3.Normalize(transformedPos);

                    // Valeur du bruit
                    float noiseValue = Noise.NoiseMapGenerator.GetMultiNoiseValue(repNoise, highNoise, lowNoise,
                        transformedPos.X / radius, transformedPos.Y / radius, transformedPos.Z / radius);
                    float tNoiseValue = texNoise.GetValue(transformedPos.X / radius, transformedPos.Y / radius, transformedPos.Z / radius);

                    // Création de la position finale
                    Vector3 finalPos = transformedPos + normal * noiseValue;
                    Vector4 pos = new Vector4(finalPos, 1.0f);

                    // Informations de géométrie.
                    min = Util.MathHelper.Min(finalPos, min);
                    max = Util.MathHelper.Max(finalPos, max);
                    geo.MinAltitude = Math.Min(noiseValue, geo.MinAltitude);
                    geo.MaxAltitude = Math.Max(noiseValue, geo.MaxAltitude);

                    // Ajout des données dans le VBuffer.
                    int index = (x + y * gridSize);

                    vertexBuffer[index] = new VWrapper();
                    vertexBuffer[index].SphereNormal = normal;

                    // Position 3D du point avec displacement.
                    vertexBuffer[index].Vertex.Position = pos;
                    // Position 3D du point sans displacement.
                    vertexBuffer[index].Vertex.SpherePosition = new Vector4(transformedPos, 1.0f);
                    vertexBuffer[index].Vertex.SphereNormal = new Vector4(normal, 1.0f);
                    // Coordonnées de texture.
                    vertexBuffer[index].Vertex.Texture = new Vector2(noisePosX, noisePosY);
                    vertexBuffer[index].Vertex.Normal = new Vector4(0);
                    vertexBuffer[index].Vertex.Altitude = noiseValue;

                    // Valeurs additionnelles.
                    vertexBuffer[index].Vertex.TextureId = tNoiseValue;
                }

            }

            // Index buffer contenant l'ordre dans lequel dessiner les vertex. (sous forme de carrés).
            int iBufferSize = (gridSize - 1) * (gridSize - 1) * 6;
            int[] indexBuffer = GetIndexBufferCpu(gridSize);
            if (computeNormals)
            {
                //Thread.Sleep(1);
                for (int i = 0; i < indexBuffer.Length / 3; i++)
                {
                    Vector4 firstvec = vertexBuffer[indexBuffer[i * 3 + 1]].Vertex.Position - vertexBuffer[indexBuffer[i * 3]].Vertex.Position;
                    Vector4 secondvec = vertexBuffer[indexBuffer[i * 3]].Vertex.Position - vertexBuffer[indexBuffer[i * 3 + 2]].Vertex.Position;
                    Vector4 normal = new Vector4(Vector3.Cross(
                        new Vector3(firstvec.X, firstvec.Y, firstvec.Z),
                        new Vector3(secondvec.X, secondvec.Y, secondvec.Z)), 1.0f);
                    normal.Normalize();
                    vertexBuffer[indexBuffer[(i * 3)]].Vertex.Normal += normal;
                    vertexBuffer[indexBuffer[(i * 3 + 1)]].Vertex.Normal += normal;
                    vertexBuffer[indexBuffer[(i * 3 + 2)]].Vertex.Normal += normal;
                }
                for (int i = 0; i < vertexBuffer.Length; i++)
                {
                    var v = Util.MathHelper.ReduceXYZ(vertexBuffer[i].Vertex.Normal);
                    v.Normalize();
                    vertexBuffer[i].Vertex.Normal = new Vector4(v, 1.0f);
                    vertexBuffer[i].Vertex.SphereNormal = new Vector4(Util.MathHelper.ReduceXYZ(vertexBuffer[i].Vertex.Normal) - vertexBuffer[i].SphereNormal, 1.0f);

                }
            }

            // Création des buffers.
            DataStream vBuffStream = new DataStream(size * Vertex.Stride, true, true);
            for (int i = 0; i < size; i++)
                vBuffStream.Write<Vertex>(vertexBuffer[i].Vertex);
            vBuffStream.Position = 0;

            vBuffer = new SlimDX.Direct3D11.Buffer(Scene.GetGraphicsDevice(), vBuffStream, new BufferDescription()
            {
                BindFlags = BindFlags.VertexBuffer,
                CpuAccessFlags = CpuAccessFlags.None,
                OptionFlags = ResourceOptionFlags.None,
                SizeInBytes = (int)vBuffStream.Length,
                Usage = ResourceUsage.Default
            });

            vBuffStream.Dispose();

            aabb = new BoundingBox(min, max);
        }
        public void When_MOS2CommonSourceAmplifierNoise_Expect_Spice3f5Reference()
        {
            // Create circuit
            var ckt = new Circuit(
                new VoltageSource("V1", "in", "0", 0.0),
                new VoltageSource("V2", "vdd", "0", 5.0),
                new Resistor("R1", "vdd", "out", 10e3),
                new Resistor("R2", "out", "g", 10e3),
                new Capacitor("C1", "in", "g", 1e-6),
                CreateMOS2("M1", "out", "g", "0", "0",
                           "NFET", "VTO = -1.44 KP = 8.64E-6 NSUB = 1e17 TOX = 20e-9 KF = 0.5e-25")
                );

            ckt.Entities["V1"].SetParameter("acmag", 1.0);
            ckt.Entities["M1"].SetParameter("l", 6e-6);
            ckt.Entities["M1"].SetParameter("w", 1e-6);

            // Create simulation, exports and references
            var noise = new Noise("noise", "out", "V1", new DecadeSweep(10, 10e9, 10));

            Export <double>[] exports = { new InputNoiseDensityExport(noise), new OutputNoiseDensityExport(noise) };
            var references            = new double[2][];

            references[0] = new[]
            {
                2.362277630616173e-06, 1.379945267414784e-06, 8.473007758572772e-07, 5.483251555734933e-07,
                3.730472062832258e-07, 2.649962499739830e-07, 1.947939731585481e-07, 1.468616981231575e-07,
                1.127127241713318e-07, 8.755438258118984e-08, 6.855631329051349e-08, 5.395973684199731e-08,
                4.261291387932214e-08, 3.372393096425626e-08, 2.672536768434284e-08, 2.119738853640898e-08,
                1.682198426685170e-08, 1.335430849281782e-08, 1.060376070211410e-08, 8.420890083617284e-09,
                6.687960230375347e-09, 5.311939245547357e-09, 4.219174575568831e-09, 3.351284863236070e-09,
                2.661957766932026e-09, 2.114436968645719e-09, 1.679541365117180e-09, 1.334099339452888e-09,
                1.059708909993047e-09, 8.417548116877004e-10, 6.686287034417421e-10, 5.311102416204870e-10,
                4.218756922498825e-10, 3.351077295963854e-10, 2.661855491980500e-10, 2.114387464861675e-10,
                1.679518309568926e-10, 1.334089539422986e-10, 1.059705753459854e-10, 8.417549847903336e-11,
                6.686305453153985e-11, 5.311129198609113e-11, 4.218787896666749e-11, 3.351110370990360e-11,
                2.661889619930598e-11, 2.114422120523689e-11, 1.679553229713451e-11, 1.334124592122790e-11,
                1.059740872594686e-11, 8.417901372215624e-12, 6.686657144343612e-12, 5.311480973435567e-12,
                4.219139713410938e-12, 3.351462208743194e-12, 2.662241468212711e-12, 2.114773974082943e-12,
                1.679905085917544e-12, 1.334476449652446e-12, 1.060092730788699e-12, 8.421419957485428e-13,
                6.690175731282215e-13, 5.314999561210558e-13, 4.222658301605114e-13, 3.354980797147467e-13,
                2.665760056722277e-13, 2.118292562645285e-13, 1.683423674506338e-13, 1.337995038254496e-13,
                1.063611319397393e-13, 8.456605843605668e-14, 6.725361617419147e-14, 5.350185447355857e-14,
                4.257844187754605e-14, 3.390166683299062e-14, 2.700945942874924e-14, 2.153478448798461e-14,
                1.718609560659779e-14, 1.373180924408069e-14, 1.098797205551033e-14, 8.808464705142402e-15,
                7.077220478956046e-15, 5.702044308892841e-15, 4.609703049291635e-15, 3.742025544836112e-15,
                3.052804804411985e-15, 2.505337310335527e-15, 2.070468422196848e-15, 1.725039785945140e-15,
                1.450656067088105e-15, 1.232705332051313e-15, 1.059580909432678e-15
            };
            references[1] = new[]
            {
                2.970552105465777e-07, 2.053392001294538e-07, 1.425716401150457e-07, 1.005637052541777e-07,
                7.253421438447867e-08, 5.355847444717597e-08, 4.037521102279383e-08, 3.093870755193646e-08,
                2.399259594639712e-08, 1.876085041593681e-08, 1.475173003376309e-08, 1.164174697973875e-08,
                9.209128460130984e-09, 7.295852862170559e-09, 5.785653492254035e-09, 4.590866976751766e-09,
                3.644227374777685e-09, 2.893495350636724e-09, 2.297774776401085e-09, 1.824881474232857e-09,
                1.449401554896117e-09, 1.151223737306888e-09, 9.144110142143362e-10, 7.263231967747751e-10,
                5.769293633775424e-10, 4.582664502662651e-10, 3.640115671591474e-10, 2.891434647260522e-10,
                2.296742247661058e-10, 1.824364329323833e-10, 1.449142737768106e-10, 1.151094398350513e-10,
                9.143465704637279e-11, 7.262912784315901e-11, 5.769137465933203e-11, 4.582590036912043e-11,
                3.640082154126390e-11, 2.891421652629465e-11, 2.296739538836536e-11, 1.824366775621906e-11,
                1.449147767750264e-11, 1.151100723242943e-11, 9.143535443489147e-12, 7.262985775837507e-12,
                5.769212087651685e-12, 4.582665475664515e-12, 3.640158002365927e-12, 2.891497706098719e-12,
                2.296815695164321e-12, 1.824442983501082e-12, 1.449224001466344e-12, 1.151176969908153e-12,
                9.144297975040658e-13, 7.263748339915787e-13, 5.769974668031978e-13, 4.583428064215170e-13,
                3.640920595011466e-13, 2.892260300796565e-13, 2.297578290890759e-13, 1.825205579743038e-13,
                1.449986597966671e-13, 1.151939566537973e-13, 9.151923941987867e-14, 7.271374307188275e-14,
                5.777600635467486e-14, 4.591054031732387e-14, 3.648546562569634e-14, 2.899886268375259e-14,
                2.305204258479738e-14, 1.832831547337173e-14, 1.457612565563390e-14, 1.159565534135988e-14,
                9.228183617974503e-15, 7.347633983178169e-15, 5.853860311459011e-15, 4.667313707724732e-15,
                3.724806238562389e-15, 2.976145944368217e-15, 2.381463934472801e-15, 1.909091223330287e-15,
                1.533872241556531e-15, 1.235825210129142e-15, 9.990780377906112e-16, 8.110230743109810e-16,
                6.616457071390669e-16, 5.429910467656397e-16, 4.487402998494061e-16, 3.738742704299892e-16,
                3.144060694404477e-16, 2.671687983261964e-16, 2.296469001488209e-16
            };

            // Run test
            AnalyzeNoise(noise, ckt, exports, references);
        }
Example #28
0
    void ResetTexture( )
    {
        if (_texture.width != resolution)
        {
            _texture.Resize(resolution, resolution);
        }

        Noise noise = null;

        switch (noiseType)
        {
        case NoiseType.WhiteNoise:
            noise = new NoiseWhite( );
            break;

        case NoiseType.Value:
            noise = new NoiseBasic( );
            break;

        case NoiseType.Gradient:
            noise = new NoiseGradient( );
            break;

        case NoiseType.Simplex:
            noise = new NoiseSimplex( );
            break;

        case NoiseType.Cellular:
            noise = new NoiseCellular( );
            (noise as NoiseCellular).SetNoiseLookup(new NoiseBasic( ));
            break;
        }

        noise.SetSeed(seed);

        noise.SetFractalGain(gain);
        noise.SetFractalLacunarity(lacunarity);

        noise.SetFractalType(fractalType);
        noise.SetInterpolationType(interpolationType);

        noise.SetFrequency(frequency);
        noise.SetFractalOctaves(octaves);

        float z = Time.time * 0.1f;

        for (int iy = 0; iy < resolution; ++iy)
        {
            float y = (( float )iy) / (( float )resolution);

            for (int ix = 0; ix < resolution; ++ix)
            {
                float x = (( float )ix) / (( float )resolution);

                float c;
                if (dimensions == 2)
                {
                    c = noise.GetNoise(x, y);
                }
                else if (dimensions == 3)
                {
                    c = noise.GetNoise(x, y, z);
                }
                else
                {
                    c = noise.GetNoise(x, y, z, noise.GetNoise(x, y, z));
                }

                _texture.SetPixel(ix, iy, new Color(c, c, c));
            }
        }

        _texture.Apply( );
    }
        /// <summary>
        /// Lance le calcul de génération d'une grille de planète.
        /// </summary>
        /// <param name="planetPosition"></param>
        /// <param name="planetRadius"></param>
        /// <param name="gridSize"></param>
        /// <param name="noiseLow"></param>
        /// <param name="noiseHigh"></param>
        /// <param name="repartitionNoise"></param>
        /// <param name="world"></param>
        /// <param name="initialGridPos"></param>
        /// <param name="gridLevelScale"></param>
        public void RunCalculation(Vector3 planetPosition, float planetRadius, int gridSize, Noise.NoiseMapGenerator.NoiseParameters noiseLow, Noise.NoiseMapGenerator.NoiseParameters noiseHigh, 
            Noise.NoiseMapGenerator.NoiseParameters repartitionNoise, Matrix world, Vector2 initialGridPos, float gridLevelScale)
        {
            if (m_isComputing)
                throw new NotImplementedException();

            m_planetPosition = planetPosition;
            m_planetRadius = planetRadius;
            m_gridSize = gridSize;

            IsRessourceReady = false;
            System.Threading.Thread.CurrentThread.Priority = ThreadPriority.Highest;
            Thread thread = new Thread(() =>
            {
                m_isComputing = true;
                System.Threading.Thread.CurrentThread.Priority = ThreadPriority.Normal;
                var low = noiseLow.CreateNoise();
                var high = noiseHigh.CreateNoise();
                var rep = repartitionNoise.CreateNoise();
                BoundingBox aabb;
                Generation.ChunkAltitude altitude;
                Buffer vertexBuffer;
                Generation.ModelGenerator.GeneratePlanet(planetPosition,
                    planetRadius,
                    gridSize,
                    initialGridPos,
                    gridLevelScale,
                    low, high, rep, // bruits
                    out vertexBuffer,
                    out aabb,
                    out altitude);

                // Si on abort la tâche.
                Ressource = new Rsc()
                {
                    VertexBuffer = vertexBuffer,
                    Box = aabb,
                    Altitude = altitude
                };
                IsRessourceReady = true;
                m_isComputing = false;
                m_currentThread = null;

                if(m_isAborted)
                {
                    Ressource.Dispose();
                    IsRessourceReady = false;
                }
            });
            m_currentThread = thread;
            Scene.Instance.ThreadPool.AddThread(thread);
        }
Example #30
0
    void Start()
    {
        //Single-channel Turbulence3d heightmap (4x Fractal)
        terrainNoise = new Noise();
        terrainNoise.addChannel(new Channel("Height",Algorithm.Turbulence3d,150.0f,NoiseStyle.Linear,0.0f,1.0f,Edge.Smooth).setFractal(4,2.0f,0.5f));

        //Three Simplex channels for Red, Green and Blueingle-channel Turbulence3d heightmap (4x Fractal)
        colourNoise = new Noise();
        colourNoise.addChannel(new Channel("Red",Algorithm.Simplex2d,250.0f,NoiseStyle.Linear,0.0f,1.0f,Edge.Smooth));
        colourNoise.addChannel(new Channel("Green",Algorithm.Simplex2d,250.0f,NoiseStyle.Linear,0.0f,1.0f,Edge.Smooth));
        colourNoise.addChannel(new Channel("Blue",Algorithm.Simplex2d,250.0f,NoiseStyle.Linear,0.0f,1.0f,Edge.Smooth));

        //Single-channel Marble noise
        marbleNoise = new Noise();
        marbleNoise.addChannel(new Channel("Color",Algorithm.Marble3d,50.0f,NoiseStyle.Linear,0.0f,1.0f,Edge.Smooth));

        //Single-channel Wood noise
        woodNoise = new Noise();
        woodNoise.addChannel(new Channel("Color",Algorithm.Wood3d,250.0f,NoiseStyle.Linear,0.0f,1.0f,Edge.Smooth));

        //Single-channel Perlin noise
        perlinNoise = new Noise();
        perlinNoise.addChannel(new Channel("Color",Algorithm.Perlin3d,75.0f,NoiseStyle.Second,0.0f,1.0f,Edge.Smooth).setFractal(4,2.0f,0.5f));

        //Single-channel Turbulence3d noise
        turbulenceNoise = new Noise();
        turbulenceNoise.addChannel(new Channel("Color",Algorithm.Turbulence3d,75.0f,NoiseStyle.Linear,0.0f,1.0f,Edge.Smooth));

        width = 700;
        height = 700;
        Texture2D texture1 = new Texture2D(width,height, TextureFormat.ARGB32, false);
        Texture2D texture2 = new Texture2D(width,height, TextureFormat.ARGB32, false);
        Texture2D texture3 = new Texture2D(width,height, TextureFormat.ARGB32, false);
        Texture2D texture4 = new Texture2D(width,height, TextureFormat.ARGB32, false);
        Texture2D texture5 = new Texture2D(width,height, TextureFormat.ARGB32, false);
        Texture2D texture6 = new Texture2D(width,height, TextureFormat.ARGB32, false);

        for(int x=0;x<width;x++)
        {for(int y=0;y<height;y++)
        {
                Vector3 vector = new Vector3((float)x,0.0f,(float)y);

                //Single-channel Turbulence3d heightmap (4x Fractal)
                float sample = terrainNoise.getNoise(vector,"Height");
                texture1.SetPixel(x,y,new Color(sample,sample,sample,1.0f));

                //Three Simplex channels for Red, Green and Blueingle-channel Turbulence3d heightmap (4x Fractal)
                Color color2 = new Color();
                color2.r = colourNoise.getNoise(vector,"Red");
                color2.g = colourNoise.getNoise(vector,"Green");
                color2.b = colourNoise.getNoise(vector,"Blue");
                texture2.SetPixel(x,y,color2);

                //Single-channel Marble noise
                Color color3 = new Color();
                sample = marbleNoise.getNoise(vector,"Color");
                color3.r = 0.96f*sample;
                color3.g = 0.87f*sample;
                color3.b = 0.32f*sample;
                texture3.SetPixel(x,y,color3);

                //Single-channel Wood noise
                sample = woodNoise.getNoise(vector,"Color");
                texture4.SetPixel(x,y,new Color(sample,sample,sample,1.0f));

                //Single-channel Perlin noise
                sample = perlinNoise.getNoise(vector,"Color");
                texture5.SetPixel(x,y,new Color(sample,sample,sample,1.0f));

                //Single-channel Turbulence3d noise
                sample = turbulenceNoise.getNoise(vector,"Color");
                texture6.SetPixel(x,y,new Color(sample,sample,sample,1.0f));

        }}
        texture1.Apply();
        material.mainTexture = texture1;
        texture2.Apply();
        material2.mainTexture = texture2;
        texture3.Apply();
        material3.mainTexture = texture3;
        texture4.Apply();
        material4.mainTexture = texture4;
        texture5.Apply();
        material5.mainTexture = texture5;
        texture6.Apply();
        material6.mainTexture = texture6;
    }
Example #31
0
 private static extern float GeneratorNoise200(Matrix matrix, Noise noise, StopToken stop,
                                               int type, float intensity, float size, float detail, float turbulence, float offsetX, float offsetZ,
                                               float worldRectPosX, float worldRectPosZ, float worldRectSizeX, float worldRectSizeZ);
Example #32
0
    private void Update()
    {
        float[,] noiseMap = Noise.GenerateNoise(mapValues.width, mapValues.height, mapValues.seed, mapValues.offsetX, mapValues.offsetY, mapValues.scale, mapValues.octaves, mapValues.persistance, mapValues.lacunarity);

        image.texture = GenerateTexture(noiseMap);
    }
Example #33
0
	void Start() {
		terrain = GetComponent<Terrain>();
		noise = GetComponent<Noise>();
	}
Example #34
0
        public void Draw(SpriteBatch spriteBatch, GUICustomComponent mapContainer)
        {
            Rectangle rect = mapContainer.Rect;

            Vector2 viewSize   = new Vector2(rect.Width / zoom, rect.Height / zoom);
            float   edgeBuffer = size * (BackgroundScale - 1.0f) / 2;

            drawOffset.X = MathHelper.Clamp(drawOffset.X, -size - edgeBuffer + viewSize.X / 2.0f, edgeBuffer - viewSize.X / 2.0f);
            drawOffset.Y = MathHelper.Clamp(drawOffset.Y, -size - edgeBuffer + viewSize.Y / 2.0f, edgeBuffer - viewSize.Y / 2.0f);

            drawOffsetNoise = new Vector2(
                (float)PerlinNoise.CalculatePerlin(Timing.TotalTime * 0.1f % 255, Timing.TotalTime * 0.1f % 255, 0) - 0.5f,
                (float)PerlinNoise.CalculatePerlin(Timing.TotalTime * 0.2f % 255, Timing.TotalTime * 0.2f % 255, 0.5f) - 0.5f) * 10.0f;

            Vector2 viewOffset = drawOffset + drawOffsetNoise;

            Vector2 rectCenter = new Vector2(rect.Center.X, rect.Center.Y) + CenterOffset;

            Rectangle prevScissorRect = GameMain.Instance.GraphicsDevice.ScissorRectangle;

            spriteBatch.End();
            spriteBatch.GraphicsDevice.ScissorRectangle = Rectangle.Intersect(prevScissorRect, rect);
            spriteBatch.Begin(SpriteSortMode.Deferred, samplerState: GUI.SamplerState, rasterizerState: GameMain.ScissorTestEnable);

            for (int x = 0; x < mapTiles.GetLength(0); x++)
            {
                for (int y = 0; y < mapTiles.GetLength(1); y++)
                {
                    Vector2 mapPos = new Vector2(
                        x * generationParams.TileSpriteSpacing.X + ((y % 2 == 0) ? 0.0f : generationParams.TileSpriteSpacing.X * 0.5f),
                        y * generationParams.TileSpriteSpacing.Y);

                    mapPos.X -= size / 2 * (BackgroundScale - 1.0f);
                    mapPos.Y -= size / 2 * (BackgroundScale - 1.0f);

                    Vector2 scale = new Vector2(
                        generationParams.TileSpriteSize.X / mapTiles[x, y].Sprite.size.X,
                        generationParams.TileSpriteSize.Y / mapTiles[x, y].Sprite.size.Y);
                    mapTiles[x, y].Sprite.Draw(spriteBatch, rectCenter + (mapPos + viewOffset) * zoom, Color.White,
                                               origin: new Vector2(256.0f, 256.0f), rotate: 0, scale: scale * zoom, spriteEffect: mapTiles[x, y].SpriteEffect);
                }
            }
#if DEBUG
            if (generationParams.ShowNoiseMap)
            {
                GUI.DrawRectangle(spriteBatch, rectCenter + (borders.Location.ToVector2() + viewOffset) * zoom, borders.Size.ToVector2() * zoom, Color.White, true);
            }
#endif
            Vector2 topLeft = rectCenter + viewOffset * zoom;
            topLeft.X = (int)topLeft.X;
            topLeft.Y = (int)topLeft.Y;

            Vector2 bottomRight = rectCenter + (viewOffset + new Vector2(size, size)) * zoom;
            bottomRight.X = (int)bottomRight.X;
            bottomRight.Y = (int)bottomRight.Y;

            spriteBatch.Draw(noiseTexture,
                             destinationRectangle: new Rectangle((int)topLeft.X, (int)topLeft.Y, (int)(bottomRight.X - topLeft.X), (int)(bottomRight.Y - topLeft.Y)),
                             sourceRectangle: null,
                             color: Color.White);

            if (topLeft.X > rect.X)
            {
                GUI.DrawRectangle(spriteBatch, new Rectangle(rect.X, rect.Y, (int)(topLeft.X - rect.X), rect.Height), Color.Black * 0.8f, true);
            }
            if (topLeft.Y > rect.Y)
            {
                GUI.DrawRectangle(spriteBatch, new Rectangle((int)topLeft.X, rect.Y, (int)(bottomRight.X - topLeft.X), (int)(topLeft.Y - rect.Y)), Color.Black * 0.8f, true);
            }
            if (bottomRight.X < rect.Right)
            {
                GUI.DrawRectangle(spriteBatch, new Rectangle((int)bottomRight.X, rect.Y, (int)(rect.Right - bottomRight.X), rect.Height), Color.Black * 0.8f, true);
            }
            if (bottomRight.Y < rect.Bottom)
            {
                GUI.DrawRectangle(spriteBatch, new Rectangle((int)topLeft.X, (int)bottomRight.Y, (int)(bottomRight.X - topLeft.X), (int)(rect.Bottom - bottomRight.Y)), Color.Black * 0.8f, true);
            }

            var   sourceRect    = rect;
            float rawNoiseScale = 1.0f + Noise[(int)(Timing.TotalTime * 100 % Noise.GetLength(0) - 1), (int)(Timing.TotalTime * 100 % Noise.GetLength(1) - 1)];
            cameraNoiseStrength = Noise[(int)(Timing.TotalTime * 10 % Noise.GetLength(0) - 1), (int)(Timing.TotalTime * 10 % Noise.GetLength(1) - 1)];

            rawNoiseSprite.DrawTiled(spriteBatch, rect.Location.ToVector2(), rect.Size.ToVector2(),
                                     startOffset: new Point(Rand.Range(0, rawNoiseSprite.SourceRect.Width), Rand.Range(0, rawNoiseSprite.SourceRect.Height)),
                                     color: Color.White * cameraNoiseStrength * 0.5f,
                                     textureScale: Vector2.One * rawNoiseScale);

            rawNoiseSprite.DrawTiled(spriteBatch, rect.Location.ToVector2(), rect.Size.ToVector2(),
                                     startOffset: new Point(Rand.Range(0, rawNoiseSprite.SourceRect.Width), Rand.Range(0, rawNoiseSprite.SourceRect.Height)),
                                     color: new Color(20, 20, 20, 100),
                                     textureScale: Vector2.One * rawNoiseScale * 2);

            if (generationParams.ShowLocations)
            {
                foreach (LocationConnection connection in connections)
                {
                    Color connectionColor;
                    if (GameMain.DebugDraw)
                    {
                        float sizeFactor = MathUtils.InverseLerp(
                            MapGenerationParams.Instance.SmallLevelConnectionLength,
                            MapGenerationParams.Instance.LargeLevelConnectionLength,
                            connection.Length);

                        connectionColor = ToolBox.GradientLerp(sizeFactor, Color.LightGreen, Color.Orange, Color.Red);
                    }
                    else
                    {
                        connectionColor = ToolBox.GradientLerp(connection.Difficulty / 100.0f,
                                                               MapGenerationParams.Instance.LowDifficultyColor,
                                                               MapGenerationParams.Instance.MediumDifficultyColor,
                                                               MapGenerationParams.Instance.HighDifficultyColor);
                    }

                    int width = (int)(3 * zoom);

                    if (SelectedLocation != CurrentLocation &&
                        (connection.Locations.Contains(SelectedLocation) && connection.Locations.Contains(CurrentLocation)))
                    {
                        connectionColor = Color.Gold;
                        width          *= 2;
                    }
                    else if (highlightedLocation != CurrentLocation &&
                             (connection.Locations.Contains(highlightedLocation) && connection.Locations.Contains(CurrentLocation)))
                    {
                        connectionColor = Color.Lerp(connectionColor, Color.White, 0.5f);
                        width          *= 2;
                    }
                    else if (!connection.Passed)
                    {
                        //crackColor *= 0.5f;
                    }

                    for (int i = 0; i < connection.CrackSegments.Count; i++)
                    {
                        var segment = connection.CrackSegments[i];

                        Vector2 start = rectCenter + (segment[0] + viewOffset) * zoom;
                        Vector2 end   = rectCenter + (segment[1] + viewOffset) * zoom;

                        if (!rect.Contains(start) && !rect.Contains(end))
                        {
                            continue;
                        }
                        else
                        {
                            if (MathUtils.GetLineRectangleIntersection(start, end, new Rectangle(rect.X, rect.Y + rect.Height, rect.Width, rect.Height), out Vector2 intersection))
                            {
                                if (!rect.Contains(start))
                                {
                                    start = intersection;
                                }
                                else
                                {
                                    end = intersection;
                                }
                            }
                        }

                        float distFromPlayer = Vector2.Distance(CurrentLocation.MapPosition, (segment[0] + segment[1]) / 2.0f);
                        float dist           = Vector2.Distance(start, end);

                        float a = GameMain.DebugDraw ? 1.0f : (200.0f - distFromPlayer) / 200.0f;
                        spriteBatch.Draw(generationParams.ConnectionSprite.Texture,
                                         new Rectangle((int)start.X, (int)start.Y, (int)(dist - 1 * zoom), width),
                                         null, connectionColor * MathHelper.Clamp(a, 0.1f, 0.5f), MathUtils.VectorToAngle(end - start),
                                         new Vector2(0, 16), SpriteEffects.None, 0.01f);
                    }

                    if (GameMain.DebugDraw && zoom > 1.0f && generationParams.ShowLevelTypeNames)
                    {
                        Vector2 center = rectCenter + (connection.CenterPos + viewOffset) * zoom;
                        if (rect.Contains(center))
                        {
                            GUI.DrawString(spriteBatch, center, connection.Biome.Name + " (" + connection.Difficulty + ")", Color.White);
                        }
                    }
                }

                rect.Inflate(8, 8);
                GUI.DrawRectangle(spriteBatch, rect, Color.Black, false, 0.0f, 8);
                GUI.DrawRectangle(spriteBatch, rect, Color.LightGray);

                for (int i = 0; i < Locations.Count; i++)
                {
                    Location location = Locations[i];
                    Vector2  pos      = rectCenter + (location.MapPosition + viewOffset) * zoom;

                    Rectangle drawRect = location.Type.Sprite.SourceRect;
                    drawRect.X = (int)pos.X - drawRect.Width / 2;
                    drawRect.Y = (int)pos.Y - drawRect.Width / 2;

                    if (!rect.Intersects(drawRect))
                    {
                        continue;
                    }

                    Color color = location.Type.SpriteColor;
                    if (location.Connections.Find(c => c.Locations.Contains(CurrentLocation)) == null)
                    {
                        color *= 0.5f;
                    }

                    float iconScale = location == CurrentLocation ? 1.2f : 1.0f;
                    if (location == highlightedLocation)
                    {
                        iconScale *= 1.1f;
                        color      = Color.Lerp(color, Color.White, 0.5f);
                    }

                    float distFromPlayer = Vector2.Distance(CurrentLocation.MapPosition, location.MapPosition);
                    color *= MathHelper.Clamp((1000.0f - distFromPlayer) / 500.0f, 0.1f, 1.0f);

                    location.Type.Sprite.Draw(spriteBatch, pos, color,
                                              scale: MapGenerationParams.Instance.LocationIconSize / location.Type.Sprite.size.X * iconScale * zoom);
                    MapGenerationParams.Instance.LocationIndicator.Draw(spriteBatch, pos, color,
                                                                        scale: MapGenerationParams.Instance.LocationIconSize / MapGenerationParams.Instance.LocationIndicator.size.X * iconScale * zoom * 1.4f);
                }

                //PLACEHOLDER until the stuff at the center of the map is implemented
                float   centerIconSize = 50.0f;
                Vector2 centerPos      = rectCenter + (new Vector2(size / 2) + viewOffset) * zoom;
                bool    mouseOn        = Vector2.Distance(PlayerInput.MousePosition, centerPos) < centerIconSize * zoom;

                var   centerLocationType = LocationType.List.Last();
                Color centerColor        = centerLocationType.SpriteColor * (mouseOn ? 1.0f : 0.6f);
                centerLocationType.Sprite.Draw(spriteBatch, centerPos, centerColor,
                                               scale: centerIconSize / centerLocationType.Sprite.size.X * zoom);
                MapGenerationParams.Instance.LocationIndicator.Draw(spriteBatch, centerPos, centerColor,
                                                                    scale: centerIconSize / MapGenerationParams.Instance.LocationIndicator.size.X * zoom * 1.2f);

                if (mouseOn && PlayerInput.LeftButtonClicked() && !messageBoxOpen)
                {
                    if (TextManager.ContainsTag("centerarealockedheader") && TextManager.ContainsTag("centerarealockedtext"))
                    {
                        var messageBox = new GUIMessageBox(
                            TextManager.Get("centerarealockedheader"),
                            TextManager.Get("centerarealockedtext"));
                        messageBoxOpen = true;
                        CoroutineManager.StartCoroutine(WaitForMessageBoxClosed(messageBox));
                    }
                    else
                    {
                        //if the message cannot be shown in the selected language,
                        //show the campaign roadmap (which mentions the center location not being reachable)
                        var messageBox = new GUIMessageBox(TextManager.Get("CampaignRoadMapTitle"), TextManager.Get("CampaignRoadMapText"));
                        messageBoxOpen = true;
                        CoroutineManager.StartCoroutine(WaitForMessageBoxClosed(messageBox));
                    }
                }
            }

            DrawDecorativeHUD(spriteBatch, rect);

            for (int i = 0; i < 2; i++)
            {
                Location location = (i == 0) ? highlightedLocation : CurrentLocation;
                if (location == null)
                {
                    continue;
                }

                Vector2 pos = rectCenter + (location.MapPosition + viewOffset) * zoom;
                pos.X += 25 * zoom;
                pos.Y -= 5 * zoom;
                Vector2 size = GUI.LargeFont.MeasureString(location.Name);
                GUI.Style.GetComponentStyle("OuterGlow").Sprites[GUIComponent.ComponentState.None][0].Draw(
                    spriteBatch, new Rectangle((int)pos.X - 30, (int)pos.Y, (int)size.X + 60, (int)(size.Y + 25 * GUI.Scale)), Color.Black * hudOpenState * 0.7f);
                GUI.DrawString(spriteBatch, pos,
                               location.Name, Color.White * hudOpenState * 1.5f, font: GUI.LargeFont);
                GUI.DrawString(spriteBatch, pos + Vector2.UnitY * 25 * GUI.Scale,
                               location.Type.Name, Color.White * hudOpenState * 1.5f);
            }

            spriteBatch.End();
            GameMain.Instance.GraphicsDevice.ScissorRectangle = prevScissorRect;
            spriteBatch.Begin(SpriteSortMode.Deferred, samplerState: GUI.SamplerState, rasterizerState: GameMain.ScissorTestEnable);
        }
Example #35
0
    private void SharedConstructor(int width, int height)
    {
        skyboxes = Utility.GetSkyboxes();
        planetNormals = Utility.GetPlanetNormals();

        planetInfo = new PlanetInfo();
        rand = new System.Random();
        floatColors = new float[width * height];
        noise = new Noise();
        this.width = width;
        this.height = height;
    }
Example #36
0
 public RigidNoiseFilter(NoiseSettings.RigidNoiseSettings noiseSettings)
 {
     this.noise         = new Noise();
     this.noiseSettings = noiseSettings;
 }
Example #37
0
 public TextureCollection(string name)
 {
     textureName = name;
     noiseGen = new Noise();
 }
    protected override IEnumerator Generate(WorldManager worldManager)
    {
        var size = (int)worldManager.worldSize;

        WorldData wd = new WorldData
        {
            tilePositions = new Vector3Int[size * size],
            tiles         = new TileBase[size * size],
            tileTypeMap   = new TileType[size, size]
        };

        falloffMap = FalloffGenerator.GenerateFalloffMap(size, size);

        yield return(null);

        UIManager.UpdateLoadScreenText("Generating terrain.");
        //Perlin noise arrays
        var terrainMap = Noise.GenerateNoiseMap(size, seed, terrainData.noiseScale, terrainData.octaves, terrainData.persistance, terrainData.lacunarity, terrainData.offset);

        yield return(null);

        UIManager.UpdateLoadScreenText("Generating deserts and tundras.");
        var temperatureMap = Noise.GenerateNoiseMap(size, seed, temperatureData.noiseScale, temperatureData.octaves, temperatureData.persistance, temperatureData.lacunarity, temperatureData.offset);

        yield return(null);

        UIManager.UpdateLoadScreenText("Generating woodlands and savanas.");
        var moistureMap = Noise.GenerateNoiseMap(size, seed, moistureData.noiseScale, moistureData.octaves, moistureData.persistance, moistureData.lacunarity, moistureData.offset);

        yield return(null);

        mapDimension = (size - (size % mapRatio)) / mapRatio;

        //color array to convert to texture2D
        Color[] colourMap = new Color[mapDimension * mapDimension];

        UIManager.UpdateLoadScreenText("Coloring in the blank spots.");

        for (int y = 0; y < size; y++)
        {
            for (int x = 0; x < size; x++)
            {
                if (useFalloff)
                {
                    //Subtracts falloff from height map
                    terrainMap[x, y] = Mathf.Clamp(terrainMap[x, y] - falloffMap[x, y], 0, 1);
                }

                //populates tile position array
                wd.tilePositions[y * size + x] = new Vector3Int(x, y, 0);

                //Get values of a tile
                float currentHeight   = terrainMap[x, y];
                float currentTemp     = temperatureMap[x, y];
                float currentMoisture = moistureMap[x, y];

                //Assign color and tile based on values
                for (int i = 0; i < regions.Count; i++)
                {
                    if (currentHeight <= regions[i].height)
                    {
                        if (regions[i].allowBiomes)
                        {
                            var biome = temperature[(int)Mathf.Round(currentTemp * (temperature.Count - 1))].moisture[(int)Mathf.Round(currentMoisture * (temperature.Count - 1))];

                            if (y % mapRatio == 0 && x % mapRatio == 0)
                            {
                                colourMap[(y / mapRatio) * mapDimension + (x / mapRatio)] = biome.colour;
                            }

                            wd.tiles[y * size + x] = biome.tile;
                            wd.tileTypeMap[x, y]   = biome;
                        }
                        else
                        {
                            if (y % mapRatio == 0 && x % mapRatio == 0)
                            {
                                colourMap[(y / mapRatio) * mapDimension + (x / mapRatio)] = regions[i].colour;
                            }

                            wd.tiles[y * size + x] = regions[i].tile;
                            wd.tileTypeMap[x, y]   = regions[i];
                        }

                        break;
                    }
                }
            }
        }

        //Handles generating and displaying a type of texture
        switch (drawMode)
        {
        default:
        case DrawMode.ColourMap:
            DisplayMap(colourMap, mapDimension);
            break;

        case DrawMode.FalloffMap:
            DisplayMap(size);
            break;

        case DrawMode.None:
            break;

        case DrawMode.NoiseMap:
            DisplayMap(terrainMap);
            break;

        case DrawMode.TemperatureMap:
            DisplayMap(temperatureMap);
            break;

        case DrawMode.MoistureMap:
            DisplayMap(moistureMap);
            break;
        }
        yield return(null);

        UIManager.UpdateLoadScreenText("Drawing world maps...");

        //Sets the world map texture
        wd.worldMap = colourMap;
        yield return(null);

        //sets the height map for later use
        wd.heightMap = terrainMap;

        worldManager.worldData = wd; //returns generated world data

        //Draw whole map
        ObjectStore.instance.mapDisplay.DrawWorldMap(wd);

        //const int chunkSize = 1024;

        ////Draw map in chunks
        //for (int c = 0; c < wd.tilePositions.Length; c+=chunkSize)
        //{
        //    UIManager.UpdateLoadScreenText($"Sculpting chunk {c/chunkSize}.");
        //    TilemapData chunk = GetChunk(c);
        //    ObjectStore.instance.mapDisplay.DrawTerrain(chunk);
        //    yield return null;
        //}

        var middle = (int)worldManager.worldSize / 2;

        worldManager.worldData.SetWorldMapIcon(middle, middle, mapIcon);

        FinishGenerating(worldManager);

        // FUNCIONS
        //TilemapData GetChunk(int startPoint)
        //{
        //    List<Vector3Int> positions = new List<Vector3Int>();
        //    List<TileBase> tiles = new List<TileBase>();

        //    for (int i = 0; i < startPoint + chunkSize; i++)
        //    {
        //        if (i < wd.tilePositions.Length)
        //        {
        //            positions.Add(wd.tilePositions[i]);
        //            tiles.Add(wd.tiles[i]);
        //        }
        //    }

        //    return new TilemapData(positions.ToArray(), tiles.ToArray());
        //}
    }
        Map GenerateMap()
        {
            Map map = new Map(null, genParams.MapWidth, genParams.MapLength, genParams.MapHeight, true);

            theme = genParams.Theme;

            // scale features vertically based on map height
            double verticalScale = (genParams.MapHeight / 96.0) / 2 + 0.5;

            maxHeightScaled    = (int)Math.Round(genParams.MaxHeight * verticalScale);
            maxDepthScaled     = (int)Math.Round(genParams.MaxDepth * verticalScale);
            snowAltitudeScaled = (int)Math.Round(genParams.SnowAltitude * verticalScale);

            // Match water coverage
            float desiredWaterLevel = .5f;

            if (genParams.MatchWaterCoverage)
            {
                ReportRelativeProgress(2, "Heightmap Processing: Matching water coverage");
                // find a number between 0 and 1 ("desiredWaterLevel") for the heightmap such that
                // the fraction of heightmap coordinates ("blocks") that are below this threshold ("underwater")
                // match the specified WaterCoverage
                desiredWaterLevel = Noise.FindThreshold(heightmap, genParams.WaterCoverage);
            }


            // Calculate above/below water multipliers
            float aboveWaterMultiplier = 0;

            if (desiredWaterLevel < 1)
            {
                aboveWaterMultiplier = (maxHeightScaled / (1 - desiredWaterLevel));
            }


            // Apply power functions to above/below water parts of the heightmap
            if (Math.Abs(genParams.BelowFuncExponent - 1) > float.Epsilon ||
                Math.Abs(genParams.AboveFuncExponent - 1) > float.Epsilon)
            {
                ReportRelativeProgress(5, "Heightmap Processing: Adjusting slope");
                for (int x = heightmap.GetLength(0) - 1; x >= 0; x--)
                {
                    for (int y = heightmap.GetLength(1) - 1; y >= 0; y--)
                    {
                        if (heightmap[x, y] < desiredWaterLevel)
                        {
                            float normalizedDepth = 1 - heightmap[x, y] / desiredWaterLevel;
                            heightmap[x, y] = desiredWaterLevel -
                                              (float)Math.Pow(normalizedDepth, genParams.BelowFuncExponent) *
                                              desiredWaterLevel;
                        }
                        else
                        {
                            float normalizedHeight = (heightmap[x, y] - desiredWaterLevel) / (1 - desiredWaterLevel);
                            heightmap[x, y] = desiredWaterLevel +
                                              (float)Math.Pow(normalizedHeight, genParams.AboveFuncExponent) *
                                              (1 - desiredWaterLevel);
                        }
                    }
                }
            }

            // Calculate the slope
            if (genParams.CliffSmoothing)
            {
                ReportRelativeProgress(2, "Heightmap Processing: Smoothing");
                slopemap = Noise.CalculateSlope(Noise.GaussianBlur5X5(heightmap));
            }
            else
            {
                slopemap = Noise.CalculateSlope(heightmap);
            }

            // Randomize max height/depth
            float[,] altmap = null;
            if (genParams.MaxHeightVariation != 0 || genParams.MaxDepthVariation != 0)
            {
                ReportRelativeProgress(5, "Heightmap Processing: Randomizing");
                altmap = new float[map.Width, map.Length];
                int blendmapDetailSize = (int)Math.Log(Math.Max(genParams.MapWidth, genParams.MapLength), 2) - 2;
                new Noise(rand.Next(), NoiseInterpolationMode.Cosine)
                .PerlinNoise(altmap, Math.Min(blendmapDetailSize, 3), blendmapDetailSize,
                             0.5f, 0, 0);
                Noise.Normalize(altmap, -1, 1);
            }

            int snowStartThreshold = snowAltitudeScaled - genParams.SnowTransition;
            int snowThreshold      = snowAltitudeScaled;

            ReportRelativeProgress(10, "Filling");
            if (theme.AirBlock != Block.Air)
            {
                map.Blocks.MemSet((byte)theme.AirBlock);
            }
            for (int x = heightmap.GetLength(0) - 1; x >= 0; x--)
            {
                for (int y = heightmap.GetLength(1) - 1; y >= 0; y--)
                {
                    int   level;
                    float slope;
                    if (heightmap[x, y] < desiredWaterLevel)
                    {
                        // for blocks below "sea level"
                        float depth = maxDepthScaled;
                        if (altmap != null)
                        {
                            depth += altmap[x, y] * genParams.MaxDepthVariation;
                        }
                        slope = slopemap[x, y] * depth;
                        level = genParams.WaterLevel - (int)Math.Round(Math.Pow(1 - heightmap[x, y] / desiredWaterLevel, genParams.BelowFuncExponent) * depth);

                        if (genParams.AddWater)
                        {
                            if (genParams.WaterLevel - level > 3)
                            {
                                map.SetBlock(x, y, genParams.WaterLevel, theme.DeepWaterSurfaceBlock);
                            }
                            else
                            {
                                map.SetBlock(x, y, genParams.WaterLevel, theme.WaterSurfaceBlock);
                            }
                            for (int i = genParams.WaterLevel; i > level; i--)
                            {
                                map.SetBlock(x, y, i, theme.WaterBlock);
                            }
                            for (int i = level; i >= 0; i--)
                            {
                                if (level - i < theme.SeaFloorThickness)
                                {
                                    map.SetBlock(x, y, i, theme.SeaFloorBlock);
                                }
                                else
                                {
                                    map.SetBlock(x, y, i, theme.BedrockBlock);
                                }
                            }
                        }
                        else
                        {
                            if (blendmap != null && blendmap[x, y] > .25 && blendmap[x, y] < .75)
                            {
                                map.SetBlock(x, y, level, theme.CliffBlock);
                            }
                            else
                            {
                                if (slope < genParams.CliffThreshold)
                                {
                                    map.SetBlock(x, y, level, theme.GroundSurfaceBlock);
                                }
                                else
                                {
                                    map.SetBlock(x, y, level, theme.CliffBlock);
                                }
                            }

                            for (int i = level - 1; i >= 0; i--)
                            {
                                if (level - i < theme.GroundThickness)
                                {
                                    if (blendmap != null && blendmap[x, y] > CliffsideBlockThreshold && blendmap[x, y] < (1 - CliffsideBlockThreshold))
                                    {
                                        map.SetBlock(x, y, i, theme.CliffBlock);
                                    }
                                    else
                                    {
                                        if (slope < genParams.CliffThreshold)
                                        {
                                            map.SetBlock(x, y, i, theme.GroundBlock);
                                        }
                                        else
                                        {
                                            map.SetBlock(x, y, i, theme.CliffBlock);
                                        }
                                    }
                                }
                                else
                                {
                                    map.SetBlock(x, y, i, theme.BedrockBlock);
                                }
                            }
                        }
                    }
                    else
                    {
                        // for blocks above "sea level"
                        float height;
                        if (altmap != null)
                        {
                            height = maxHeightScaled + altmap[x, y] * genParams.MaxHeightVariation;
                        }
                        else
                        {
                            height = maxHeightScaled;
                        }
                        slope = slopemap[x, y] * height;
                        if (height != 0)
                        {
                            level = genParams.WaterLevel +
                                    (int)Math.Round(Math.Pow(heightmap[x, y] - desiredWaterLevel, genParams.AboveFuncExponent) *
                                                    aboveWaterMultiplier / maxHeightScaled * height);
                        }
                        else
                        {
                            level = genParams.WaterLevel;
                        }

                        bool snow = genParams.AddSnow &&
                                    (level > snowThreshold ||
                                     (level > snowStartThreshold && rand.NextDouble() < (level - snowStartThreshold) / (double)(snowThreshold - snowStartThreshold)));

                        if (blendmap != null && blendmap[x, y] > .25 && blendmap[x, y] < .75)
                        {
                            map.SetBlock(x, y, level, theme.CliffBlock);
                        }
                        else
                        {
                            if (slope < genParams.CliffThreshold)
                            {
                                map.SetBlock(x, y, level, (snow ? theme.SnowBlock : theme.GroundSurfaceBlock));
                            }
                            else
                            {
                                map.SetBlock(x, y, level, theme.CliffBlock);
                            }
                        }

                        for (int i = level - 1; i >= 0; i--)
                        {
                            if (level - i < theme.GroundThickness)
                            {
                                if (blendmap != null && blendmap[x, y] > CliffsideBlockThreshold && blendmap[x, y] < (1 - CliffsideBlockThreshold))
                                {
                                    map.SetBlock(x, y, i, theme.CliffBlock);
                                }
                                else
                                {
                                    if (slope < genParams.CliffThreshold)
                                    {
                                        if (snow)
                                        {
                                            map.SetBlock(x, y, i, theme.SnowBlock);
                                        }
                                        else
                                        {
                                            map.SetBlock(x, y, i, theme.GroundBlock);
                                        }
                                    }
                                    else
                                    {
                                        map.SetBlock(x, y, i, theme.CliffBlock);
                                    }
                                }
                            }
                            else
                            {
                                map.SetBlock(x, y, i, theme.BedrockBlock);
                            }
                        }
                    }
                }
            }

            if (genParams.AddCaves || genParams.AddOre)
            {
                AddCaves(map);
            }

            if (genParams.AddBeaches)
            {
                ReportRelativeProgress(5, "Processing: Adding beaches");
                AddBeaches(map);
            }

            if (genParams.AddTrees)
            {
                ReportRelativeProgress(5, "Processing: Planting trees");
                if (genParams.AddGiantTrees)
                {
                    Map outMap = new Map(null, map.Width, map.Length, map.Height, false)
                    {
                        Blocks = (byte[])map.Blocks.Clone()
                    };
                    var foresterArgs = new ForesterArgs {
                        Map       = map,
                        Rand      = rand,
                        TreeCount = (int)(map.Width * map.Length * 4 / (1024f * (genParams.TreeSpacingMax + genParams.TreeSpacingMin) / 2)),
                        Operation = Forester.ForesterOperation.Add,
                        PlantOn   = theme.GroundSurfaceBlock
                    };
                    foresterArgs.BlockPlacing += (sender, e) => outMap.SetBlock(e.Coordinate, e.Block);
                    Forester.Generate(foresterArgs);
                    map = outMap;
                }
                GenerateTrees(map);
            }

            if (genParams.AddFloodBarrier)
            {
                MakeFloodBarrier(map);
            }
            return(map);
        }
Example #40
0
	void Start() {
		noise = GetComponent<Noise>();
	}
Example #41
0
 public static int GetNoise(int x, int y, int z, float scale, int max)
 {
     return(Mathf.FloorToInt((Noise.Generate(x * scale, y * scale, z * scale) + 1f) * (max / 2f)));
 }
Example #42
0
 public void NoiseClear()
 {
     Noise.Clear();
     OriginalNoise.Clear();
 }
Example #43
0
    /// <summary>
    /// Redraws the preview texture
    /// </summary>
    private void updatePreview()
    {
        WorldGenerator worldGenerator = target as WorldGenerator;

        if (worldGenerator.temperature != null)
        {
            // Generate the height values
            float[,] heightValues = Noise.generateNoiseMap(previewSizePixels, previewSizePixels, worldGenerator.geography, new Vector2(worldPos.x, worldPos.y));
            float[,] tempValues   = Noise.generateNoiseMap(previewSizePixels, previewSizePixels, worldGenerator.temperature, new Vector2(worldPos.x, worldPos.y));
            float[,] rainfall     = Noise.generateNoiseMap(previewSizePixels, previewSizePixels, worldGenerator.rainfall, new Vector2(worldPos.x, worldPos.y));

            Color[] geographyColors   = new Color[previewSizePixels * previewSizePixels];
            Color[] temperatureColors = new Color[previewSizePixels * previewSizePixels];
            Color[] rainfallColors    = new Color[previewSizePixels * previewSizePixels];
            Color[] biomeColors       = new Color[previewSizePixels * previewSizePixels];

            for (int y = 0; y < previewSizePixels; y++)
            {
                for (int x = 0; x < previewSizePixels; x++)
                {
                    float height      = heightValues[x, y];
                    float temperature = worldGenerator.getTemp(tempValues[x, y], height);
                    float rianfall    = rainfall[x, y];

                    BiomeType biomeType = worldGenerator.getBiomeType(temperature, rianfall, height);
                    Color     biomeColor;

                    if (biomeType == BiomeType.DeepOcean)
                    {
                        biomeColor = new Color(0, 0, 0.7f);
                    }
                    else if (biomeType == BiomeType.Ocean)
                    {
                        biomeColor = new Color(0, 0, 1f);
                    }
                    else if (biomeType == BiomeType.Dessert)
                    {
                        biomeColor = new Color(1f, 1f, 0);
                    }
                    else if (biomeType == BiomeType.Grassland)
                    {
                        biomeColor = new Color(0f, 0.6f, 0);
                    }
                    else if (biomeType == BiomeType.Jungle)
                    {
                        biomeColor = new Color(0.0f, 0.3f, 0.0f);
                    }
                    else if (biomeType == BiomeType.TemperateForest)
                    {
                        biomeColor = new Color(0.0f, 0.6f, 0.6f);
                    }
                    else if (biomeType == BiomeType.SnowyPeaks)
                    {
                        biomeColor = new Color(0.9f, 0.9f, 0.9f);
                    }
                    else // Mountains
                    {
                        biomeColor = new Color(0.7f, 0.6f, 0.3f);
                    }


                    biomeColors[y * previewSizePixels + x] = biomeColor;

                    if (height <= worldGenerator.seaLevel)
                    {
                        geographyColors[y * previewSizePixels + x] = Color.blue;
                        rainfallColors[y * previewSizePixels + x]  = Color.blue;
                    }
                    else
                    {
                        geographyColors[y * previewSizePixels + x] = Color.Lerp(Color.black, Color.white, height);
                        rainfallColors[y * previewSizePixels + x]  = Color.Lerp(Color.black, Color.blue, rianfall);
                    }

                    if (temperature <= 0.5f)
                    {
                        temperatureColors[y * previewSizePixels + x] = Color.Lerp(Color.blue, Color.yellow, Mathf.InverseLerp(0, 0.5f, temperature));
                    }
                    else
                    {
                        temperatureColors[y * previewSizePixels + x] = Color.Lerp(Color.yellow, Color.red, Mathf.InverseLerp(0.5f, 1, temperature));
                    }
                }
            }

            int halfWorld = (previewSizePixels / 2);

            geographyColors[halfWorld * previewSizePixels + halfWorld]   = new Color(0, 1, 0);
            temperatureColors[halfWorld * previewSizePixels + halfWorld] = new Color(0, 1, 0);
            rainfallColors[halfWorld * previewSizePixels + halfWorld]    = new Color(0, 1, 0);
            biomeColors[halfWorld * previewSizePixels + halfWorld]       = new Color(0, 1, 0);

            geographyMap   = TextureGenerator.textureFromColormap(geographyColors, previewSizePixels, previewSizePixels);
            temperatureMap = TextureGenerator.textureFromColormap(temperatureColors, previewSizePixels, previewSizePixels);
            rainfallMap    = TextureGenerator.textureFromColormap(rainfallColors, previewSizePixels, previewSizePixels);
            biomeMap       = TextureGenerator.textureFromColormap(biomeColors, previewSizePixels, previewSizePixels);
        }
    }
Example #44
0
        public void Computer()
        {
            Restore();

            Filters filters = new Filters();

            if (IntervalSettings.MaxNoise != 0)
            {
                var buffer = Noise.ToArray();
                if (buffer.Count() > 0)
                {
                    filters.FilterMaximum(buffer, IntervalSettings.MaxNoise);
                    Noise.Clear();
                    Noise.AddRange(buffer);
                }
            }

            if (IntervalSettings.MinNoise != 0)
            {
                var buffer = Noise.ToArray();
                if (buffer.Count() > 0)
                {
                    filters.FilterMinimum(buffer, IntervalSettings.MinNoise);
                    Noise.Clear();
                    Noise.AddRange(buffer);
                }
            }

            if (IntervalSettings.MaxSignal != 0)
            {
                var buffer = Signal.ToArray();
                if (buffer.Count() > 0)
                {
                    filters.FilterMaximum(buffer, IntervalSettings.MaxSignal);
                    Signal.Clear();
                    Signal.AddRange(buffer);
                }
            }

            if (IntervalSettings.MinSignal != 0)
            {
                var buffer = Signal.ToArray();
                if (buffer.Count() > 0)
                {
                    filters.FilterMinimum(buffer, IntervalSettings.MinSignal);
                    Signal.Clear();
                    Signal.AddRange(buffer);
                }
            }

            if (IntervalSettings.ShiftNoise != 0)
            {
                var buffer = Noise.ToArray();
                if (buffer.Count() > 0)
                {
                    filters.FilterShift(buffer, IntervalSettings.ShiftNoise);
                    Noise.Clear();
                    Noise.AddRange(buffer);
                }
            }

            if (IntervalSettings.ShiftSignal != 0)
            {
                var buffer = Signal.ToArray();
                if (buffer.Count() > 0)
                {
                    filters.FilterShift(buffer, IntervalSettings.ShiftSignal);
                    Signal.Clear();
                    Signal.AddRange(buffer);
                }
            }

            if (IntervalSettings.DeltaShiftFrequency != 0)
            {
                var buffer = Signal.ToArray();
                if (buffer.Count() > 0)
                {
                    filters.FilterDeltaAfterFrequency(IntervalSettings.DeltaShiftFrequency, Frequencys.ToArray(), buffer);
                    Signal.Clear();
                    Signal.AddRange(buffer);
                }

                buffer = Noise.ToArray();
                if (buffer.Count() > 0)
                {
                    filters.FilterDeltaAfterFrequency(IntervalSettings.DeltaShiftFrequency, Frequencys.ToArray(), buffer);
                    Noise.Clear();
                    Noise.AddRange(buffer);
                }
            }

            if (IntervalSettings.SpecialSignalNoiseShift != 0)
            {
                var signals = Signal.ToArray();
                var noises  = Noise.ToArray();

                filters.FilterShiftNoiseOverSignal(signals, noises, IntervalSettings.SpecialSignalNoiseShift);

                Signal.Clear();
                Signal.AddRange(signals);
                Noise.Clear();
                Noise.AddRange(noises);
            }
        }
Example #45
0
        public TerrainChunk(Vector2 coord, int size, LODInfo[] detailLevels, Transform parent, Material material, GameObject _waterPlane, GenerateGameObjects genGOs)
        {
            waterPlane        = _waterPlane;
            this.detailLevels = detailLevels;
            position          = coord * size;

            if (mapGenerator.randomIslands)
            {
                float noise = Noise.GenerateNoise(mapGenerator.seed, new Vector2(position.x + mapGenerator.offset.x + mapGenerator.seed, position.y + mapGenerator.offset.y / mapGenerator.seed));
                //print(noise);
                if (noise >= mapGenerator.islandChance)
                {
                    //It is just water and not an island
                    isIsland = false;
                }
                else
                {
                    isIsland = true;
                }
            }

            bounds = new Bounds(position, Vector2.one * size);
            Vector3 positionV3 = new Vector3(position.x, 0, position.y);

            meshObject            = new GameObject("Terrain Chunk, X: " + position.x + ", Y: " + position.y);
            meshRenderer          = meshObject.AddComponent <MeshRenderer>();
            meshFilter            = meshObject.AddComponent <MeshFilter>();
            meshRenderer.material = material;
            meshCollider          = meshObject.AddComponent <MeshCollider>();

            if (waterIns == null && mapGenerator.generateWater)
            {
                Vector3 _position = new Vector3(0, -0.22f * scale, 0);
                if (isIsland)
                {
                    _position.y = -6.6f;
                }
                waterIns = GameObject.Instantiate(waterPlane, _position, Quaternion.identity);
                waterIns.transform.parent = meshObject.transform;
            }
            meshObject.transform.position = positionV3 * scale;
            meshObject.transform.parent   = parent;
            if (isIsland == false)
            {
                meshObject.AddComponent <FixHeights>();
            }

            meshObject.transform.localScale = Vector3.one * scale;

            SetVisible(false);

            lodMeshes = new LODMesh[detailLevels.Length];
            for (int i = 0; i < detailLevels.Length; i++)
            {
                lodMeshes[i] = new LODMesh(detailLevels[i].lod, UpdateTerrainChunk);
                if (detailLevels[i].useForCollider)
                {
                    collisionMesh = lodMeshes[i];
                }
            }

            mapGenerator.RequestMapData(position, OnMapDataReceived);
        }
Example #46
0
 // Update is called once per frame
 void Update()
 {
     // Simulate wacky main menu text sway
     transform.position    = initial_pos + Noise.GetSeaOffset() * 100.0f;
     transform.eulerAngles = inital_rot + 100.0f * new Vector3(Noise.GetSeaOffset().x, Noise.GetSeaOffset().y, Noise.GetSeaOffset().z);
 }
    public static IslandMapData GenerateFloatingIslandMesh(
        Vector3 baseCenterPosition,
        float maxTopHeight,
        float maxBotHeight,
        float jaggedScale,
        float islandScale,
        float minorRadius,
        float jaggedDensity,
        int meshRings,
        int seed,
        Noise.NoiseParams edgeNoiseParams,
        Noise.NoiseParams contourNoiseParams,
        IslandTerrianType[] topTerrains,
        IslandTerrianType[] bottomTerrains)
    {
        int divisions    = (int)jaggedDensity;
        int numVertices2 = 2 * divisions * (meshRings - 1) + 1;

        IslandMapData  mapData  = new IslandMapData();
        IslandMeshData meshData = new IslandMeshData(divisions, meshRings, numVertices2);

        float deltaTheta = 360f / (float)divisions;

        Color[] colorMap = new Color[2 * (divisions + 1) * (meshRings - 1)];
        float[,] noiseDivisionMap = Noise.GenerateNoiseMap(divisions, 1,
                                                           seed,
                                                           edgeNoiseParams.noiseScale,
                                                           edgeNoiseParams.octaves,
                                                           edgeNoiseParams.persistance,
                                                           edgeNoiseParams.lacunarity,
                                                           edgeNoiseParams.offset,
                                                           edgeNoiseParams.normalizeMode);

        float[,] topNoiseMapType2 = Noise.GenerateNoiseMap(meshRings, divisions,
                                                           seed,
                                                           contourNoiseParams.noiseScale,
                                                           contourNoiseParams.octaves,
                                                           contourNoiseParams.persistance,
                                                           contourNoiseParams.lacunarity,
                                                           contourNoiseParams.offset,
                                                           contourNoiseParams.normalizeMode);

        float theta    = 0;
        int   noiseIdx = 0;

        int halfway = numVertices2 / 2;

        int topVertexIndex = halfway + 1;
        int botVertexIndex = halfway - 1;

        int topIdxBegin = halfway + 1;
        int botIdxBegin = halfway - 1;

        meshData.vertices[halfway] = new Vector3(baseCenterPosition.x, maxTopHeight / 2f + baseCenterPosition.y, baseCenterPosition.z);
        meshData.vertices[0]       = new Vector3(baseCenterPosition.x, -maxBotHeight / 2f + baseCenterPosition.y, baseCenterPosition.z);
        meshData.uvs [halfway]     = new Vector2(0.5f, 0.5f);
        colorMap[halfway]          = getTerrainColor(topTerrains, 0);

        int total_added_verts = 0;

        //generate vertices
        for (int i = 0; i < divisions * (meshRings - 1); i += meshRings - 1)
        {
            float rayLength  = noiseDivisionMap[noiseIdx, 0] * jaggedScale + minorRadius * islandScale;
            float offset     = rayLength;
            float offsetIncr = rayLength / (float)meshRings;

            int jj = 0;
            for (int j = 0; j < meshRings; j++)
            {
                float modRayLength = rayLength - offset;
                float xPart        = modRayLength * (float)Math.Cos((double)theta * Math.PI / 180f);
                float zPart        = modRayLength * (float)Math.Sin((double)theta * Math.PI / 180f);

                offset -= offsetIncr;
                if (xPart == 0 && zPart == 0)
                {
                    continue;
                }

                // float curve1 = 1 - ((float)j/(float)meshRings);
                // float curve2 = 1 - (float)Math.Sqrt((float)j/(float)meshRings);
                float curve3 = 1 - (float)Math.Pow((float)j / (float)meshRings, 2);
                float curve4 = 1 - 4f * (float)Math.Pow((float)j / (float)meshRings - 0.5, 2);
                // float curve5 = 1 - 2f * (float) Math.Pow((float)j/(float)meshRings - 0.3, 2);


                float top_height = baseCenterPosition.y + topNoiseMapType2[j, noiseIdx] * (maxTopHeight * curve4);
                float bot_height = baseCenterPosition.y - topNoiseMapType2[j, noiseIdx] * (maxBotHeight * curve3);

                meshData.vertices[topVertexIndex] = new Vector3(
                    xPart + baseCenterPosition.x,
                    top_height,
                    zPart + baseCenterPosition.z);

                meshData.vertices[botVertexIndex] = new Vector3(
                    xPart + baseCenterPosition.x,
                    bot_height,
                    zPart + baseCenterPosition.z);
                total_added_verts += 2;

                //normalize for color map
                top_height = (top_height - baseCenterPosition.y) / (maxTopHeight * 0.7f);
                bot_height = (Math.Abs(bot_height - baseCenterPosition.y)) / maxBotHeight;

                meshData.uvs [topVertexIndex] = new Vector2(((float)jj) / (meshRings - 1f), 0.5f + ((float)noiseIdx) / ((float)divisions) / 2f);
                meshData.uvs [botVertexIndex] = new Vector2(((float)jj) / (meshRings - 1f), ((float)noiseIdx) / ((float)divisions) / 2f);

                jj++;

                colorMap[topVertexIndex] = getTerrainColor(topTerrains, top_height);
                colorMap[botVertexIndex] = getTerrainColor(bottomTerrains, bot_height);

                // seal center disc
                if (j == 1 && noiseIdx < divisions - 1)
                {
                    //add island top triangles
                    // meshData.AddTriangle(topVertexIndex, topVertexIndex + (meshRings + 1), topVertexIndex + 1);
                    meshData.AddTriangle(topVertexIndex, topVertexIndex + meshRings, topVertexIndex + (meshRings + 1));
                    meshData.AddTriangle(topVertexIndex, topVertexIndex + (meshRings - 1), topVertexIndex + meshRings);

                    meshData.AddTriangle(botVertexIndex, botVertexIndex - meshRings, botVertexIndex - (meshRings - 1));

                    //connect to center
                    meshData.AddTriangle(topVertexIndex + meshRings - 1, topVertexIndex, halfway);
                    meshData.AddTriangle(botVertexIndex, botVertexIndex - meshRings + 1, halfway);
                }

                //add middle triangles
                if (noiseIdx < divisions - 1 && j < meshRings - 2)
                {
                    //add island top triangles
                    meshData.AddTriangle(topVertexIndex, topVertexIndex + (meshRings + 1), topVertexIndex + 1);
                    meshData.AddTriangle(topVertexIndex, topVertexIndex + meshRings, topVertexIndex + (meshRings + 1));
                    // add island bottom triangles
                    meshData.AddTriangle(botVertexIndex, botVertexIndex - 1, botVertexIndex - (meshRings + 1));
                    meshData.AddTriangle(botVertexIndex, botVertexIndex - (meshRings + 1), botVertexIndex - meshRings);
                }

                // seal the edges
                if (noiseIdx < divisions - 1 && j == meshRings - 2)
                {
                    //extra
                    meshData.AddTriangle(topVertexIndex, topVertexIndex + (meshRings), topVertexIndex + 1);
                    meshData.AddTriangle(botVertexIndex - (meshRings), botVertexIndex, botVertexIndex - 1);

                    // //stitch gap
                    meshData.AddTriangle(topVertexIndex + 1, topVertexIndex + (meshRings), botVertexIndex - 1);
                    meshData.AddTriangle(botVertexIndex - 1, topVertexIndex + (meshRings), (botVertexIndex - (meshRings)));
                }

                // seal the end of the disc
                if (noiseIdx == divisions - 1 && j < meshRings - 1)
                {
                    //seal the edges
                    if (j == meshRings - 2)
                    {
                        //extra
                        meshData.AddTriangle(topVertexIndex + 1, topVertexIndex, topIdxBegin);
                        meshData.AddTriangle(botVertexIndex - 1, botIdxBegin, botVertexIndex);
                        //stitch gap
                        meshData.AddTriangle(topVertexIndex + 1, topIdxBegin, botVertexIndex - 1);
                        meshData.AddTriangle(botVertexIndex - 1, topIdxBegin, botIdxBegin);
                    }
                    else                       //normal
                    {
                        meshData.AddTriangle(topVertexIndex + 1, topVertexIndex, topIdxBegin);
                        meshData.AddTriangle(topVertexIndex + 1, topIdxBegin, topIdxBegin + 1);

                        meshData.AddTriangle(botVertexIndex - 1, botIdxBegin, botVertexIndex);
                        meshData.AddTriangle(botVertexIndex - 1, botIdxBegin - 1, botIdxBegin);
                    }

                    // seal the center
                    if (j == 1)
                    {
                        meshData.AddTriangle(botVertexIndex, botIdxBegin, halfway);
                        meshData.AddTriangle(topIdxBegin, topVertexIndex, halfway);
                    }

                    topIdxBegin++;
                    botIdxBegin--;
                }

                topVertexIndex++;
                botVertexIndex--;
            }

            theta += deltaTheta;
            noiseIdx++;
        }

        mapData.meshData = meshData;
        mapData.colorMap = colorMap;
        return(mapData);
    }
Example #48
0
 public TerrainGen(Noise noise)
 {
     noiseGen = noise;
 }
Example #49
0
        public static List <SampleValue> EquilibrateList(Env env, List <Symbol> outSymbols, List <SampleValue> inSamples, Noise noise, double fortime, Netlist netlist, Style style)
        {
            List <SampleValue> result = new List <SampleValue> {
            };

            for (int i = 0; i < outSymbols.Count; i++)
            {
                result.Add(Equilibrate(env, outSymbols[i], inSamples[i], noise, fortime, netlist, style));
            }
            return(result);
        }
Example #50
0
 void Start()
 {
     //Makes the block index fetch all the BlockDefinition components
     //on this gameobject and add them to the index
     Block.index.GetMissingDefinitions();
     noiseGen = new Noise(worldName);
 }
Example #51
0
    public static void generateRocks()
    {
        var spawn = m_RockGroup.ToComponentDataArray <RockTypeSpawner>(Allocator.TempJob);


        List <Entity> rocks = new List <Entity>();

        rocks.Add(spawn[0].Rock_v1);
        rocks.Add(spawn[0].Rock_v2);
        rocks.Add(spawn[0].Rock_v3);
        rocks.Add(spawn[0].Rock_v4);
        rocks.Add(spawn[0].Rock_v5);
        rocks.Add(spawn[0].Rock_v6);


        NoiseData nd1 = new NoiseData(46, 6, 0.5f, 1.7f, 54, new Vector2(0, 0), 1, 0);

        float[,] nm1 = Noise.GenerateNoiseMap(terrainWidth, terrainWidth, nd1);

        NoiseData nd2 = new NoiseData(76, 6, 0.5f, 1.7f, 54, new Vector2(0, 0), 1, 0);

        float[,] nm2 = Noise.GenerateNoiseMap(terrainWidth, terrainWidth, nd1);

        for (int i = 0; i < terrainWidth; i++)
        {
            for (int j = 0; j < terrainWidth; j++)
            {
                Vector3 terrainNormal = terrain.terrainData.GetInterpolatedNormal(i / (float)terrainWidth, j / (float)terrainWidth);
                float   slope         = calculateSlope(terrainNormal);

                if (slope < MainLoader.settings.rockSlopeThreshold)
                {
                    if (nm1[i, j] > MainLoader.settings.rockThreshold)
                    {
                        int ran = UnityEngine.Random.Range(0, MainLoader.settings.rockDensity);

                        if (ran == 0)
                        {
                            float terHeight = terrain.terrainData.GetInterpolatedHeight(i / (float)terrainWidth, j / (float)terrainWidth);
                            if ((terHeight < MainLoader.settings.rockTerrainHeightCutoff) && (terHeight > MainLoader.settings.rockTerrainMinHeight))
                            {
                                Vector3 placePos = new Vector3(i, terHeight - 1, j);
                                int     ranNum   = UnityEngine.Random.Range(0, rocks.Count);

                                var entity = MainLoader.entityManager.Instantiate(rocks[ranNum]);

                                MainLoader.entityManager.SetComponentData(entity, new Translation {
                                    Value = new float3(placePos)
                                });

                                MainLoader.entityManager.SetComponentData(entity, new Rotation
                                {
                                    Value = Quaternion.Euler(
                                        new float3(
                                            UnityEngine.Random.Range(0, 180),
                                            UnityEngine.Random.Range(0, 180),
                                            UnityEngine.Random.Range(0, 180))
                                        )
                                });
                            }


                            //MainLoader.entityManager.SetComponentData(entity, new NonUniformScale { Value = UnityEngine.Random.Range(0.3f, 3f)});
                        }
                    }
                }
            }
        }

        spawn.Dispose();
    }
Example #52
0
        Integrate(Func <double, double, Vector, Func <double, Vector, Vector>, IEnumerable <SolPoint> > Solver,
                  State initialState, double initialTime, double finalTime, Func <double, Vector, Vector> Flux,
                  SampleValue sample, List <ReportEntry> reports, Noise noise, bool nonTrivialSolution, Style style)
        {
            double redrawTick = initialTime; double redrawStep = (finalTime - initialTime) / 50;
            double densityTick = initialTime; double densityStep = (finalTime - initialTime) / 1000;
            int    pointsCounter   = 0;
            int    renderedCounter = 0;
            double lastTime        = finalTime;
            State  lastState       = null;

            if (initialState.NaN())
            {
                Gui.Log("Initial state contains NaN.");
                return(lastTime, lastState);
            }

            KChartHandler.ChartClearData(style);
            (string[] series, string[] seriesLNA) = GenerateSeries(reports, noise, style);
            KChartHandler.LegendUpdate(style);
            KScoreHandler.ScoreUpdate();

            IEnumerable <SolPoint> solution = SolutionGererator(Solver, initialState, initialTime, finalTime, Flux, nonTrivialSolution, style);
            List <TriggerEntry>    triggers = sample.Triggers(style);

            bool[] triggered = new bool[triggers.Count]; for (int i = 0; i < triggers.Count; i++)
            {
                triggered[i] = false;
            }

            // BEGIN foreach (SolPoint solPoint in solution)  -- done by hand to catch exceptions in MoveNext()

            SolPoint solPoint    = new SolPoint(initialTime, initialState.Clone().ToArray());
            bool     hasSolPoint = false;
            var      enumerator  = solution.GetEnumerator();

            do
            {
                // Handle triggers first, they can apply to the initial state
                if (triggers.Count > 0)
                {
                    State state         = null; // allocated on need from solPoint
                    State modifiedState = null; // allocated on need from state
                    for (int i = 0; i < triggers.Count; i++)
                    {
                        if (triggered[i] == false)
                        {
                            TriggerEntry trigger = triggers[i];
                            if (state == null)
                            {
                                state = new State(sample.Count(), lna: noise != Noise.None).InitAll(solPoint.X);
                            }
                            if (trigger.condition.ObserveBool(sample, solPoint.T, state, Flux, style))
                            {
                                if (modifiedState == null)
                                {
                                    modifiedState = state.Clone();
                                }
                                double rawValue   = trigger.assignment.ObserveMean(sample, solPoint.T, state, Flux, style);
                                double assignment = trigger.sample.stateMap.NormalizeDimension(trigger.target, rawValue, trigger.dimension, trigger.sample.Volume(), style);
                                int    index      = sample.stateMap.IndexOf(trigger.target.symbol);
                                modifiedState.SetMean(index, assignment);
                                if (noise != Noise.None && trigger.assignmentVariance != null)
                                {
                                    double rawValueVariance   = trigger.assignmentVariance.ObserveMean(sample, solPoint.T, state, Flux, style);
                                    double assignmentVariance = trigger.sample.stateMap.NormalizeDimension(trigger.target, rawValueVariance, trigger.dimension, trigger.sample.Volume(), style);
                                    modifiedState.SetCovar(index, index, assignmentVariance);
                                }
                                triggered[i] = true;
                            }
                        }
                    }
                    if (modifiedState != null)          //restart the solver
                    {
                        State newState = modifiedState; // new State(sample.Count(), lna: noise != Noise.None).InitAll(modifiedState.ToArray());
                        solution   = SolutionGererator(Solver, newState, solPoint.T, finalTime, Flux, nonTrivialSolution, style);
                        enumerator = solution.GetEnumerator();
                    }
                }

                try {
                    if (!enumerator.MoveNext())
                    {
                        break;
                    }
                    solPoint    = enumerator.Current;    // get next step of integration from solver
                    hasSolPoint = true;
                }
                catch (ConstantEvaluation e) { // stop simulation but allow execution to proceed
                    Gui.Log("Simulation stopped and ignored: cannot evaluate constant '" + e.Message + "'");
                    return(lastTime, lastState);
                }
                catch (Error e) { throw new Error(e.Message); }
                catch (Exception e) { KChartHandler.ChartUpdate(style, false); throw new Error("ODE Solver FAILED: " + e.Message); }
                pointsCounter++;

                // LOOP BODY of foreach (SolPoint solPoint in solution):
                if (!Exec.IsExecuting())
                {
                    KChartHandler.ChartUpdate(style); throw new ExecutionEnded("");
                }                                  // break;

                if (style.chartOutput)             // Plot the new solution point
                {
                    if (solPoint.T >= densityTick) // avoid drawing too many points
                    {
                        State state = new State(sample.Count(), lna: noise != Noise.None).InitAll(solPoint.X);
                        for (int i = 0; i < reports.Count; i++)
                        {
                            if (series[i] != null)   // if a series was actually generated from this report
                            // generate deterministic series
                            {
                                if ((noise == Noise.None && reports[i].flow.HasDeterministicValue()) ||
                                    (noise != Noise.None && reports[i].flow.HasStochasticMean()))
                                {
                                    double mean = reports[i].flow.ObserveMean(sample, solPoint.T, state, Flux, style);
                                    KChartHandler.ChartAddPoint(series[i], solPoint.T, mean, 0.0, Noise.None);
                                }
                                // generate LNA-dependent series
                                if (noise != Noise.None && reports[i].flow.HasStochasticVariance() && !reports[i].flow.HasNullVariance())
                                {
                                    double mean     = reports[i].flow.ObserveMean(sample, solPoint.T, state, Flux, style);
                                    double variance = reports[i].flow.ObserveVariance(sample, solPoint.T, state, style);
                                    KChartHandler.ChartAddPoint(seriesLNA[i], solPoint.T, mean, variance, noise);
                                }
                            }
                        }
                        renderedCounter++;
                        densityTick += densityStep;
                    }
                    if (solPoint.T >= redrawTick)   // avoid redrawing the plot too often
                    {
                        KChartHandler.ChartUpdate(style, incremental: true);
                        redrawTick += redrawStep;
                    }
                }

                lastTime = solPoint.T;

                // END foreach (SolPoint solPoint in solution)
            } while (true);

            if (hasSolPoint)
            {
                lastState = new State(sample.Count(), lna: noise != Noise.None).InitAll(solPoint.X);
            }
            KChartHandler.ChartUpdate(style, incremental: false);

            return(lastTime, lastState);
        }
 public static void createNoiseObjects(int seed)
 {
     baseTerrainNoise = new Noise(seed * 3 + 0);
     continentNoise   = new Noise(seed * 3 + 0);
     mountainNoise    = new Noise(seed * 3 + 2);
 }
Example #54
0
        public static SampleValue Equilibrate(Env env, Symbol outSymbol, SampleValue inSample, Noise noise, double fortime, Netlist netlist, Style style)
        {
            inSample.CheckConsumed(style); // we will consume it later, but we need to check now
            double initialTime = 0.0;
            double finalTime   = fortime;

            string sampleName = (outSymbol.Raw() == "vessel") ? "" : "Sample " + inSample.FormatSymbol(style);

            KChartHandler.ChartClear(sampleName, "s", "M", style);

            List <SpeciesValue> inSpecies = inSample.stateMap.species;
            State initialState            = inSample.stateMap.state;

            if ((noise == Noise.None) && initialState.lna)
            {
                initialState = new State(initialState.size, lna: false).InitMeans(initialState.MeanVector());
            }
            if ((noise != Noise.None) && !initialState.lna)
            {
                initialState = new State(initialState.size, lna: true).InitMeans(initialState.MeanVector());
            }
            List <ReactionValue> reactions = inSample.RelevantReactions(netlist, style);
            CRN crn = new CRN(inSample, reactions, precomputeLNA: (noise != Noise.None) && KControls.precomputeLNA);

            KChartHandler.SetMeanFlowDictionary(crn.MeanFlowDictionary(), style);
            // List<ReportEntry> reports = netlist.Reports(inSpecies);
            List <ReportEntry> reports = inSample.RelevantReports(style);

            Exec.lastExecution.lastCRN = crn; KGui.gui.GuiOutputSetText(crn.FormatNice(style));
            Exec.lastExecution.ResetGraphCache();

            Func <double, double, Vector, Func <double, Vector, Vector>, IEnumerable <SolPoint> > Solver;

            if (KControls.solver == "GearBDF")
            {
                Solver = Ode.GearBDF;
            }
            else if (KControls.solver == "RK547M")
            {
                Solver = Ode.RK547M;
            }
            else
            {
                throw new Error("No solver");
            }

            Func <double, Vector, Vector> Flux;

            if (noise != Noise.None)
            {
                Flux = (t, x) => crn.LNAFlux(t, x, style);
            }
            else
            {
                Flux = (t, x) => crn.Flux(t, x, style);
            }

            bool nonTrivialSolution =
                (inSpecies.Count > 0) &&  // we don't want to run on the empty species list: Oslo crashes
                (!crn.Trivial(style)) &&  // we don't want to run trivial ODEs: some Oslo solvers hang on very small stepping
                finalTime > 0;            // we don't want to run when fortime==0

            // INTEGRATE
            (double lastTime, State lastState) =
                Integrate(Solver, initialState, initialTime, finalTime, Flux, inSample, reports, noise, nonTrivialSolution, style);

            if (lastState == null)
            {
                lastState = initialState.Clone();
            }
            lastState = lastState.Positive();
            List <SpeciesValue> outSpecies = new List <SpeciesValue> {
            }; foreach (SpeciesValue sp in inSpecies)
            {
                outSpecies.Add(sp);                                                                                                // the species list may be destructively modified (added to) later in the new sample
            }
            SampleValue outSample = new SampleValue(outSymbol, new StateMap(outSymbol, outSpecies, lastState), new NumberValue(inSample.Volume()), new NumberValue(inSample.Temperature()), produced: true);

            outSample.AddReports(inSample.RelevantReports(style));

            foreach (ReportEntry report in reports)
            {
                // an equilibrate may pick up the reports of a previous equilibrate, so we reassign the report even if it has already been assigned
                // this does not really affect lexical binding because a second report with the same name will get a new symbol
                // P.S. this was changed so that an equilibrate no longer picks up reports of previous equilibrate, so the issue should not arise
                if (report.timecourse != null)
                {
                    env.AssignValue(report.timecourse, KChartHandler.ToTimecourse(report.timecourse, report.flow, style), reassign: true);
                }
            }

            inSample.Consume(reactions, lastTime, lastState, netlist, style);
            return(outSample);
        }
Example #55
0
    public void GenerateMap()
    {
        prng       = new System.Random(seed);
        sectorsMap = new Transform[mapSize.x, mapSize.y];

        // Generating coordinates for all the sectors
        sectorsCoords = new List <Vector2Int>();
        for (int x = 0; x < mapSize.x; x++)
        {
            for (int y = 0; y < mapSize.y; y++)
            {
                sectorsCoords.Add(new Vector2Int(x, y));
            }
        }
        shuffledSectorsCoords = new Queue <Vector2Int>(Utility.ShuffleArray(sectorsCoords.ToArray(), seed));

        // Creating Map Holders
        if (GameObject.Find(mapName))
        {
            DestroyImmediate(GameObject.Find(mapName));
        }
        Transform mapHolder   = new GameObject(mapName).transform;
        Transform floorHolder = new GameObject("Floor").transform;

        floorHolder.parent = mapHolder;
        Transform wallsHolder = new GameObject("Walls").transform;

        wallsHolder.parent = mapHolder;
        Transform obstaclesHolder = new GameObject("Obstacles").transform;

        obstaclesHolder.parent = mapHolder;
        Transform borderHolder = new GameObject("Border").transform;

        borderHolder.parent = mapHolder;
        Transform roofHolder = new GameObject("Roof").transform;

        roofHolder.parent = mapHolder;
        Transform floraHolder = new GameObject("Flora").transform;

        floraHolder.parent = mapHolder;

        // Generate wall sectors
        bool[,] wallSectorsMap = new bool[mapSize.x, mapSize.y];

        int wallSectorsCount        = (int)(mapSize.x * mapSize.y * wallPercent);
        int currentWallSectorsCount = 0;

        List <Vector2Int> freeSectorsCoords = new List <Vector2Int>(sectorsCoords);

        float[,] noiseMap = Noise.GenerateNoiseMap(mapSize.x * sectorSize,
                                                   mapSize.y * sectorSize,
                                                   seed,
                                                   10,
                                                   8,
                                                   0.8f,
                                                   4,
                                                   Vector2.one);

        for (int i = 0; i < wallSectorsCount; i++)
        {
            Vector2Int randomCoord = GetRandomSectorCoord();
            wallSectorsMap[randomCoord.x, randomCoord.y] = true;
            currentWallSectorsCount++;

            if (randomCoord != Vector2Int.zero && Utility.FloodFill(wallSectorsMap, currentWallSectorsCount, mapSize.x * mapSize.y, Vector2Int.zero))
            {
                GenerateWallSector(noiseMap, randomCoord, wallsHolder);
                freeSectorsCoords.Remove(randomCoord);
            }
            else
            {
                wallSectorsMap[randomCoord.x, randomCoord.y] = false;
                currentWallSectorsCount--;
            }
        }

        // Generate free map
        List <Vector2Int> freeTilesCoords = new List <Vector2Int>();

        for (int i = 0; i < freeSectorsCoords.Count; i++)
        {
            for (int x = 0; x < sectorSize; x++)
            {
                for (int y = 0; y < sectorSize; y++)
                {
                    freeTilesCoords.Add(new Vector2Int(x, y) + freeSectorsCoords[i] * sectorSize);
                }
            }
        }
        GenerateFreeMap(freeTilesCoords, floorHolder, obstaclesHolder, floraHolder);

        GenerateBorder(borderHolder);

        //GenerateRoof(roofHolder);
    }
Example #56
0
 private void DestroyAnimationMenu() => CreateMenu("Destroy animation", GotoMenu(PatchesMenu, 4),
                                                   MenuItem.Create(Sprites.ToText()).OnSelect((s, a) => Settings.DestroyAnimation = Sprites).SetActive(() => Settings.DestroyAnimation == Sprites),
                                                   MenuItem.Create(Noise.ToText()).OnSelect((s, a) => Settings.DestroyAnimation   = Noise).SetActive(() => Settings.DestroyAnimation == Noise),
                                                   MenuItem.Create("Back")
                                                   );
Example #57
0
        //обработка данных измерений только для СС
        public void Computer()
        {
            //для сигналов, > Мах или < Мин, формируется случайное значение в диапазоне Мах-2,Мах или Мин,Мин+2
            Restore(); //копирование оригинальных значений сигнала и шума в коллекцию сигналов и шумов

            Filters filters = new Filters();

            if (IntervalSettings.MaxNoise != 0)
            {
                var buffer = Noise.ToArray();
                if (buffer.Count() > 0)
                {
                    filters.FilterMaximum(buffer, IntervalSettings.MaxNoise);
                    Noise.Clear();
                    Noise.AddRange(buffer);
                }
            }

            if (IntervalSettings.MinNoise != 0)
            {
                var buffer = Noise.ToArray();
                if (buffer.Count() > 0)
                {
                    filters.FilterMinimum(buffer, IntervalSettings.MinNoise);
                    Noise.Clear();
                    Noise.AddRange(buffer);
                }
            }

            if (IntervalSettings.MaxSignal != 0)
            {
                var buffer = Signal.ToArray();
                if (buffer.Count() > 0)
                {
                    filters.FilterMaximum(buffer, IntervalSettings.MaxSignal);
                    Signal.Clear();
                    Signal.AddRange(buffer);
                }
            }

            if (IntervalSettings.MinSignal != 0)
            {
                var buffer = Signal.ToArray();
                if (buffer.Count() > 0)
                {
                    filters.FilterMinimum(buffer, IntervalSettings.MinSignal);
                    Signal.Clear();
                    Signal.AddRange(buffer);
                }
            }

            if (IntervalSettings.ShiftNoise != 0)
            {
                var buffer = Noise.ToArray();
                if (buffer.Count() > 0)
                {
                    filters.FilterShift(buffer, IntervalSettings.ShiftNoise);
                    Noise.Clear();
                    Noise.AddRange(buffer);
                }
            }

            if (IntervalSettings.ShiftSignal != 0)
            {
                var buffer = Signal.ToArray();
                if (buffer.Count() > 0)
                {
                    filters.FilterShift(buffer, IntervalSettings.ShiftSignal);
                    Signal.Clear();
                    Signal.AddRange(buffer);
                }
            }
            //задана частота предусилителя
            if (IntervalSettings.DeltaShiftFrequency != 0)
            {
                var buffer = Signal.ToArray();
                if (buffer.Count() > 0)
                {
                    filters.FilterDeltaAfterFrequency(IntervalSettings.DeltaShiftFrequency, Frequencys.ToArray(), buffer);
                    Signal.Clear();
                    Signal.AddRange(buffer);
                }

                buffer = Noise.ToArray();
                if (buffer.Count() > 0)
                {
                    filters.FilterDeltaAfterFrequency(IntervalSettings.DeltaShiftFrequency, Frequencys.ToArray(), buffer);
                    Noise.Clear();
                    Noise.AddRange(buffer);
                }
            }

            if (IntervalSettings.SpecialSignalNoiseShift != 0)
            {
                var signals = Signal.ToArray();
                var noises  = Noise.ToArray();

                filters.FilterShiftNoiseOverSignal(signals, noises, IntervalSettings.SpecialSignalNoiseShift);

                Signal.Clear();
                Signal.AddRange(signals);
                Noise.Clear();
                Noise.AddRange(noises);
            }
        }