Inheritance: MonoBehaviour
Example #1
0
 public void Init()
 {
     textureBlendNoise = new PerlinNoise();
     textureBlendNoise.baseOctave = textureBlendNoiseBaseOctave;
     textureBlendNoise.weights = textureBlendNoiseWeights;
     textureBlendNoise.Init();
 }
        public void Generate(Block[,,] blocks, ChunkInfo info)
        {
            PerlinNoise coarse = new PerlinNoise(info.Seed + PerlinAllocations.TEMPERATURE_COARSE);
            PerlinNoise medium = new PerlinNoise(info.Seed + PerlinAllocations.TEMPERATURE_MEDIUM);
            PerlinNoise fine = new PerlinNoise(info.Seed + PerlinAllocations.TEMPERATURE_FINE);
            TemperatureInformation temperature = new TemperatureInformation();

            // Generate temperature.
            int ox = info.Bounds.Width / 2;
            int oy = info.Bounds.Height / 2;
            for (int x = -info.Bounds.Width / 2; x < info.Bounds.Width * 1.5; x++)
                for (int y = -info.Bounds.Height / 2; y < info.Bounds.Height * 1.5; y++)
                {
                    double noise = coarse.Noise((double)(info.Bounds.X + x) / PERLIN_COARSE_SCALE,
                        (double)(info.Bounds.Y + y) / PERLIN_COARSE_SCALE,
                        0);
                    noise += PerlinNoise.OFFSET;
                    if (x >= 0 && y >= 0 && x < info.Bounds.Width && y < info.Bounds.Height)
                        temperature.Temperature[x, y] = (float)noise;
                    temperature.NeighbouringTemperature[x + ox, y + oy] = (float)noise;
                }

            // Add to information list.
            info.Objects.Add(temperature);
        }
Example #3
0
 public void OctavePerlinReturnsDifferentValuesForDifferentCoordinates()
 {
     PerlinNoise tm = new PerlinNoise();
       var test = tm.OctavePerlin(0.5f, 0.5f, 0, 1, 128, 4);
       var test2 = tm.OctavePerlin(0.6f, 0.5f, 0, 1, 128, 4);
       Assert.AreNotEqual(test, test2);
 }
 public float SampleGround(float x,float z, PerlinNoise perlin)
 {
     //This creates the noise used for the ground.
     //The last value (8.0f) is the amp that defines (roughly) the maximum
     float w = perlin.FractalNoise2D(x , z ,1,GroundFrequency,GroundAmplitude);
     return perlin.FractalNoise2D(x-w, z-w,GroundOct,GroundFrequency,GroundAmplitude);
 }
Example #5
0
 public void PerlinReturnsTheSameValueForTheSameCoordinates()
 {
     PerlinNoise tm = new PerlinNoise();
       var test = tm.perlin(0.5f, 0.5f, 0);
       var test2 = tm.perlin(0.5f, 0.5f, 0);
       Assert.AreEqual(test, test2);
 }
	protected override void Start() {

		base.Start ();

		_beatSync = GetComponent<BeatSynchronizer>();
		_beatCounter = GetComponent<BeatCounter>();
		_beatObserver = GetComponent<BeatObserver>();

		_beatSync.enabled = false;
		_boss.gameObject.SetActive(false);

		_tilesSource  = new MisObjectPool (_platforms[(int)PLATFORMS.BREAKABLE], 300, transform);
		_tilesSource.ExecActionInObjects (InitTile);

		_enemiesSource  = new MisObjectPool (_enemies[(int)ENEMIES.MINION], 50, transform);
		_enemiesSource.ExecActionInObjects (InitEnemy);

		_tilesAdded    = new List<GameObject> ();
		_tilesToDelete = new List<GameObject> ();
		_collidebleTiles = new Dictionary <Vector2, GameObject> ();

		_noiseGenerator = new PerlinNoise (0);

		_lenght = (int)(_beatCounter.audioSource.clip.length * 8f);
		_lenght += FST_SECTION + SND_SECTION + FST_JMP_SIZE;

		_spectrum = new float[SONG_SAMPLE_SIZE];
	}
Example #7
0
 public void PerlinReturnsDifferentValuesForDifferentCoordinates()
 {
     PerlinNoise tm = new PerlinNoise();
       var test = tm.perlin(0f / 513, 0f / 513, 0);
       var test2 = tm.perlin(0f / 513, 1f / 513, 0);
       Assert.AreNotEqual(test, test2);
 }
    void Start()
    {
        var m_perlin = new PerlinNoise(2);

        //Target is the value that represents the surface of mesh
        //For example the perlin noise has a range of -1 to 1 so the mid point is were we want the surface to cut through
        //The target value does not have to be the mid point it can be any value with in the range
        MarchingCubes.SetTarget(0);

        //Winding order of triangles use 2,1,0 or 0,1,2
        MarchingCubes.SetWindingOrder(0, 1, 2);

        //Set the mode used to create the mesh
        //Cubes is faster and creates less verts, tetrahedrons is slower and creates more verts but better represents the mesh surface
        MarchingCubes.SetModeToCubes();
        //MarchingCubes.SetModeToTetrahedrons();

        //The size of voxel array. Be carefull not to make it to large as a mesh in unity can only be made up of 65000 verts
        var width = 32;
        var height = 32;
        var length = 32;

        var voxels = new float[width, height, length];

        //Fill voxels with values. Im using perlin noise but any method to create voxels will work
        for (int x = 0; x < width; x++)
        {
            for (int y = 0; y < height; y++)
            {
                for (int z = 0; z < length; z++)
                {
                    //voxels[x,y,z] = m_perlin.FractalNoise3D(x, y, z, 3, 40.0, 1.0); 

                    // 0 - means the voxel will be filled, any other value means it won't be filled
                    voxels[x, y, z] = (x - width / 2f) * (x - width / 2f) + (y - height / 2f) * (y - height / 2f) + (z - length / 2f) * (z - length / 2f) - 256;

                    //if (x == 0 || x == width || y == 0 || y == height)
                    //    voxels[x, y, z] = 0;
                }
            }
        }

        Mesh mesh = MarchingCubes.CreateMesh(voxels);

        //The diffuse shader wants uvs so just fill with a empty array, there not actually used
        mesh.uv = new Vector2[mesh.vertices.Length];
        mesh.RecalculateNormals();

        m_mesh = new GameObject("Mesh");
        m_mesh.AddComponent<MeshFilter>();
        m_mesh.AddComponent<MeshRenderer>();
        m_mesh.GetComponent<Renderer>().material = m_material;
        m_mesh.GetComponent<MeshFilter>().mesh = mesh;
        //Center mesh
        m_mesh.transform.localPosition = new Vector3(-width / 2, -height / 2, -length / 2);
    }
Example #9
0
    void Start()
    {
        //Random.seed = Random.Range (0, 65000);
        m_surfaceSeed = Random.Range (0, 65000);
        //Make 2 perlin noise objects, one is used for the surface and the other for the caves
        m_surfacePerlin = new PerlinNoise(m_surfaceSeed);
        m_voronoi = new VoronoiNoise(m_surfaceSeed);
        GameObject.Find ("SaveTracker").GetComponent<SaveSceneComponent>().save.m_surfaceSeed = m_surfaceSeed;
        player = GameObject.FindWithTag ("Player").transform;

        //	PerlinNoise  m_cavePerlin = new PerlinNoise(m_caveSeed);

        //Set some varibles for the marching cubes plugin
        MarchingCubes.SetTarget(0.0f);
        MarchingCubes.SetWindingOrder(2, 1, 0);
        MarchingCubes.SetModeToCubes();

        //create a array to hold the voxel chunks

        m_voxelChunk  = new VoxelChunk[m_chunksX,m_chunksY,m_chunksZ];

        //The offset is used to centre the terrain on the x and z axis. For the Y axis
        //you can have a certain amount of chunks above the y=0 and the rest will be below
        Vector3 offset = new Vector3(m_chunksX*m_voxelWidth*-0.5f, -(m_chunksY-m_chunksAbove0)*m_voxelHeight, m_chunksZ*m_voxelLength*-0.5f);

        for(int x = 0; x < m_chunksX; x++)
        {
            for(int y = 0; y < m_chunksY; y++)
            {
                for(int z = 0; z < m_chunksZ; z++)
                {
                    //The position of the voxel chunk
                    Vector3 pos = new Vector3(x*m_voxelWidth, y*m_voxelHeight, z*m_voxelLength);
                    //Create the voxel object
                    m_voxelChunk[x,y,z] = new VoxelChunk(pos+offset, m_voxelWidth, m_voxelHeight, m_voxelLength, m_surfaceLevel);
                    //Create the voxel data
                    m_voxelChunk[x,y,z].CreateVoxels(m_surfacePerlin, m_voronoi);//, m_cavePerlin);
                    i++;
                    //Smooth the voxels, is optional but I think it looks nicer
                //	m_voxelChunk[x,y,z].SmoothVoxels();
                    //Create the normals. This will create smoothed normal.
                    //This is optional and if not called the unsmoothed mesh normals will be used
                //	m_voxelChunk[x,y,z].CalculateNormals();
                    //Creates the mesh form voxel data using the marching cubes plugin and creates the mesh collider
                    m_voxelChunk[x,y,z].CreateMesh(m_material);

                }
            }
        }
        currentX = m_chunksX * m_voxelWidth;
        currentZ = m_chunksZ * m_voxelLength;
    }
Example #10
0
    //, PerlinNoise cavePerlin)
    public void CreateVoxels(PerlinNoise surfacePerlin, VoronoiNoise voronoiNoise)
    {
        //float startTime = Time.realtimeSinceStartup;

        //Creates the data the mesh is created form. Fills m_voxels with values between -1 and 1 where
        if(monoInstance == null)
        {
            //-1 is a soild voxel and 1 is a empty voxel.
            monoInstance = GameObject.Find ("CoRoutiner").GetComponent<MonoBehaviour>();
        }
        monoInstance.StartCoroutine ("DoCoroutine", this.kriejt(surfacePerlin, voronoiNoise));
        //Debug.Log("Create voxels time = " + (Time.realtimeSinceStartup-startTime).ToString() );
    }
Example #11
0
    // Use this for initialization
    void Awake()
    {
        riverPathNoiseSeed = 3;
        riverPathNoise = new PerlinNoise(riverPathNoiseSeed);
        RiverStartPointsPerPolygon = 4;
        HexagonRadius = 20000;        
        HexagonApothem = HexagonRadius * (Mathf.Cos(30 * Mathf.Deg2Rad));
        tribLength = 2000; //Maximum distance between tributary endPoints
        maximumTributaries = Mathf.RoundToInt((HexagonRadius * 2) / tribLength);

        offsets = new float[,]
        {
            {0, 2}, //North
            {1.5f, 1}, //north East
            {1.5f, -1}, //South East
            {0, -2}, //South
            {-1.5f, -1}, //South West
            {-1.5f, 1}, //North West
        };

        hexagonCentres = new Vector3[7];
        adjacentHexagonCentres = new Vector3[3];
        platePoints = new int[3, 2];
        riverMouths = new Vector3[3, 4];        
        hexagonVertices = new Vector3[3, 6];       
        riverStartPoints = new Vector3[3, RiverStartPointsPerPolygon];
        riverMidpoints = new Vector3[3, 4];
        activeRiverMidpoints = new bool[3, 4];
        riverStartToMid = new int[3, 4];
        closestContinentCentres = new Vector3[3];
        hexagonClassifications = new int[3,5];
        tribEndStartMid = new Vector3[RiverStartPointsPerPolygon][,];
        for (int i = 0; i < RiverStartPointsPerPolygon; i++)
        {
            tribEndStartMid[i] = new Vector3[maximumTributaries,2];
        }
        
        /*
        Classifications:
        One for each adjacent Hexagon
        0 - Landmass (central(0) or outer(1)), ocean(2), large island(3), small islands(4)
        1 - No mountains (0), Central Mountains(1), Mountain Range (2)
        2 - Desert(0), Tropical (1), Temperate (2) etc (add later)
        */

        tectonicNoise = new PerlinNoise(plateRatioSeed);
        getPlayerPosition();
        calculateHexagons();

    }
        public override int[] GenerateData(int x, int y, int width, int height)
        {
            int[] data = new int[width * height];
            PerlinNoise perlin = new PerlinNoise(this.GetPerlinRNG());

            for (int a = 0; a < width; a++)
                for (int b = 0; b < height; b++)
                {
                    double noise = perlin.Noise((x + a) / this.Scale, (y + b) / this.Scale, 0) / 2.0 + 0.5;
                    data[a + b * width] = (int)((noise * (this.MaxValue - this.MinValue)) + this.MinValue);
                }

            return data;
        }
    public float FillVoxel2d(float x,float z, Vector3 m_pos,PerlinNoise noise,PerlinNoise caveNoise)
    {
        //float startTime = Time.realtimeSinceStartup;

        //Creates the data the mesh is created form. Fills m_voxels with values between -1 and 1 where
        //-1 is a soild voxel and 1 is a empty voxel.

        float HT = 0;

        HT  += SampleGround(x,z,noise);
        HT  += SampleMountains(x,z,noise);
        HT  -= SampleCaves(x,z,caveNoise);
        if(check)
            Debug.Log(HT);

        return HT;
    }
Example #14
0
    void AddNoiseToVoxels()
    {
        if (noiseAmount < 0f) return;

        PerlinNoise noise = new PerlinNoise (Random.seed);

        int v = voxelCountPerChunk * chunkStride;
        for (int i = 0; i < v; i++) {
            for (int j = 0; j < v; j++) {
                for (int k = 0; k < v; k++) {
                    if (voxels[i, j, k] == 0f) continue;
                    voxels[i, j, k] += noise.FractalNoise3D(i, j, k, octNum, noiseFreq, 1f) * noiseAmount;
                    voxels[i, j, k] = Mathf.Clamp01(voxels[i, j, k]);
                }
            }
        }
    }
Example #15
0
    void Start()
    {
        windNoise = new PerlinNoise();
        windNoise.baseOctave = windNoiseBaseOctave;
        windNoise.weights = windNoiseWeights;
        windNoise.Init();

        birdNoise = new PerlinNoise();
        birdNoise.baseOctave = birdNoiseBaseOctave;
        birdNoise.weights = birdNoiseWeights;
        birdNoise.Init();

        // Retrieve some settings from the chunk controller.
        ChunkController chunk = chunkController.GetComponent<ChunkController>();

        heavyWindHeight = chunk.terrainHeight * chunk.mountainPeekHeight * 1.2f;
        underwaterLevel = chunk.terrainHeight * chunk.waterHeight;
    }
Example #16
0
    void Start()
    {
        //Make 2 perlin noise objects, one is used for the surface and the other for the caves
        PerlinNoise m_surfacePerlin = new PerlinNoise(m_surfaceSeed);
        PerlinNoise  m_cavePerlin = new PerlinNoise(m_caveSeed);

        //Set some varibles for the marching cubes plugin
        MarchingCubes.SetTarget(0.0f);
        MarchingCubes.SetWindingOrder(2, 1, 0);
        MarchingCubes.SetModeToCubes();

        //create a array to hold the voxel chunks
        m_Chunk  = new Chunk[m_chunksX,m_chunksY,m_chunksZ];

        //The offset is used to centre the terrain on the x and z axis. For the Y axis
        //we can have a certain amount of chunks above the y=0 and the rest will be below
        Vector3 offset = new Vector3(m_chunksX*m_voxelWidth*-0.5f, -(m_chunksY-m_chunksAbove0)*m_voxelHeight, m_chunksZ*m_voxelLength*-0.5f);

        for(int x = 0; x < m_chunksX; x++)
        {
            for(int y = 0; y < m_chunksY; y++)
            {
                for(int z = 0; z < m_chunksZ; z++)
                {
                    //The position of the voxel chunk
                    Vector3 pos = new Vector3(x*m_voxelWidth, y*m_voxelHeight, z*m_voxelLength);
                    //Create the voxel object
                    m_Chunk[x,y,z] = new Chunk(pos+offset, m_voxelWidth, m_voxelHeight, m_voxelLength, m_surfaceLevel);
                    //Create the voxel data
                    m_Chunk[x,y,z].CreateVoxels(m_surfacePerlin);

                    //Smooth the voxels, is optional but I think it looks nicer
                    m_Chunk[x,y,z].SmoothVoxels();
                    //Create the normals. This will create smoothed normal.
                    //This is optional and if not called the unsmoothed mesh normals will be used
                    m_Chunk[x,y,z].CalculateNormals();
                    //Creates the mesh form voxel data using the marching cubes plugin and creates the mesh collider
                    m_Chunk[x,y,z].CreateMesh(m_material);

                }
            }
        }
    }
Example #17
0
 public void MinMaxTest()
 {
     float min = float.MaxValue;
       float max = float.MinValue;
       PerlinNoise tm = new PerlinNoise();
       for (int y = 0; y < 20000; y++)
       {
     for (int x = 0; x < 512; x++)
     {
       float val = (float)tm.OctavePerlin((float)x / 3000f, (float)y / 3000f, 0, 8, 128, 4);
       if (val > max)
       {
     max = val;
       }
       if (val < min)
       {
     min = val;
       }
     }
       }
 }
Example #18
0
 public void Initialize(int seed_,float freq_,Vector3 gPos_, Material mat)
 {
     seed = seed_;
     freq = freq_;
     gPos = gPos_;
     xi = (int)gPos_.x;
     yi = (int)gPos_.y;
     zi = (int)gPos_.z;
     m_perlin = new PerlinNoise(seed);
     MarchingCubes.SetTarget(0.0f);
     MarchingCubes.SetWindingOrder(2, 1, 0);
     MarchingCubes.SetModeToCubes();
     m_mesh = new GameObject("Mesh(" + xi + "," + yi + "," + zi + ")");
     m_mesh.AddComponent<MeshFilter>();
     m_mesh.AddComponent<MeshRenderer>();
     m_mesh.renderer.material = mat;
     m_mesh.renderer.material.SetTextureScale("_MainTex", new Vector2(0.1f, 0.1f));
     if(Resources.Load<Mesh>("meshes/mesh" + xi + yi + zi))
         isNew = false;
     else
         isNew = true;
 }
Example #19
0
    //, PerlinNoise cavePerlin)
    IEnumerator kriejt(PerlinNoise surfacePerlin, VoronoiNoise voronoiNoise)
    {
        int w = m_voxels.GetLength(0);
        int h = m_voxels.GetLength(1);
        int l = m_voxels.GetLength(2);
        for(int x = 0; x < w; x++)
        {
            for(int z = 0; z < l; z++)
            {
                //world pos is the voxels position plus the voxel chunks position
                float worldX = x+m_pos.x;
                float worldZ = z+m_pos.z;
                groundHt = SampleGround(worldX, worldZ, surfacePerlin, voronoiNoise);

                mountainHt = SampleMountains(worldX, worldZ, surfacePerlin);
                ht = mountainHt + groundHt;

                for(int y = 0; y < h; y++)
                {
                    worldY = y+m_pos.y-m_surfaceLevel;

                    //If we take the heigth value and add the world
                    //the voxels will change from positiove to negative where the surface cuts through the voxel chunk
                    m_voxels[x,y,z] = Mathf.Clamp(ht + worldY , -1.0f, 1.0f);
                    //float caveHt = SampleCaves(worldX, worldY, worldZ, cavePerlin);

                    //This fades the voxel value so the caves never appear more than 16 units from
                    //the surface level.
                    //float fade = 1.0f - Mathf.Clamp01(Mathf.Max(0.0f, worldY)/16.0f);

                    //m_voxels[x,y,z] += caveHt * fade;

                    //	m_voxels[x,y,z] = Mathf.Clamp(m_voxels[x,y,z], -1.0f, 1.0f);
                }
            }
        }
        yield return new WaitForSeconds(0.001f);
    }
Example #20
0
 float SampleGround(float x, float z, PerlinNoise perlin, VoronoiNoise voronoi)
 {
     //This creates the noise used for the ground.
     //The last value (8.0f) is the amp that defines (roughly) the maximum
     //and minimum vaule the ground varies from the surface level
     //return perlin.FractalNoise2D(x, z, 12, 80.0f, 8.0f);
     test = voronoi.FractalNoise2D(x, z, 8, 32.0f, 8.0f) + perlin.FractalNoise2D(x, z, 12, 80.0f, 8.0f)/2;
     if(test > 1.85f)
     {
         return Mathf.Min (1.85f, test) + test/3f;
     }
     else
     {
         return test;
     }
     //return Mathf.Min (2.75f,test);
 }
Example #21
0
    void FillTreeInstances()
    {
        terrain.treeDistance = m_treeDistance;
        terrain.treeBillboardDistance = m_treeBillboardDistance;
        terrain.treeCrossFadeLength = m_treeCrossFadeLength;
        terrain.treeMaximumFullLODCount = m_treeMaximumFullLODCount;

        m_treeProtoTypes = new TreePrototype[2];

        m_treeProtoTypes[0] = new TreePrototype();
        m_treeProtoTypes [0].prefab = m_tree0;

        m_treeProtoTypes [1] = new TreePrototype ();
        m_treeProtoTypes[1].prefab = m_tree1;

        terrain.terrainData.treePrototypes = m_treeProtoTypes;

        PerlinNoise m_treeNoise = new PerlinNoise(Random.Range(0,100));

        //ArrayList instances = new ArrayList();

        for(int x = 0; x < m_terrainSize; x += m_treeSpacing)
        {
            for (int z = 0; z < m_terrainSize; z += m_treeSpacing)
            {

                float unit = 1.0f / (m_terrainSize - 1);

                float offsetX = Random.value * unit * m_treeSpacing;
                float offsetZ = Random.value * unit * m_treeSpacing;

                float normX = x * unit + offsetX;
                float normZ = z * unit + offsetZ;

                // Get the steepness value at the normalized coordinate.
                float angle = terrain.terrainData.GetSteepness(normX, normZ);

                // Steepness is given as an angle, 0..90 degrees. Divide
                // by 90 to get an alpha blending value in the range 0..1.
                float frac = angle / 90.0f;

                if(frac < 0.45f) //make sure tree are not on steep slopes
                {
                    float worldPosX = x;
                    float worldPosZ = z;

                    float noise = m_treeNoise.FractalNoise2D(worldPosX, worldPosZ, 3, m_treeFrq, 1.0f);
                    float ht = terrain.terrainData.GetInterpolatedHeight(normX, normZ);

                    if(noise > 0.0f && ht < m_terrainHeight*0.4f)
                    {

                        TreeInstance temp = new TreeInstance();
                        temp.position = new Vector3(normX,ht,normZ);
                        temp.prototypeIndex = Random.Range (0, 2);
                        temp.widthScale = 1f;
                        temp.heightScale = 1f;
                        temp.color = Color.white;
                        temp.lightmapColor = Color.white;

                        terrain.AddTreeInstance(temp);
                    }
                }

            }
        }

        //terrain.terrainData.treeInstances = (TreeInstance[])instances.ToArray(typeof(TreeInstance));
        terrain.terrainData.SetHeights(0, 0, new float[,] { { } });
        terrain.Flush ();
    }
Example #22
0
        public override void Update(float deltaTime, Camera cam)
        {
            if (item.body == null || !item.body.Enabled)
            {
                return;
            }
            if (picker == null || !picker.HasEquippedItem(item))
            {
                if (Pusher != null)
                {
                    Pusher.Enabled = false;
                }
                IsActive = false;
                return;
            }

            Vector2 swing = Vector2.Zero;

            if (swingAmount != Vector2.Zero)
            {
                swingState += deltaTime;
                swingState %= 1.0f;
                if (SwingWhenHolding ||
                    (SwingWhenAiming && picker.IsKeyDown(InputType.Aim)) ||
                    (SwingWhenUsing && picker.IsKeyDown(InputType.Aim) && picker.IsKeyDown(InputType.Shoot)))
                {
                    swing = swingAmount * new Vector2(
                        PerlinNoise.GetPerlin(swingState * SwingSpeed * 0.1f, swingState * SwingSpeed * 0.1f) - 0.5f,
                        PerlinNoise.GetPerlin(swingState * SwingSpeed * 0.1f + 0.5f, swingState * SwingSpeed * 0.1f + 0.5f) - 0.5f);
                }
            }

            ApplyStatusEffects(ActionType.OnActive, deltaTime, picker);

            if (item.body.Dir != picker.AnimController.Dir)
            {
                Flip();
            }

            item.Submarine = picker.Submarine;

            if (picker.HasSelectedItem(item))
            {
                scaledHandlePos[0] = handlePos[0] * item.Scale;
                scaledHandlePos[1] = handlePos[1] * item.Scale;
                bool aim = picker.IsKeyDown(InputType.Aim) && aimPos != Vector2.Zero && (picker.SelectedConstruction == null || picker.SelectedConstruction.GetComponent <Ladder>() != null);
                picker.AnimController.HoldItem(deltaTime, item, scaledHandlePos, holdPos + swing, aimPos + swing, aim, holdAngle);
            }
            else
            {
                Limb equipLimb = null;
                if (picker.Inventory.IsInLimbSlot(item, InvSlotType.Headset) || picker.Inventory.IsInLimbSlot(item, InvSlotType.Head))
                {
                    equipLimb = picker.AnimController.GetLimb(LimbType.Head);
                }
                else if (picker.Inventory.IsInLimbSlot(item, InvSlotType.InnerClothes) ||
                         picker.Inventory.IsInLimbSlot(item, InvSlotType.OuterClothes))
                {
                    equipLimb = picker.AnimController.GetLimb(LimbType.Torso);
                }

                if (equipLimb != null)
                {
                    float itemAngle = (equipLimb.Rotation + holdAngle * picker.AnimController.Dir);

                    Matrix  itemTransfrom        = Matrix.CreateRotationZ(equipLimb.Rotation);
                    Vector2 transformedHandlePos = Vector2.Transform(handlePos[0] * item.Scale, itemTransfrom);

                    item.body.ResetDynamics();
                    item.SetTransform(equipLimb.SimPosition - transformedHandlePos, itemAngle);
                }
            }
        }
Example #23
0
    public static GeneratedTrack GenerateTrack(float length, float width, long seed)
    {
        float anglePeriod     = param_AnglePeriod;
        float angleAmplitude  = param_AngleAmplitude;
        float radiusPeriod    = param_RadiusPeriod;
        float radiusAmplitude = param_RadiusAmplitude;
        float radiusOffset    = param_RadiusOffset;

        // Segment Decider
        //
        // Decider works like this:
        //   If noise returns < -1, the segment is a straight
        //   If noise returns > 1, the segment is a turn
        //   Else, it is a combination of both
        //
        float segDecMin    = param_SegDecMin;
        float segDecMax    = param_SegDecMax;
        float segDecPeriod = param_SegDecPeriod;

        float modePeriod = param_ModePeriod;


        perlinNoise = new PerlinNoise(seed);
        GeneratedTrack track = new GeneratedTrack();

        track.Faulty = false;

        List <Circle> circles = new List <Circle>();

        circles.Add(new Circle(new Vector2(0f, 150f), 250f, true));
        circles.Add(new Circle(new Vector2(150f, -100f), 250f, true));
        circles.Add(new Circle(new Vector2(-150f, -100f), 250f, true));

        List <float> circleDirections = new List <float>();

        for (int i = 0; i < circles.Count; i++)
        {
            int i2 = (i + 1) % circles.Count;

            Vector2 c1Toc2   = circles[i2].Midpoint - circles[i].Midpoint;
            Vector2 c1ToLeft = (new Vector2(-c1Toc2.y, c1Toc2.x)).normalized * circles[i].Radius;
            Vector2 c2ToLeft = (new Vector2(-c1Toc2.y, c1Toc2.x)).normalized * circles[i2].Radius;

            Vector2 c1Outs = circles[i].Midpoint + c1ToLeft;
            Vector2 c2Outs = circles[i2].Midpoint + c2ToLeft;

            Vector2 vec = c2Outs - c1Outs;

            float zAngle          = Vector2.Angle(new Vector2(0f, 1f), vec);
            float xAngle          = Vector2.Angle(new Vector2(1f, 0f), vec);
            float circleDirection = zAngle;

            if (xAngle > 90f)
            {
                circleDirection = 360f - zAngle;
            }

            circleDirection = circleDirection - 90f;
            if (circleDirection < 0f)
            {
                circleDirection = 360f - circleDirection;
            }

            circleDirections.Add(circleDirection);
        }


        int angleStep   = 0;
        int radiusStep  = 0;
        int segmentStep = 0;

        int circleIndex = 0;

        float currentAngle = 0f;
        float startRadius  = perlinNoise.noise1(radiusStep * radiusPeriod) * radiusAmplitude + radiusOffset;

        Vector2 startPoint = new Vector2(Mathf.Sin((currentAngle * Mathf.PI) / 180f) * startRadius, Mathf.Cos((currentAngle * Mathf.PI) / 180f) * startRadius);

        while (true)
        {
            angleStep++;
            radiusStep++;
            segmentStep++;

            // Segment Decider is between [-1, 1]
            float segDec = perlinNoise.noise1(segmentStep * segDecPeriod) * ((Mathf.Abs(segDecMin) + Mathf.Abs(segDecMax)) / 2f);
            segDec = segDec + ((segDecMin + segDecMax) / 2f);
            segDec = segDec > 1f ? 1f : (segDec < -1f ? -1f : segDec);

            // Angle Delta between [0, angleAmplitude]
            float angleDelta = (perlinNoise.noise1(angleStep * anglePeriod) * 0.5f + 0.5f) * angleAmplitude;
            currentAngle += angleDelta;

            // Radius between [0, 2 * radiusAmplitude]
            float radius = perlinNoise.noise1(radiusStep * radiusPeriod) * radiusAmplitude + radiusOffset;

            // Mode is either PERFECT_PART_CIRCLES or BEZIER_SPLINES
            bool takeBezierSpline = false;

            if (generationMode == DiscreteGenerationMode.BEZIER_SPLINES)
            {
                takeBezierSpline = true;
            }
            else if (generationMode == DiscreteGenerationMode.PERFECT_PART_CIRCLES)
            {
                takeBezierSpline = false;
            }
            else
            {
                takeBezierSpline = perlinNoise.noise1(angleStep * modePeriod) >= 0f;
            }

            if (currentAngle >= circleDirections[circleIndex])
            {
                circleIndex++;
                if (circleIndex >= circles.Count)
                {
                    circleIndex = 0;
                }
            }


            Vector2 oldPoint;
            float   oldDirection;
            if (track.Elements.Length == 0)
            {
                oldPoint     = startPoint;
                oldDirection = Mathf.PI * 0.5f;
            }
            else
            {
                oldPoint     = new Vector2(track.Elements[track.Elements.Length - 1].EndPosition.x, track.Elements[track.Elements.Length - 1].EndPosition.z);
                oldDirection = track.Elements[track.Elements.Length - 1].EndDirection;
            }


            Vector2 point = new Vector2(Mathf.Sin((currentAngle * Mathf.PI) / 180f) * radius, Mathf.Cos((currentAngle * Mathf.PI) / 180f) * radius);

            point += circles[circleIndex].Midpoint;

            if (Vector2.Distance(point, oldPoint) < 4f)
            {
                Vector2 oldToP = (point - oldPoint).normalized * 4f;

                point = oldPoint + oldToP;
            }


            //Debug.Log("Iteration: " + angleStep);
            //Debug.Log("CurrentAngle: " + currentAngle);
            //Debug.Log("Radius: " + radius);
            //Debug.Log("SegDec: " + segDec);

            bool  fixedEndpointDirection = false;
            float endpointDirection      = Mathf.PI * 0.5f;
            float endpointWidth          = width;

            if (currentAngle >= 360f)
            {
                fixedEndpointDirection = true;

                point             = new Vector2(track.Elements[0].Position.x, track.Elements[0].Position.z);
                endpointDirection = track.Elements[0].Direction;
                endpointWidth     = track.Elements[0].WidthStart;
            }



            if (fixedEndpointDirection == false)
            {
                // Completely a turn
                if (segDec >= 1f)
                {
                    if (takeBezierSpline == false)
                    {
                        float[] radiusAndDegree = makeTurn(oldPoint, point, oldDirection);

                        float circleRadius = radiusAndDegree[0];
                        float circleDegree = radiusAndDegree[1];

                        GeneratedTurn turn = new GeneratedTurn(new Vector3(oldPoint.x, 0f, oldPoint.y), oldDirection, circleRadius, circleDegree, width);

                        Vector2 turnEndPoint = new Vector2(turn.EndPosition.x, turn.EndPosition.z);
                        if (Vector2.Distance(turnEndPoint, point) > 1f)
                        {
                            track.Faulty = true;
                            Debug.LogError("Too big distance");
                        }

                        track.AddElement(turn);
                    }
                    else
                    {
                        float[] radiusAndDegree = makeTurn(oldPoint, point, oldDirection);

                        float circleRadius = radiusAndDegree[0];
                        float circleDegree = radiusAndDegree[1];

                        GeneratedTurn turn = new GeneratedTurn(new Vector3(oldPoint.x, 0f, oldPoint.y), oldDirection, circleRadius, circleDegree, width);

                        float turnEndDirection = turn.EndDirection;

                        float interDirection = (perlinNoise.noise1(angleStep * anglePeriod) * 0.5f + 0.5f) * (oldDirection - turnEndDirection) + turnEndDirection;

                        GeneratedBezSpline turnSpline = new GeneratedBezSpline(new Vector3(oldPoint.x, 0f, oldPoint.y), oldDirection, new Vector3(point.x, 0f, point.y), interDirection, width, width);

                        track.AddElement(turnSpline);
                    }
                }

                // Part straight part turn
                else
                {
                    if (takeBezierSpline == false)
                    {
                        float maxWidth = width;
                        //TODO not only one width all the time

                        float minRadius = maxWidth + 0.8f;

                        float[] radiusAndDegree = makeTurn(oldPoint, point, oldDirection);

                        float circleRadius = radiusAndDegree[0];
                        float circleDegree = radiusAndDegree[1];

                        float maxRadius = circleRadius;

                        float circlePartRadius = (maxRadius - minRadius) * ((segDec + 1f) * 0.5f) + minRadius;

                        Vector2 circleMiddle = Vector2.zero;

                        float[] partcircleRadiusAndDegree = makeTurnFixedRadius(oldPoint, circlePartRadius, oldDirection, (circleDegree >= 0f), point);

                        float partcircleDegree   = partcircleRadiusAndDegree[0];
                        float partstraightLength = partcircleRadiusAndDegree[1];

                        GeneratedTurn turn = new GeneratedTurn(new Vector3(oldPoint.x, 0f, oldPoint.y), oldDirection, circlePartRadius, partcircleDegree, width);
                        track.AddElement(turn);

                        GeneratedStraight straight = new GeneratedStraight(turn.EndPosition, turn.EndDirection, partstraightLength, width);
                        //straight.AddCurb(new GeneratedCurb(0.1f, 0.9f, true, true, true));
                        track.AddElement(straight);


                        Vector2 bothEndPoint = new Vector2(straight.EndPosition.x, straight.EndPosition.z);
                        if (Vector2.Distance(bothEndPoint, point) > 1f)
                        {
                            Debug.LogError("Too big distance");
                            track.Faulty = true;
                        }
                    }
                    else
                    {
                        // Only straight
                        if (segDec <= -1f && track.Elements.Length > 0 && track.Elements[track.Elements.Length - 1].GetType() == typeof(GeneratedBezSpline))
                        {
                            float angleBetween = Vector2.Angle(new Vector2(0f, 1f), point - oldPoint);
                            float angleRight   = Vector2.Angle(new Vector2(1f, 0f), point - oldPoint);
                            if (angleRight > 90f)
                            {
                                angleBetween = 360f - angleBetween;
                            }
                            float radianOldEndDirection = (angleBetween * Mathf.PI) / 180f;

                            track.Elements[track.Elements.Length - 1].ForceEndDirection(radianOldEndDirection);

                            GeneratedStraight straight = new GeneratedStraight(oldPoint, radianOldEndDirection, Vector2.Distance(oldPoint, point), width);

                            track.AddElement(straight);
                        }

                        // Really part turn part straight
                        else
                        {
                            float maxWidth = width;
                            //TODO not only one width all the time

                            float minRadius = maxWidth + 0.8f;

                            float[] radiusAndDegree = makeTurn(oldPoint, point, oldDirection);

                            float circleRadius = radiusAndDegree[0];
                            float circleDegree = radiusAndDegree[1];

                            float maxRadius = circleRadius;

                            float circlePartRadius = (maxRadius - minRadius) * ((segDec + 1f) * 0.5f) + minRadius;

                            Vector2 circleMiddle = Vector2.zero;

                            float[] partcircleRadiusAndDegree = makeTurnFixedRadius(oldPoint, circlePartRadius, oldDirection, (circleDegree >= 0f), point);

                            float partcircleDegree   = partcircleRadiusAndDegree[0];
                            float partstraightLength = partcircleRadiusAndDegree[1];

                            GeneratedTurn turn = new GeneratedTurn(new Vector3(oldPoint.x, 0f, oldPoint.y), oldDirection, circlePartRadius, partcircleDegree, width);
                            //track.AddElement(turn);

                            float turnEndDirection = turn.EndDirection;

                            GeneratedBezSpline turnSpline = new GeneratedBezSpline(new Vector3(oldPoint.x, 0f, oldPoint.y), oldDirection, turn.EndPosition, turnEndDirection, width, width);
                            track.AddElement(turnSpline);

                            GeneratedStraight straight = new GeneratedStraight(turn.EndPosition, turnEndDirection, Vector2.Distance(point, new Vector2(turn.EndPosition.x, turn.EndPosition.z)), width);
                            //straight.AddCurb(new GeneratedCurb(0.1f, 0.9f, true, true, true));
                            track.AddElement(straight);


                            Vector2 bothEndPoint = new Vector2(straight.EndPosition.x, straight.EndPosition.z);
                            if (Vector2.Distance(bothEndPoint, point) > 1f)
                            {
                                track.Faulty = true;
                                Debug.LogError("Too big distance");
                            }
                        }
                    }
                }
            }

            // Drive to a fixed endpoint
            else
            {
                // Two turns one straight
                if (false)
                {
                    float[] angleStraightAndAngle = makeTwoTurnsOneStraight(oldPoint, point, oldDirection, endpointDirection, 1f, 0.5f, Mathf.Max(endpointWidth, width));
                    float   circle1Radius         = angleStraightAndAngle[0];
                    float   circle1Degree         = angleStraightAndAngle[1];
                    float   straightLegnth        = angleStraightAndAngle[2];
                    float   circle2Radius         = angleStraightAndAngle[3];
                    float   circle2Degree         = angleStraightAndAngle[4];

                    if (circle1Radius == 0f && circle1Degree == 0f && straightLegnth == 0f && circle2Degree == 0f && circle2Radius == 0f)
                    {
                        track.Faulty = true;
                    }
                    else
                    {
                        GeneratedTurn turn = new GeneratedTurn(new Vector3(oldPoint.x, 0f, oldPoint.y), oldDirection, circle1Radius, circle1Degree, width);
                        track.AddElement(turn);

                        GeneratedStraight straight = new GeneratedStraight(turn.EndPosition, turn.EndDirection, straightLegnth, width);
                        track.AddElement(straight);

                        GeneratedTurn turn2 = new GeneratedTurn(straight.EndPosition, straight.EndDirection, circle2Radius, circle2Degree, width);
                        track.AddElement(turn2);
                    }
                }


                // Do it with Beziers
                else
                {
                    GeneratedBezSpline turnSpline = new GeneratedBezSpline(new Vector3(oldPoint.x, 0f, oldPoint.y), oldDirection, new Vector3(point.x, 0f, point.y), endpointDirection, width, width);

                    track.AddElement(turnSpline);
                }
            }



            if (currentAngle >= 360f)
            {
                break;
            }
        }

        return(track);
    }
Example #24
0
 public MarchingCubesRecursive(int seed)
 {
     noise = new PerlinNoise(seed);
 }
Example #25
0
 //All of these sample functions create the noise needed for a certain effect, for example caves, moutains etc.
 //The last three values in the noise functions are octaves, frequency and amplitude.
 //More ocatves will create more detail but is slower.
 //Higher/lower frquency will 'strech/shrink' out the noise.
 //Amplitude defines roughly the range of the noise, ie amp = 1.0 means roughly -1.0 to +1.0 * range of noise
 //The range of noise is 0.5 for 1D, 0.75 for 2D and 1.5 for 3D
 float SampleMountains(float x, float z, PerlinNoise perlin)
 {
     //This creates the noise used for the mountains. It used something called
     //domain warping. Domain warping is basically offseting the position used for the noise by
     //another noise value. It tends to create a warped effect that looks nice.
     float w = perlin.FractalNoise2D(x, z, 3, 120.0f, 32.0f);
     //Clamp noise to 0 so mountains only occur where there is a positive value
     //The last value (32.0f) is the amp that defines (roughly) the maximum mountaion height
     //Change this to create high/lower mountains
     return Mathf.Min(0.0f, perlin.FractalNoise2D(x+w, z+w, 6, 120.0f, 32.0f) );
 }
Example #26
0
	void Start() 
	{
		m_groundNoise = new PerlinNoise(m_groundSeed);
		m_mountainNoise = new PerlinNoise(m_mountainSeed);
		m_treeNoise = new PerlinNoise(m_treeSeed);
		m_detailNoise = new PerlinNoise(m_detailSeed);
		
		if(!Mathf.IsPowerOfTwo(m_heightMapSize-1))
		{
			Debug.Log("TerrianGenerator::Start - height map size must be pow2+1 number");
			m_heightMapSize = Mathf.ClosestPowerOfTwo(m_heightMapSize)+1;
		}
		
		if(!Mathf.IsPowerOfTwo(m_alphaMapSize))
		{
			Debug.Log("TerrianGenerator::Start - Alpha map size must be pow2 number");
			m_alphaMapSize = Mathf.ClosestPowerOfTwo(m_alphaMapSize);
		}
		
		if(!Mathf.IsPowerOfTwo(m_detailMapSize))
		{
			Debug.Log("TerrianGenerator::Start - Detail map size must be pow2 number");
			m_detailMapSize = Mathf.ClosestPowerOfTwo(m_detailMapSize);
		}
		
		if(m_detailResolutionPerPatch < 8)
		{
			Debug.Log("TerrianGenerator::Start - Detail resolution per patch must be >= 8, changing to 8");
			m_detailResolutionPerPatch = 8;
		}
		
		float[,] htmap = new float[m_heightMapSize,m_heightMapSize];
		
		m_terrain = new Terrain[m_tilesX,m_tilesZ];
		
		//this will center terrain at origin
		m_offset = new Vector2(-m_terrainSize*m_tilesX*0.5f, -m_terrainSize*m_tilesZ*0.5f);
		
		CreateProtoTypes();
		
		for(int x = 0; x < m_tilesX; x++)
		{
			for(int z = 0; z < m_tilesZ; z++)
			{
				FillHeights(htmap, x, z);
				
				TerrainData terrainData = new TerrainData();

				terrainData.heightmapResolution = m_heightMapSize;
				terrainData.SetHeights(0, 0, htmap);
				terrainData.size = new Vector3(m_terrainSize, m_terrainHeight, m_terrainSize);
				terrainData.splatPrototypes = m_splatPrototypes;
				terrainData.treePrototypes = m_treeProtoTypes;  
				terrainData.detailPrototypes = m_detailProtoTypes;
				
				FillAlphaMap(terrainData);
	
				m_terrain[x,z] = Terrain.CreateTerrainGameObject(terrainData).GetComponent<Terrain>();
				m_terrain[x,z].transform.position = new Vector3(m_terrainSize*x + m_offset.x, 0, m_terrainSize*z + m_offset.y);
				m_terrain[x,z].heightmapPixelError = m_pixelMapError;
				m_terrain[x,z].basemapDistance = m_baseMapDist;
				
				//disable this for better frame rate
				m_terrain[x,z].castShadows = false;
				
				FillTreeInstances(m_terrain[x,z], x, z);
				FillDetailMap(m_terrain[x,z], x, z);
			}
		}
		
		//Set the neighbours of terrain to remove seams.
		for(int x = 0; x < m_tilesX; x++)
		{
			for(int z = 0; z < m_tilesZ; z++)
			{
				Terrain right = null;
				Terrain left = null;
				Terrain bottom = null;
				Terrain top = null;
				
				if(x > 0) left = m_terrain[(x-1),z];
				if(x < m_tilesX-1) right = m_terrain[(x+1),z];
				
				if(z > 0) bottom = m_terrain[x,(z-1)];
				if(z < m_tilesZ-1) top = m_terrain[x,(z+1)];
				
				m_terrain[x,z].SetNeighbors(left, top, right, bottom);
	
			}
		}
		
	}
Example #27
0
        public void generateProcedural()
        {
            //TODO: remove cast
            World world = (World)this.world;

            if (generated)
            {
                Logger.log("Procedural chunk generation threading error");
            }
            generated = true;

            random = new Random(location.X * 500 + location.Y);
            Dictionary <Point, Decoration> queuedDecorations = new Dictionary <Point, Decoration>();
            int   terrainMultipler = world.decorator.getTerrainMultiplier();
            float caveThreshold    = world.decorator.caveThreshold;

            PerlinNoise perlin = world.noise;

            for (int x = 0; x < tilesPerChunk; x++)
            {
                float groundLevel = perlin.octavePerlin1D((float)(location.X * tilesPerChunk + x) / 25) * terrainMultipler;
                for (int y = 0; y < tilesPerChunk; y++)
                {
                    if ((location.Y * tilesPerChunk + y) > groundLevel)
                    {
                        float current = perlin.octavePerlin((float)(location.X * tilesPerChunk + x) / 25, (float)(location.Y * tilesPerChunk + y) / 25);

                        if (current > caveThreshold || location.X == 0 || location.X == -1)
                        {
                            tiles[x, y]           = TileTypeReferencer.DIRT;
                            backgroundTiles[x, y] = TileTypeReferencer.CAVE;
                        }
                        else
                        {
                            backgroundTiles[x, y] = TileTypeReferencer.CAVE;
                            tiles[x, y]           = TileTypeReferencer.AIR;
                            if ((location.Y * tilesPerChunk + y) > groundLevel + 5 && random.NextDouble() < .23 && perlin.octavePerlin((float)(location.X * tilesPerChunk + x) / 25, (float)(location.Y * tilesPerChunk + y + 1) / 25) > caveThreshold)
                            {
                                Decoration foliage = world.decorator.getSubTerranianFoliage(this, x, y);

                                if (new Rectangle(0, 0, tilesPerChunk, tilesPerChunk).Contains(new Rectangle(x + foliage.box.X, y + foliage.box.Y, foliage.box.Width, foliage.box.Height)))
                                {
                                    queuedDecorations.Add(new Point(x, y), foliage);
                                }
                            }
                        }
                    }
                    else
                    {
                        if ((location.Y * tilesPerChunk + y) <= groundLevel + 1 && (location.Y * tilesPerChunk + y) > groundLevel - 1)
                        {
                            float currentDown = perlin.octavePerlin((float)(location.X * tilesPerChunk + x) / 25, (float)(location.Y * tilesPerChunk + y + 1) / 25);
                            if (currentDown > caveThreshold)
                            {
                                backgroundTiles[x, y] = world.decorator.shrubManager.grass;
                                if (random.NextDouble() < world.decorator.foliageChance)
                                {
                                    Decoration foliage = world.decorator.getFoliage(this, x, y);

                                    if (new Rectangle(0, 0, tilesPerChunk, tilesPerChunk).Contains(new Rectangle(x + foliage.box.X, y + foliage.box.Y, foliage.box.Width, foliage.box.Height)))
                                    {
                                        queuedDecorations.Add(new Point(x, y), foliage);
                                    }
                                }
                            }
                        }
                        tiles[x, y] = TileTypeReferencer.AIR;
                    }
                }
            }

            foreach (Point point in queuedDecorations.Keys)
            {
                Decoration decoration = queuedDecorations[point];
                for (int nx = 0; nx < decoration.box.Width; nx++)
                {
                    for (int ny = 0; ny < decoration.box.Height; ny++)
                    {
                        if (decoration.decorationMap[nx, ny] != null)
                        {
                            tiles[point.X + decoration.box.X + nx, point.Y + decoration.box.Y + ny] = decoration.decorationMap[nx, ny];
                        }

                        if (decoration.backgroundDecorationMap != null && decoration.backgroundDecorationMap[nx, ny] != null)
                        {
                            backgroundTiles[point.X + decoration.box.X + nx, point.Y + decoration.box.Y + ny] = decoration.backgroundDecorationMap[nx, ny];
                        }
                    }
                }
            }

            reBuildCollisions();
        }
 public RandomLandGenerator()
 {
     InitializeComponent();
     this._perlinNoise   = new PerlinNoise();
     this._kochLikeNoise = new KochLikeNoise();
 }
 public ChainLightningRenderer(RenderingDevice device, MdfMaterialFactory materialFactory, PerlinNoise noise)
     : base(device, materialFactory, noise, MaxLineSegments, "LightningBolt")
 {
     // The line's "surface" will always be facing up
     InitVertices(Vector3.UnitY);
 }
 public ChainLightningRenderer(PerlinNoise noise) : this(Tig.RenderingDevice, Tig.MdfFactory, noise)
 {
 }
Example #31
0
        public override void Update(float deltaTime, Camera cam)
        {
            if (item.AiTarget != null)
            {
                UpdateAITarget(item.AiTarget);
            }
            UpdateOnActiveEffects(deltaTime);

#if CLIENT
            light.ParentSub = item.Submarine;
#endif
            if (item.Container != null)
            {
                SetLightSourceState(false, 0.0f);
                return;
            }
#if CLIENT
            light.Position = ParentBody != null ? ParentBody.Position : item.Position;
#endif

            PhysicsBody body = ParentBody ?? item.body;
            if (body != null)
            {
#if CLIENT
                light.Rotation          = body.Dir > 0.0f ? body.DrawRotation : body.DrawRotation - MathHelper.Pi;
                light.LightSpriteEffect = (body.Dir > 0.0f) ? SpriteEffects.None : SpriteEffects.FlipVertically;
#endif
                if (!body.Enabled)
                {
                    SetLightSourceState(false, 0.0f);
                    return;
                }
            }
            else
            {
#if CLIENT
                light.Rotation = -Rotation;
#endif
            }

            currPowerConsumption = powerConsumption;
            if (Rand.Range(0.0f, 1.0f) < 0.05f && Voltage < Rand.Range(0.0f, MinVoltage))
            {
#if CLIENT
                if (Voltage > 0.1f)
                {
                    SoundPlayer.PlaySound("zap", item.WorldPosition, hullGuess: item.CurrentHull);
                }
#endif
                lightBrightness = 0.0f;
            }
            else
            {
                lightBrightness = MathHelper.Lerp(lightBrightness, powerConsumption <= 0.0f ? 1.0f : Math.Min(Voltage, 1.0f), 0.1f);
            }

            if (blinkFrequency > 0.0f)
            {
                blinkTimer = (blinkTimer + deltaTime * blinkFrequency) % 1.0f;
            }

            if (blinkTimer > 0.5f)
            {
                SetLightSourceState(false, lightBrightness);
            }
            else
            {
                flickerState += deltaTime * FlickerSpeed;
                flickerState %= 255;
                float noise = PerlinNoise.GetPerlin(flickerState, flickerState * 0.5f) * flicker;
                SetLightSourceState(true, lightBrightness * (1.0f - noise));
            }

            if (powerIn == null && powerConsumption > 0.0f)
            {
                Voltage -= deltaTime;
            }
        }
Example #32
0
    public void GenerateMap()
    {
        System.Random random     = new System.Random();
        int           RandomSeed = random.Next(0, 100000);

        System.Random local_seed = new System.Random(RandomSeed);
        int           int_seed   = local_seed.Next(-100000, 100000);

        float[,] NoiseMap;

        if (this.noiseSelector == NoiseSelector.Perlin)
        {
            NoiseMap = PerlinNoise.PerlinNoiseMapGenerator(this.mapWidth, this.mapHeigth, int_seed, this.noiseScale, octaves, persistance, lacunarity, offset);
        }
        else if (this.noiseSelector == NoiseSelector.Simplex)
        {
            NoiseMap = SimplexNoise.SimplexNoiseMapGenerator(this.mapWidth, this.mapHeigth, int_seed, octaves, offset);
        }
        else if (this.noiseSelector == NoiseSelector.Value)
        {
            NoiseMap = ValueNoise.ValueNoiseMapGenerator(this.mapWidth, this.mapHeigth, int_seed, this.noiseScale);
        }
        else if (this.noiseSelector == NoiseSelector.Voronoi)
        {
            NoiseMap = VoronoiNoise.ValueNoiseMapGenerator(this.mapWidth, this.mapHeigth, int_seed, this.noiseScale, octaves, persistance);
        }
        else if (this.noiseSelector == NoiseSelector.PerlinVoronoi)
        {
            float[,] perlinMap  = PerlinNoise.PerlinNoiseMapGenerator(this.mapWidth, this.mapHeigth, int_seed, this.noiseScale, octaves, persistance, lacunarity, offset);
            float[,] voronoiMap = VoronoiNoise.ValueNoiseMapGenerator(this.mapWidth, this.mapHeigth, int_seed, this.noiseScale, octaves, persistance);
            NoiseMap            = Convolution.ConvolutionMapGenerator(this.mapWidth, this.mapHeigth, perlinMap, voronoiMap);
        }
        else
        {
            //default: perlin noise
            NoiseMap = PerlinNoise.PerlinNoiseMapGenerator(this.mapWidth, this.mapHeigth, int_seed, this.noiseScale, octaves, persistance, lacunarity, offset);
        }

        Color[] HeighMap = new Color[mapWidth * mapHeigth];
        for (int y = 0; y < mapHeigth; y++)
        {
            for (int x = 0; x < mapWidth; x++)
            {
                float currentHeigth = NoiseMap[x, y];
                for (int i = 0; i < regions.Length; i++)
                {
                    if (currentHeigth <= regions[i].heigth)
                    {
                        HeighMap[y * mapWidth + x] = regions[i].colour;
                        break;
                    }
                }
            }
        }

        MapDisplay display = FindObjectOfType <MapDisplay>();

        if (drawMode == DrawMode.NoiseMap)
        {
            display.DrawTexture(TextureGenerator.TextureFromHeightMap(NoiseMap));
        }
        else if (drawMode == DrawMode.HeighMap)
        {
            display.DrawTexture(TextureGenerator.TextureFromHeighMap(HeighMap, mapWidth, mapHeigth));
        }
    }
Example #33
0
	void Start () {
		noise = new PerlinNoise();
		noise.baseOctave = noiseBaseOctave;
		noise.weights = noiseWeights;
		noise.Init();

		chunkResolution = (int)Math.Pow(2, chunkExponent) + 1;
		chunkWidth = chunkResolution * chunkScale;

		chunks = new Hashtable();
		heightmapQueue = Queue.Synchronized(new Queue());

		reverseThermalEroder = new ThermalTerrainErosion();
		reverseThermalEroder.talus = this.reverseErosionTalus;
		reverseThermalEroder.strength = this.reverseErosionStrength;
		reverseThermalEroder.reverse = true;
		reverseThermalEroder.reverseTalusCutoff = this.reverseErosionReverseTalusCutoff ;
		reverseThermalEroder.iterations = this.reverseErosionIterations;

		thermalEroder = new ThermalTerrainErosion();
		thermalEroder.talus = this.thermalErosionTalus;
		thermalEroder.strength = this.thermalErosionStrength;
		thermalEroder.reverse = false;
		thermalEroder.iterations = this.thermalErosionIterations;

		hydraulicEroder = new HydraulicTerrainErosion();
		hydraulicEroder.rainfallAmount = hydraulicErosionRainfallAmount; // kr
		hydraulicEroder.evaporationRatio = hydraulicErosionEvaporationRatio; // ke
		hydraulicEroder.sedimentCapacity = hydraulicErosionSedimentCapacity; // kc
		hydraulicEroder.soilSolubility = hydraulicErosionSoilSolubility; // ks
		hydraulicEroder.rainAltitude = hydraulicErosionRainAltitude;
		hydraulicEroder.rainFalloff = hydraulicErosionRainFalloff;
		hydraulicEroder.iterations = hydraulicErosionIterations;

		texturer = new Texturer();
		texturer.slopeValue = slopeValue;
		texturer.mountainPeekHeight = mountainPeekHeight;
		texturer.waterHeight = waterHeight;
		splats = new SplatPrototype[diffuses.Length];

		for (var i = 0; i < diffuses.Length; i++) {
			splats[i] = new SplatPrototype();
			splats[i].texture = diffuses[i];
			splats[i].normalMap = normals[i];
			splats[i].tileSize = new Vector2(5, 5);
		}

		ensureChunk(new ChunkCoord(0, 0), false);
		ensureChunk(new ChunkCoord(-1, -1), true);
		ensureChunk(new ChunkCoord(0, -1), true);
		ensureChunk(new ChunkCoord(-1, 0), true);
	}
Example #34
0
        public void generateProceduralCenote()
        {
            //TODO: remove cast
            World world = (World)this.world;

            if (generated)
            {
                Logger.log("Procedural chunk generation threading error");
            }
            generated = true;

            random = new Random(location.X * 500 + location.Y);
            Dictionary <Point, Decoration> queuedDecorations = new Dictionary <Point, Decoration>();
            int   terrainMultipler = world.decorator.getTerrainMultiplier();
            float caveThreshold    = world.decorator.caveThreshold;
            float waterLevel       = world.decorator.waterLevel;

            PerlinNoise perlin = world.noise;

            for (int x = 0; x < tilesPerChunk; x++)
            {
                float groundLevel  = perlin.octavePerlin1D((float)(location.X * tilesPerChunk + x) / 25) * terrainMultipler;
                float cielingLevel = Math.Min(groundLevel - 5 + perlin.octavePerlin1D((float)(location.X * tilesPerChunk + x + 200) / 25) * terrainMultipler, groundLevel - 5);

                for (int y = 0; y < tilesPerChunk; y++)
                {
                    float totalY = (location.Y * tilesPerChunk + y);
                    if (totalY > groundLevel || totalY < cielingLevel)
                    {
                        float current = perlin.octavePerlin((float)(location.X * tilesPerChunk + x) / 25, (float)(location.Y * tilesPerChunk + y) / 25);

                        if (current > caveThreshold || location.X == 0 || location.X == -1)
                        {
                            tiles[x, y] = TileTypeReferencer.DIRT;
                        }
                        else
                        {
                            if (totalY > waterLevel)
                            {
                                tiles[x, y] = TileTypeReferencer.WATER;
                            }
                            else
                            {
                                tiles[x, y] = TileTypeReferencer.AIR;
                            }
                        }
                    }
                    else
                    {
                        if (totalY > waterLevel)
                        {
                            tiles[x, y] = TileTypeReferencer.WATER;
                        }
                        else
                        {
                            tiles[x, y] = TileTypeReferencer.AIR;
                        }
                    }

                    //coat the floor in floor
                    if (tiles[x, y] == TileTypeReferencer.AIR)
                    {
                        float currentDown = perlin.octavePerlin((float)(location.X * tilesPerChunk + x) / 25, (float)(location.Y * tilesPerChunk + y + 1) / 25);
                        if (currentDown > caveThreshold && (totalY + 1 > groundLevel || totalY + 1 < cielingLevel) && totalY <= waterLevel)
                        {
                            tiles[x, y] = TileTypeReferencer.CAVE_FLOOR;

                            if (random.NextDouble() < world.decorator.foliageChance)
                            {
                                Decoration foliage = world.decorator.getFoliage(this, x, y);

                                if (new Rectangle(0, 0, tilesPerChunk, tilesPerChunk).Contains(new Rectangle(x + foliage.box.X, y + foliage.box.Y, foliage.box.Width, foliage.box.Height)))
                                {
                                    queuedDecorations.Add(new Point(x, y), foliage);
                                }
                            }
                        }
                    }

                    backgroundTiles[x, y] = TileTypeReferencer.CAVE;
                }
            }

            foreach (Point point in queuedDecorations.Keys)
            {
                Decoration decoration = queuedDecorations[point];
                for (int nx = 0; nx < decoration.box.Width; nx++)
                {
                    for (int ny = 0; ny < decoration.box.Height; ny++)
                    {
                        if (decoration.decorationMap[nx, ny] != null)
                        {
                            tiles[point.X + decoration.box.X + nx, point.Y + decoration.box.Y + ny] = decoration.decorationMap[nx, ny];
                        }

                        if (decoration.backgroundDecorationMap != null && decoration.backgroundDecorationMap[nx, ny] != null)
                        {
                            backgroundTiles[point.X + decoration.box.X + nx, point.Y + decoration.box.Y + ny] = decoration.backgroundDecorationMap[nx, ny];
                        }
                    }
                }
            }

            reBuildCollisions();
        }
Example #35
0
    public void CreateVoxels(PerlinNoise surfacePerlin)
    {
        //float startTime = Time.realtimeSinceStartup;

        //Creates the data the mesh is created form. Fills m_voxels with values between -1 and 1 where
        //-1 is a soild voxel and 1 is a empty voxel.

        int w = m_voxels.GetLength(0);
        int h = m_voxels.GetLength(1);
        int l = m_voxels.GetLength(2);

        for(int x = 0; x < w; x++)
        {
            for(int z = 0; z < l; z++)
            {
                //world pos is the voxels position plus the voxel chunks position
                float worldX = x+m_pos.x;
                float worldZ = z+m_pos.z;

                float groundHt = SampleGround(worldX, worldZ, surfacePerlin);

                float mountainHt = SampleMountains(worldX, worldZ, surfacePerlin);

                float ht = mountainHt + groundHt;

                for(int y = 0; y < h; y++)
                {
                    float worldY = y+m_pos.y-m_surfaceLevel;

                    //If we take the heigth value and add the world
                    //the voxels will change from positiove to negative where the surface cuts through the voxel chunk
                    m_voxels[x,y,z] = Mathf.Clamp(ht + worldY , -1.0f, 1.0f);

                    //This fades the voxel value so the caves never appear more than 16 units from
                    //the surface level.
                    float fade = 1.0f - Mathf.Clamp01(Mathf.Max(0.0f, worldY)/16.0f);

                    //m_voxels[x,y,z] += caveHt * fade;

                    m_voxels[x,y,z] = Mathf.Clamp(m_voxels[x,y,z], -1.0f, 1.0f);
                }
            }
        }

        //Debug.Log("Create voxels time = " + (Time.realtimeSinceStartup-startTime).ToString() );
    }
Example #36
0
 partial void UpdateProjSpecific(float deltaTime)
 {
     if (shakeTimer > 0.0f)
     {
         shakeTimer -= deltaTime;
         Vector2 noisePos = new Vector2((float)PerlinNoise.CalculatePerlin(shakeTimer * 10.0f, shakeTimer * 10.0f, 0) - 0.5f, (float)PerlinNoise.CalculatePerlin(shakeTimer * 10.0f, shakeTimer * 10.0f, 0.5f) - 0.5f);
         shakePos = noisePos * shake * 2.0f;
         shake    = Math.Min(shake, shakeTimer * 10.0f);
     }
     else
     {
         shakePos = Vector2.Zero;
     }
 }
Example #37
0
        public override void OnCreate()
        {
            GameApplication.SetLogger("Logs", "log");
            GameApplication.Log(LogEntryType.Debug, "GameWindow Created!", true);
            this.SetTextureInterpolationMode(System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor);
            testGameObj.Transform.Place(30, 30);
            testGameObj.Transform.SetSize(32, 32);
            Texture bg = new Texture(Image.FromFile(@"G:\Родион\Images\_PNG\12.png"), TextureLayout.Default);

            scene1.BackgroundTexture = bg;
            scene1.LightValue        = 0.8f;
            Audio        audio        = Audio.FromFile(@"D:\Родион\Desktop\testAssets\aud.wav");
            AudioChannel audioChannel = new AudioChannel("test", audio);
            Texture      texture      = new Texture(Image.FromFile(@"D:\Родион\VS\MyGame2\resources\raw\maps\textures\overworld_base_river.png"), TextureLayout.Default);
            Texture      texturetiled = new Texture(Image.FromFile(@"D:\Родион\VS\MyGame2\resources\raw\maps\textures\overworld_base_river.png"), TextureLayout.Tile);

            testGameObj.SetTexture(texture);
            testGameObj.CollisionBox.SetCollisionBox(0, 0, 32, 32);
            Objs.AddGameObject(testGameObj);
            testGameObj1.Transform.Place(80, 30);
            testGameObj1.Transform.SetSize(32, 32);
            testGameObj1.CollisionBox.SetCollisionBox(0, 0, 32, 32);
            testGameObj1.SetTexture(texture);
            Animation animation = new Animation(new Texture(Image.FromFile(@"D:\Родион\Desktop\testAssets\anim.png"), TextureLayout.Stretch), 6, 10, 32);

            testGameObj.Animation = animation;
            testGameObj.Animate();
            cameraBinded.Transform.Place((scene1.Width / 2) - (cameraBinded.Width / 2), (scene1.Height / 2) - (cameraBinded.Height / 2));
            cameraBinded.Transform.SetSize(48, 48);
            cameraBinded.SetTexture(texturetiled);
            cameraBinded.CollisionBox.SetCollisionBox(2, 2, 28, 28);
            Objs.AddGameObject(testGameObj);
            Objs.AddGameObject(testGameObj1);
            Objs.AddGameObject(cameraBinded);
            Texture grass = Texture.FromFile(@"D:\Родион\VS\MyGame2\resources\raw\maps\textures\overworld_map_base_grass.png", TextureLayout.Default);

            for (int x = 0; x < 20; x++)
            {
                for (int y = 0; y < 20; y++)
                {
                    Terrain.AddGameObject(new GrassObject(grass, x * 16, y * 16));
                }
            }
            TestObj tobj = new TestObj(cameraBinded);

            Objs.AddGameObject(tobj);
            TestUIControl control   = new TestUIControl();
            Texture       buttonTex = new Texture(Image.FromFile(@"D:\Родион\fankit\TestButtonTexture.png"), TextureLayout.Stretch);
            UIButton      button    = new UIButton(100, 32, buttonTex, 32);

            scene1.AddUIControl(control);
            button.Transform.Place(100, 100);
            scene1.AddUIControl(button);
            scene1.AddGameLayer(0, Terrain);
            scene1.AddGameLayer(1, Objs);
            //cameraBinded.IsCameraSticked = true;
            Coroutine coroutine = new Coroutine(new CoroutineMethod(() =>
            {
                this.Invoke(new Action(() =>
                {
                    Title = "GameWindow | Second: {tick}";
                    Title = Title.Replace("{tick}", DateTime.Now.Second.ToString());
                }));
            }), "Test Coroutine");

            audioChannel.ChannelVolume = 0.1f;
            audioChannel.Play();
            double[,] perlinData = new double[16, 16];
            int xArr = 0, yArr = 0;

            for (double x = 0; x < 1.0d; x += 0.0625d)
            {
                for (double y = 0; y < 1.0d; y += 0.0625d)
                {
                    perlinData[xArr, yArr] = new PerlinNoise().GetNoiseData(x, y, 0);
                    yArr++;
                }
                xArr++;
                yArr = 0;
            }
            for (int x = 0; x < 16; x++)
            {
                string arrCtor = "";
                for (int y = 0; y < 16; y++)
                {
                    arrCtor += Math.Round(perlinData[x, y], 2) + " ";
                }
                GameApplication.Log(LogEntryType.Info, arrCtor);
            }
            coroutine.StartCoroutine();
        }
Example #38
0
 public void RefreshMap(PerlinNoise heightMap)
 {
     this.heightMap = heightMap;
 }
Example #39
0
    void Awake()
    {
        pixelAvgs = new float[img.width, img.height];
        xSize     = img.width;
        ySize     = img.height;
        //pixelAvgs = new float[xSize, ySize];
        Color c = img.GetPixel(0, 0);

        hi = (c.r + c.g + c.b) / 3f;
        lo = (c.r + c.g + c.b) / 3f;
        for (int y = 0; y < ySize; y++)
        {
            for (int x = 0; x < xSize; x++)
            {
                c = img.GetPixel(x, y);
                pixelAvgs[x, y] = (c.r + c.g + c.b) / 3f;
                if (pixelAvgs[x, y] < lo)
                {
                    lo = pixelAvgs[x, y];
                }
                if (pixelAvgs[x, y] > hi)
                {
                    hi = pixelAvgs[x, y];
                }
                avgColor += new Color(c.r / (float)(xSize * ySize), c.g / (float)(xSize * ySize), c.b / (float)(xSize * ySize));
                //pixelAvgs[y, x] = Mathf.PerlinNoise(((float)x) * perlinMult + perlinOffset, ((float)y) * perlinMult + perlinOffset);
            }
        }

        float centColor = (avgColor.r + avgColor.g + avgColor.b) / 3f;

        hiColor = avgColor * hi;
        loColor = (avgColor * lo + avgColor * 2f) / 2f;

        float xft = 0;

        for (int y = 0; y < ySize; y++)
        {
            float xf = 0;
            for (int x = 1; x < xSize; x++)
            {
                xf += Mathf.Abs(pixelAvgs[x, y] - pixelAvgs[x - 1, y]) * ((xSize / 2.0f) / xSize);
            }
            xft += xf * ((ySize / 2.0f) / ySize);
        }
        print(xft);

        float yft = 0;

        for (int x = 0; x < xSize; x++)
        {
            float yf = 0;
            for (int y = 1; y < ySize; y++)
            {
                yf += Mathf.Abs(pixelAvgs[x, y] - pixelAvgs[x, y - 1]) * ((ySize / 2.0f) / ySize);
            }
            yft += yf * ((xSize / 2.0f) / xSize);
        }
        print(yft);

        float ft = (xft + yft) / (.2f * xSize * ySize);

        print(ft);

        outTexture = new Texture2D(xSize, ySize);

        Noise sn = new SimplexNoise(1, ft);
        Noise pn = new PerlinNoise(1, ft);
        Noise vn = new ValueNoise(1, 1);

        for (int y = 0; y < ySize; y++)
        {
            for (int x = 0; x < xSize; x++)
            {
                float p = (sn.Sample2D(((float)x) + perlinOffset, ((float)y) * 2f + perlinOffset) + sn.Sample2D(((float)x) * 2f + perlinOffset, ((float)y) * 4f + perlinOffset) + sn.Sample2D(((float)x) * 4f + perlinOffset, ((float)y) * 8f + perlinOffset)) / 3f;
                if (p > .5f)
                {
                    c = Color.Lerp(avgColor, hiColor, (p - .5f) * 2f);
                }
                else
                {
                    c = Color.Lerp(loColor, avgColor, p * 2f);
                }
                outTexture.SetPixel(x, y, c);
            }
        }
        outTexture.Apply();

        imgmat.mainTexture = outTexture;
    }
Example #40
0
        public void NoiseIsPeriodicWith256()
        {
            Random random = new Random(1234567);

            for (int i = 0; i < 100; i++)
            {
                var v = random.NextVector4D(-1000, 1000);

                Assert.IsTrue(Numeric.AreEqual(PerlinNoise.Compute(v.X), PerlinNoise.Compute(v.X - 256)));
                Assert.IsTrue(Numeric.AreEqual(PerlinNoise.Compute(v.X), PerlinNoise.Compute(v.X + 256)));

                Assert.IsTrue(Numeric.AreEqual(PerlinNoise.Compute(v.X, v.Y), PerlinNoise.Compute(v.X - 256, v.Y - 256)));
                Assert.IsTrue(Numeric.AreEqual(PerlinNoise.Compute(v.X, v.Y), PerlinNoise.Compute(v.X + 256, v.Y + 256)));

                Assert.IsTrue(Numeric.AreEqual(PerlinNoise.Compute(v.X, v.Y, v.Z), PerlinNoise.Compute(v.X - 256, v.Y - 256, v.Z - 256)));
                Assert.IsTrue(Numeric.AreEqual(PerlinNoise.Compute(v.X, v.Y, v.Z), PerlinNoise.Compute(v.X + 256, v.Y + 256, v.Z + 256)));

                Assert.IsTrue(Numeric.AreEqual(PerlinNoise.Compute(v.X, v.Y, v.Z, v.W), PerlinNoise.Compute(v.X - 256, v.Y - 256, v.Z - 256, v.W - 256)));
                Assert.IsTrue(Numeric.AreEqual(PerlinNoise.Compute(v.X, v.Y, v.Z, v.W), PerlinNoise.Compute(v.X + 256, v.Y + 256, v.Z + 256, v.W + 256)));
            }
        }
Example #41
0
        void Start()
        {
            foreach (GameObject o in meshes)
            {
                o.transform.parent = null; Destroy(o);
            }
            meshes = new List <GameObject>();
            INoise       perlin  = new PerlinNoise(seed, 2.0f);
            FractalNoise fractal = new FractalNoise(perlin, 3, 1.0f);

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

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

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

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

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

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

                    float value = fractal.Sample2D(fx, fz);
                    for (int y = 0; y < height; y++)
                    {
                        int idx = x + y * width + z * width * height;
                        voxels[idx] = y < (value + 1.0f) / 2.0f * height ? 1 : -1;
                    }
                }
            }

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

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

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

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

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

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

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

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

                Mesh mesh = new Mesh();
                mesh.SetVertices(splitVerts);

                mesh.SetTriangles(splitIndices, 0);
                mesh.SetNormals(splitNormals);
                mesh.RecalculateBounds();

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

                meshes.Add(go);
            }
        }
Example #42
0
    void GenerateSurface()
    {
        InstallBiomes();

        float dA   = BHLenght / Radius;    //угол кусочка поверхности длиной в метр(по горизонтальному проложению)
        int   step = 0;

        int seedsCountToGenerate = 5;

        int capacity = Mathf.CeilToInt(2 * Mathf.PI / dA);

        Vector2[] path = new Vector2[capacity + 1];
        rend.SetVertexCount(capacity + 1);

        //Generation
        PerlinNoise noise = new PerlinNoise(Random.Range(-999999, 999999));

        if (currentBiome == null)
        {
            currentBiome = BiomesList[0];
        }
        if (lastBiome == null)
        {
            lastBiome = currentBiome;
        }
        int len = currentBiome.lenght;
        int transitionLenght = 0;

        float currentLenght = 0;

        Camera.main.transform.position = new Vector3(0, Radius, Camera.main.transform.position.z);

        int transHeight = 0;

        for (float angle = 0; angle <= Mathf.PI * 2 + dA; angle += dA)
        {
            Vector2 dirVector = new Vector2(Mathf.Cos(angle), Mathf.Sin(angle));
            Vector2 point;

            float delta;
            delta          = noise.FractalNoise1D(step, currentBiome.octaves, currentBiome.frequency, currentBiome.height);
            currentLenght += delta;


            point = dirVector * (Radius + currentLenght);

            if (seedsCountToGenerate > 0)
            {
                Instantiate(seedPrefab, dirVector * (Radius + currentLenght + 1), Quaternion.identity);
                seedsCountToGenerate--;
            }

            if (len <= 0)
            {
                lastBiome            = currentBiome;
                currentBiome         = BiomesList[Random.Range(0, BiomesList.Count)];
                len                  = currentBiome.lenght;
                seedsCountToGenerate = Random.Range(1, 10);
            }
            path[step] = point;
            rend.SetPosition(step, point);
            //////////////////////////////

            len--;
            step++;
            Debug.Log(angle);
        }
        coll.SetPath(0, path);
    }
Example #43
0
    void FillDetailMap()
    {
        m_detailProtoTypes = new DetailPrototype[0];

        terrain.terrainData.detailPrototypes = m_detailProtoTypes;

        m_detailProtoTypes = new DetailPrototype[3];

        float minHeight = 0.2f;
        float maxHeight = 0.8f;
        float minWidth = 0.2f;
        float maxWidth = 0.8f;

        m_detailProtoTypes[0] = new DetailPrototype();
        m_detailProtoTypes[0].prototypeTexture = m_detail0;
        m_detailProtoTypes[0].renderMode = detailMode;
        m_detailProtoTypes[0].healthyColor = m_grassHealthyColor;
        m_detailProtoTypes[0].dryColor = m_grassDryColor;
        m_detailProtoTypes [0].minHeight = minHeight;
        m_detailProtoTypes [0].maxHeight = maxHeight;
        m_detailProtoTypes [0].minWidth = minWidth;
        m_detailProtoTypes [0].maxWidth = maxWidth;

        m_detailProtoTypes[1] = new DetailPrototype();
        m_detailProtoTypes[1].prototypeTexture = m_detail1;
        m_detailProtoTypes[1].renderMode = detailMode;
        m_detailProtoTypes[1].healthyColor = m_grassHealthyColor;
        m_detailProtoTypes[1].dryColor = m_grassDryColor;
        m_detailProtoTypes [1].minHeight = minHeight;
        m_detailProtoTypes [1].maxHeight = maxHeight;
        m_detailProtoTypes [1].minWidth = minWidth;
        m_detailProtoTypes [1].maxWidth = maxWidth;

        m_detailProtoTypes[2] = new DetailPrototype();
        m_detailProtoTypes[2].prototypeTexture = m_detail2;
        m_detailProtoTypes[2].renderMode = detailMode;
        m_detailProtoTypes[2].healthyColor = m_grassHealthyColor;
        m_detailProtoTypes[2].dryColor = m_grassDryColor;
        m_detailProtoTypes [2].minHeight = minHeight;
        m_detailProtoTypes [2].maxHeight = maxHeight;
        m_detailProtoTypes [2].minWidth = minWidth;
        m_detailProtoTypes [2].maxWidth = maxWidth;

        terrain.terrainData.detailPrototypes = m_detailProtoTypes;

        PerlinNoise m_detailNoise = new PerlinNoise(Random.Range(0,100));

        //each layer is drawn separately so if you have a lot of layers your draw calls will increase
        int[,] detailMap0 = new int[512,512];
        int[,] detailMap1 = new int[512,512];
        int[,] detailMap2 = new int[512,512];

        float ratio = (float)m_terrainSize/(float)512;

        for(int x = 0; x < 512; x++)
        {
            for (int z = 0; z < 512; z++)
            {
                detailMap0[z,x] = 0;
                detailMap1[z,x] = 0;
                detailMap2[z,x] = 0;

                float unit = 1.0f / (512 - 1);

                float normX = x * unit;
                float normZ = z * unit;

                // Get the steepness value at the normalized coordinate.
                float angle = terrain.terrainData.GetSteepness(normX, normZ);

                // Steepness is given as an angle, 0..90 degrees. Divide
                // by 90 to get an alpha blending value in the range 0..1.
                float frac = angle / 90.0f;

                if(frac < 0.3f)
                {
                    float worldPosX = (x+(512-1))*ratio;
                    float worldPosZ = (z+(512-1))*ratio;

                    float noise = m_detailNoise.FractalNoise2D(worldPosX, worldPosZ, 3, m_detailFrq, 1.0f);

                    if(noise > 0.0f)
                    {
                        float rnd = Random.value;
                        if(rnd < 0.33)
                            detailMap0[z,x] = 1;
                        else if(rnd < 0.66f)
                            detailMap1[z,x] = 1;
                        else
                            detailMap2[z,x] = 1;
                    }
                }

            }
        }

        terrain.terrainData.wavingGrassStrength = m_wavingGrassStrength;
        terrain.terrainData.wavingGrassAmount = m_wavingGrassAmount;
        terrain.terrainData.wavingGrassSpeed = m_wavingGrassSpeed;
        terrain.terrainData.wavingGrassTint = m_wavingGrassTint;
        terrain.detailObjectDensity = m_detailObjectDensity;
        terrain.detailObjectDistance = m_detailObjectDistance;
        terrain.terrainData.SetDetailResolution(512, m_detailResolutionPerPatch);

        terrain.terrainData.SetDetailLayer(0,0,0,detailMap0);
        terrain.terrainData.SetDetailLayer(0,0,1,detailMap1);
        terrain.terrainData.SetDetailLayer(0,0,2,detailMap2);
    }
Example #44
0
 public float GenerateHeightmap(float x, float z, double seedf, MapGen handle)
 {
     return(PerlinNoise.Noise(x * 0.05f, z * 0.05f, (float)seedf * 38f) + 10f);
 }
Example #45
0
    IEnumerator lV(Vector3 pos)
    {
        MarchingCubes.SetTarget(0.0f);
        MarchingCubes.SetWindingOrder(2, 1, 0);
        MarchingCubes.SetModeToCubes();
        m_surfacePerlin = new PerlinNoise(save.m_surfaceSeed);
        m_voronoi = new VoronoiNoise(save.m_surfaceSeed);
        m_voxelChunk = new VoxelChunk(pos, m_Width, m_Height, m_Length, surfaceLevel);
        m_voxelChunk.bDodane = true;

        m_voxelChunk.CreateVoxels(m_surfacePerlin, m_voronoi);//, m_cavePerlin);
        m_voxelChunk.CreateMesh (GameObject.Find ("TerrainGenerator").GetComponent<GenerateTerrain>().m_material);
        yield return new WaitForFixedUpdate();
    }
    private int GetTerrainHeight(Vector2Int pos)
    {
        BiomeAttributes biome = world.WorldAttributes.BiomeAttributes[world.Bioms[pos.x, pos.y]];

        int terrainHeight = biome.SolidGroundHeight;

        for (int i = 0; i < biome.OctavesNumber; ++i)
        {
            terrainHeight += Mathf.FloorToInt((1 / Mathf.Pow(2, i)) * biome.BiomeHeight * PerlinNoise.Get2DPerlin(world, pos, i, biome.BiomeScale * Mathf.Pow(2, i)));
        }

        return(terrainHeight);
    }
Example #47
0
    public static Color Generate(float x, float y, float freq, float colorBase, float colorVariance, int seed)
    {
        Color color;

        float index, bright, red, green, blue;

        PerlinNoise myPerlin = new PerlinNoise(seed);

        index = colorBase + myPerlin.FractalNoise2D(x, y, 3, freq, colorVariance);

        while (index > 6.0f)
        {
            index -= 6.0f;
        }
        while (index < 0.0f)
        {
            index += 6.0f;
        }

        bright = 0.5f + myPerlin.FractalNoise2D(x, y, 3, freq, 0.5f);

        while (bright > 1.0f)
        {
            bright -= 0.01f;
        }
        while (bright < 0.0f)
        {
            bright += 0.01f;
        }

        red   = 0.0f;
        green = 0.0f;
        blue  = 0.0f;

        if (index >= 2.0f && index < 4.0f)
        {
            red = 0.0f;
        }
        else if (index >= 0.0f && index < 1.0f)
        {
            red = bright;
        }
        else if (index >= 1.0f && index < 2.0f)
        {
            red = bright * (2.0f - index);
        }
        else if (index >= 4.0f && index < 5.0f)
        {
            red = bright * (index - 4.0f);
        }
        else if (index >= 5.0f && index <= 6.0f)
        {
            red = bright;
        }

        if (index >= 4.0f && index < 6.0f)
        {
            green = 0.0f;
        }
        else if (index >= 1.0f && index < 3.0f)
        {
            green = bright;
        }
        else if (index >= 3.0f && index < 4.0f)
        {
            green = bright * (4.0f - index);
        }
        else if (index >= 0.0f && index < 1.0f)
        {
            green = bright * index;
        }

        if (index >= 0.0f && index < 2.0f)
        {
            blue = 0.0f;
        }
        else if (index >= 3.0f && index < 5.0f)
        {
            blue = bright;
        }
        else if (index >= 2.0f && index < 3.0f)
        {
            blue = bright * (index - 2.0f);
        }
        else if (index >= 5.0f && index <= 6.0f)
        {
            blue = bright * (6.0f - index);
        }

        color = new Vector4(red, green, blue);

        return(color);
    }
    public static float[,] GenerateNoiseMap(int mapWidth, int mapHeight, int seed, float scale, int octaves, float persistance, float lacunarity, Vector2 offset)
    {
        float[,] noiseMap = new float[mapWidth, mapHeight];

        //Generates a random number giving the a seed
        System.Random prng = new System.Random(seed);

        Vector2[] octaveOffsets = new Vector2[octaves];
        for (int i = 0; i < octaves; i++)
        {
            float offSetX = prng.Next(-100000, 100000) + offset.x;
            float offSetY = prng.Next(-100000, 100000) + offset.y;
            octaveOffsets[i] = new Vector2(offSetX, offSetY);
        }

        if (scale <= 0)
        {
            scale = 0.00001f;
        }

        float maxNoiseHeight = float.MinValue;
        float minNoiseHeight = float.MaxValue;

        float halfWidth  = mapWidth / 2f;
        float halfHeight = mapHeight / 2f;

        //Calculate the center of the screen, so when using the noise scale it zooms in the middle and not in the corner

        for (int y = 0; y < mapHeight; y++)
        {
            for (int x = 0; x < mapWidth; x++)
            {
                float amplitude   = 1;
                float frequency   = 1;
                float noiseHeight = 0;

                for (int i = 0; i < octaves; i++)
                {
                    float sampleX = (x - halfWidth) / scale * frequency + octaveOffsets[i].x;
                    float sampleY = (y - halfHeight) / scale * frequency + octaveOffsets[i].y;
                    //Multiplying the sampleY by two and after subtracting one is going to create a negative value.
                    //SampleY = 0 * 2 - 1 = -1 // SampleY = 1 * 2 - 1 = 1;
                    //float perlinValue = Mathf.PerlinNoise(sampleX, sampleY * 2 - 1);
                    float perlinValue = PerlinNoise.Perlin(sampleX, sampleY * 2 - 1);

                    //float perlinValue = PerlinNoise.Perlin(sampleX, sampleY, 0);
                    noiseHeight += perlinValue * amplitude;

                    amplitude *= persistance;
                    frequency *= lacunarity;
                }

                if (noiseHeight > maxNoiseHeight)
                {
                    maxNoiseHeight = noiseHeight;
                }
                else if (noiseHeight < minNoiseHeight)
                {
                    minNoiseHeight = noiseHeight;
                }
                noiseMap[x, y] = noiseHeight;
            }
        }

        for (int y = 0; y < mapHeight; y++)
        {
            for (int x = 0; x < mapWidth; x++)
            {
                //InverseLerp returns a value 0 - 1
                //If the noiseMap value is equals to minNoiseHeight it returns 0 if it is equals to maxNoiseHeight it returns 1 and if it is half way it returns 0.5 and so on.
                noiseMap[x, y] = Mathf.InverseLerp(minNoiseHeight, maxNoiseHeight, noiseMap[x, y]);
            }
        }

        return(noiseMap);
    }
Example #49
0
        public override void Update(float deltaTime, Camera cam)
        {
            if (attachTargetCell != null)
            {
                if (attachTargetCell.CellType != Voronoi2.CellType.Solid)
                {
                    Drop(dropConnectedWires: true, dropper: null);
                }
                return;
            }

            if (item.body == null || !item.body.Enabled)
            {
                return;
            }
            if (picker == null || !picker.HasEquippedItem(item))
            {
                if (Pusher != null)
                {
                    Pusher.Enabled = false;
                }
                if (attachTargetCell == null)
                {
                    IsActive = false;
                }
                return;
            }

            if (picker == Character.Controlled && picker.IsKeyDown(InputType.Aim) && CanBeAttached(picker))
            {
                Drawable = true;
            }

            Vector2 swing = Vector2.Zero;

            if (swingAmount != Vector2.Zero && !picker.IsUnconscious && picker.Stun <= 0.0f)
            {
                swingState += deltaTime;
                swingState %= 1.0f;
                if (SwingWhenHolding ||
                    (SwingWhenAiming && picker.IsKeyDown(InputType.Aim)) ||
                    (SwingWhenUsing && picker.IsKeyDown(InputType.Aim) && picker.IsKeyDown(InputType.Shoot)))
                {
                    swing = swingAmount * new Vector2(
                        PerlinNoise.GetPerlin(swingState * SwingSpeed * 0.1f, swingState * SwingSpeed * 0.1f) - 0.5f,
                        PerlinNoise.GetPerlin(swingState * SwingSpeed * 0.1f + 0.5f, swingState * SwingSpeed * 0.1f + 0.5f) - 0.5f);
                }
            }

            ApplyStatusEffects(ActionType.OnActive, deltaTime, picker);

            if (item.body.Dir != picker.AnimController.Dir)
            {
                item.FlipX(relativeToSub: false);
            }

            item.Submarine = picker.Submarine;

            if (picker.HeldItems.Contains(item))
            {
                scaledHandlePos[0] = handlePos[0] * item.Scale;
                scaledHandlePos[1] = handlePos[1] * item.Scale;
                bool aim = picker.IsKeyDown(InputType.Aim) && aimPos != Vector2.Zero && picker.CanAim;
                picker.AnimController.HoldItem(deltaTime, item, scaledHandlePos, holdPos + swing, aimPos + swing, aim, holdAngle);
            }
            else
            {
                Limb equipLimb = null;
                if (picker.Inventory.IsInLimbSlot(item, InvSlotType.Headset) || picker.Inventory.IsInLimbSlot(item, InvSlotType.Head))
                {
                    equipLimb = picker.AnimController.GetLimb(LimbType.Head);
                }
                else if (picker.Inventory.IsInLimbSlot(item, InvSlotType.InnerClothes) ||
                         picker.Inventory.IsInLimbSlot(item, InvSlotType.OuterClothes))
                {
                    equipLimb = picker.AnimController.GetLimb(LimbType.Torso);
                }

                if (equipLimb != null)
                {
                    float itemAngle = (equipLimb.Rotation + holdAngle * picker.AnimController.Dir);

                    Matrix  itemTransfrom        = Matrix.CreateRotationZ(equipLimb.Rotation);
                    Vector2 transformedHandlePos = Vector2.Transform(handlePos[0] * item.Scale, itemTransfrom);

                    item.body.ResetDynamics();
                    item.SetTransform(equipLimb.SimPosition - transformedHandlePos, itemAngle);
                }
            }
        }
Example #50
0
        private void Update()
        {
            foreach (var entity in Ecs.GetEntities <RandomOverworld>())
            {
                var randomOverworld = entity.Item1;
                var tilemap         = randomOverworld.tilemap;
                var playerPrefab    = randomOverworld.playerPrefab;
                var frequency       = randomOverworld.frequency;

                if (randomOverworld.regenrateNow == false)
                {
                    continue;
                }

                randomOverworld.regenrateNow = false;
                var size   = tilemap.size;
                var width  = randomOverworld.width = size.x;
                var height = randomOverworld.height = size.y;

                // Reset tilemap
                for (int x = 0; x < width; x++)
                {
                    for (int y = 0; y < height; y++)
                    {
                        tilemap.SetColor(new Vector3Int(x, y, 0), Color.white);
                    }
                }

                // Generate World
                for (int x = 0; x < width; x++)
                {
                    for (int y = 0; y < height; y++)
                    {
                        var value = PerlinNoise.Get(x / (float)randomOverworld.width, y / (float)randomOverworld.height, frequency);
                        if (value < 0.8f)
                        {
                            var position   = new Vector3Int(x, y, 0);
                            var randomTile = randomOverworld.grassTiles[UnityEngine.Random.Range(0, randomOverworld.grassTiles.Count)];
                            tilemap.SetTile(position, randomTile);
                        }
                        else
                        {
                            var position   = new Vector3Int(x, y, 0);
                            var randomTile = randomOverworld.mountainTiles[UnityEngine.Random.Range(0, randomOverworld.mountainTiles.Count)];
                            tilemap.SetTile(position, randomTile);
                        }
                    }
                }

                // Place Character
                GameObject player = null;
                while (!player)
                {
                    var x        = UnityEngine.Random.Range(0, width);
                    var y        = UnityEngine.Random.Range(0, height);
                    var position = new Vector3Int(x, y, 0);
                    var tile     = (Tile)tilemap.GetTile(position);
                    if (tile.sprite.name.Contains("Grass"))
                    {
                        player = Instantiate(playerPrefab, tilemap.CellToWorld(position), Quaternion.identity);
                    }
                }
            }
        }
 public virtual float FillVoxel(float x,float y,float z, Vector3 m_pos,PerlinNoise noise,int Oct,float Frequency,float Amplitude,bool DoCaves)
 {
     float HT = 0;
     return HT;
 }
        /// <summary>
        /// Generates the map.
        /// </summary>
        public void Generate()
        {
            if (Level == null)
            {
                throw new NullReferenceException("Level to generate was null");
            }

            if (OnProgressArgs != null)
            {
                OnProgressArgs(this, new GenerationEventArgs("Creating Dimentions...", 10));
            }

            NoiseGenerator = new PerlinNoise()
            {
                Amplitude   = GenArgs.Amplitude,
                Frequency   = GenArgs.WaveFrequency,
                Octaves     = GenArgs.MoutainOctaves,
                Persistence = GenArgs.Persistence
            };

            NoiseGenerator.InitNoiseFunctions();
            map     = new float[Level.CWMap.Size.x, Level.CWMap.Size.z];
            overlay = new float[Level.CWMap.Size.x, Level.CWMap.Size.z];

            if (GenArgs.PlantMushrooms || GenArgs.PlantFlowers || GenArgs.PlantSaplings)
            {
                plants = new float[Level.CWMap.Size.x, Level.CWMap.Size.z];
            }


            if (OnProgressArgs != null)
            {
                OnProgressArgs(this, new GenerationEventArgs("Building...", 20));
            }
            Generate3DTerrain();

            if (OnProgressArgs != null)
            {
                OnProgressArgs(this, new GenerationEventArgs("Raking...", 10));
            }
            ApplyFilter();

            if (OnProgressArgs != null)
            {
                OnProgressArgs(this, new GenerationEventArgs("Creating Moutains...", 20));
            }
            GenerateNoise();


            if (OnProgressArgs != null)
            {
                OnProgressArgs(this, new GenerationEventArgs("Cleaning Moutains..", 10));
            }
            NoiseUtils.Normalize(map);

            if (OnProgressArgs != null)
            {
                OnProgressArgs(this, new GenerationEventArgs("Setting blocks...", 20));
            }
            SetBlocks();

            if (OnProgressArgs != null)
            {
                OnProgressArgs(this, new GenerationEventArgs("Planting..", 20));
            }
            SetPlants();


            if (OnProgressArgs != null)
            {
                OnProgressArgs(this, new GenerationEventArgs("Created map " + Level.Name, 10));
            }
            Finalize();
        }
Example #53
0
 float SampleCaves(float x, float y, float z, PerlinNoise perlin)
 {
     //The creates the noise used for the caves. It uses domain warping like the moiuntains
     //to creat long twisting caves.
     float w = perlin.FractalNoise3D(x, y, z, 1, 40.0f, 32.0f);
     //The last vaule is the cave amp and defines the maximum cave diameter. A larger value will create
     //larger caves (A higher frequency will also create larger caves). It is unitless, 1 != 1m
     return Mathf.Abs(perlin.FractalNoise3D(x+w, y*2.0f+w, z+w, 2, 40.0f, 2.0f));
 }
Example #54
0
 void Start()
 {
     noise = new PerlinNoise(Random.Range(100000, 10000000));
     Regenerate();
 }
Example #55
0
 float SampleGround(float x, float z, PerlinNoise perlin)
 {
     //This creates the noise used for the ground.
     //The last value (8.0f) is the amp that defines (roughly) the maximum
     //and minimum vaule the ground varies from the surface level
     return perlin.FractalNoise2D(x, z, 4, 80.0f, 8.0f);
 }
Example #56
0
 public PerlinRenderer(Paint paint) : base(paint)
 {
     Perlin = new PerlinNoise(Rand.Int(1, 100));
 }
    public IEnumerator GenerateEnvironment(HightMap heightMap, MechData meshData, MeshSettings meshSettings, HightMapSettings hightMapSettings, EnvironmentData environmentData, int mapChunkSize, float scale, float min, float max)
    {
        int seed;

        if (environmentData.usingHeightMapSeed)
        {
            seed = hightMapSettings.noiseSettings.seed;
        }
        else
        {
            seed = environmentData.seed;
        }

        System.Random prng = new System.Random(seed);


        bool useFlatSheadedB            = false;
        int  flatSheadedChunkSizeIndexB = 0;

        if (meshSettings.useFlatShader)
        {
            flatSheadedChunkSizeIndexB  = meshSettings.chunkSizeIndex;
            useFlatSheadedB             = true;
            meshSettings.chunkSizeIndex = meshSettings.flatSheadedChunkSizeIndex;
            meshSettings.useFlatShader  = false;
        }

        for (int i = 0; i < environmentData.types.Length; i++)
        {
            panelProcess.setNumer(i + 1 + "/" + environmentData.types.Length);
            panelProcess.setLabel("Environment ");

            EnvironmentData.Types now = environmentData.types[i];
            float[,] noise = PerlinNoise.GeneratorNoise(mapChunkSize + 2, mapChunkSize + 2, now.noiseData.noiseSettings, Vector2.zero);

            float[] noisMapEnd = HightMap.ConwertTab(noise, mapChunkSize + 2);
            int     msi        = (now.LOD == 0) ? 1 : now.LOD * 2;
            Vector3 lastPos    = Vector3.zero;
            int     len        = ((int)(mapChunkSize + 2) / msi) + 1;
            len = len * len;

            Vector3[] points          = mechDraw.GenerateMech(heightMap.value, meshSettings, now.LOD).vertices;
            Vector3[] orginalVerticis = meshData.vertices;

            for (int j = 0; j < len; j++)
            {
                Vector3 nowPos = Vector3.zero;
                if ((positioningMode == PositioningMode.Calculation) || (positioningMode == PositioningMode.BothMode))
                {
                    nowPos = orginalVerticis[CalculationPos(points, orginalVerticis, j, len)];
                }
                else
                {
                    nowPos = points[j];
                }


                panelProcess.setValue((float)j / len);

                float wynik = map(min, max, 0, 1, nowPos.y);


                //if (true)
                if (noisMapEnd[j] < now.curve.Evaluate(wynik))
                {
                    if (lastPos != nowPos)
                    {
                        Vector3 randPos = new Vector3(prng.Next(-now.LOD * environmentData.prngPrecision, now.LOD * environmentData.prngPrecision) / environmentData.prngPrecision, 0, prng.Next(-now.LOD * environmentData.prngPrecision, now.LOD * environmentData.prngPrecision) / environmentData.prngPrecision) * now.randPos;

                        float x = 0, y = 0, z = 0;
                        if (now.randRotX)
                        {
                            x = prng.Next(0, 359);
                        }
                        if (now.randRotY)
                        {
                            y = prng.Next(0, 359);
                        }
                        if (now.randRotZ)
                        {
                            z = prng.Next(0, 359);
                        }
                        if ((positioningMode == PositioningMode.Colision) || (positioningMode == PositioningMode.BothMode))
                        {
                            nowPos.y = ColidePos(nowPos.x + randPos.x, nowPos.z + randPos.z, heightMap.minV, heightMap.maxV) - randPos.y;
                        }
                        Vector3 randRot = new Vector3(x, y, z);
                        lastPos = nowPos;

                        GameObject o = Instantiate(now.Object, (nowPos + randPos) * scale, Quaternion.Euler(now.rotation + randRot));

                        Transform tObject = o.GetComponent <Transform>() as Transform;
                        tObject.SetParent(parent, true);
                        tObject.localScale = now.scale;

                        if (j % skip == 0)
                        {
                            yield return(null);
                        }
                    }
                }
            }
        }
        yield return(null);

        if (useFlatSheadedB)
        {
            meshSettings.chunkSizeIndex = flatSheadedChunkSizeIndexB;
            meshSettings.useFlatShader  = true;
        }
        panelProcess.setActive(false);
    }
    protected LineSegmentRenderer(RenderingDevice device, MdfMaterialFactory materialFactory, PerlinNoise noise,
                                  int maxLineSegments, string debugName)
    {
        _noise   = noise;
        Vertices = new Vertex[maxLineSegments * 2];
        Jitter   = new float[maxLineSegments];

        _device   = device;
        _material = materialFactory.LoadMaterial("art/meshes/lightning.mdf",
                                                 material => material.perVertexColor = true);

        _indexBuffer    = CreateIndexBuffer(_device, maxLineSegments, debugName);
        _capIndexBuffer = CreateIndexBuffer2(_device, debugName);
        _vertexBuffer   =
            _device.CreateEmptyVertexBuffer(Vertex.Size * Vertices.Length, debugName: debugName);
        _bufferBinding = _device.CreateMdfBufferBinding(true).Ref();
        _bufferBinding.Resource.AddBuffer <Vertex>(_vertexBuffer.Resource, 0)
        .AddElement(VertexElementType.Float3, VertexElementSemantic.Position)
        .AddElement(VertexElementType.Float3, VertexElementSemantic.Normal)
        .AddElement(VertexElementType.Color, VertexElementSemantic.Color)
        .AddElement(VertexElementType.Float2, VertexElementSemantic.TexCoord);
    }
Example #59
0
        public void NoiseIsPeriodicWithUserPeriod()
        {
            Random random = new Random(1234567);

            for (int i = 0; i < 100; i++)
            {
                var v = random.NextVector4D(-1000, 1000);

                var randomPeriod = random.NextVector4D(2, 444);
                var px           = (int)randomPeriod.X;
                var py           = (int)randomPeriod.Y;
                var pz           = (int)randomPeriod.Z;
                var pw           = (int)randomPeriod.W;

                Assert.IsTrue(Numeric.AreEqual(PerlinNoise.Compute(v.X, px), PerlinNoise.Compute(v.X - px, px)));
                Assert.IsTrue(Numeric.AreEqual(PerlinNoise.Compute(v.X, px), PerlinNoise.Compute(v.X + px, px)));

                Assert.IsTrue(Numeric.AreEqual(PerlinNoise.Compute(v.X, v.Y, px, py), PerlinNoise.Compute(v.X - px, v.Y - py, px, py)));
                Assert.IsTrue(Numeric.AreEqual(PerlinNoise.Compute(v.X, v.Y, px, py), PerlinNoise.Compute(v.X + px, v.Y + py, px, py)));

                Assert.IsTrue(Numeric.AreEqual(PerlinNoise.Compute(v.X, v.Y, v.Z, px, py, pz), PerlinNoise.Compute(v.X - px, v.Y - py, v.Z - pz, px, py, pz)));
                Assert.IsTrue(Numeric.AreEqual(PerlinNoise.Compute(v.X, v.Y, v.Z, px, py, pz), PerlinNoise.Compute(v.X + px, v.Y + py, v.Z + pz, px, py, pz)));

                Assert.IsTrue(Numeric.AreEqual(PerlinNoise.Compute(v.X, v.Y, v.Z, v.W, px, py, pz, pw), PerlinNoise.Compute(v.X - px, v.Y - py, v.Z - pz, v.W - pw, px, py, pz, pw)));
                Assert.IsTrue(Numeric.AreEqual(PerlinNoise.Compute(v.X, v.Y, v.Z, v.W, px, py, pz, pw), PerlinNoise.Compute(v.X + px, v.Y + py, v.Z + pz, v.W + pw, px, py, pz, pw)));
            }
        }
Example #60
0
 private float[,] GenerateBiomeMap(int mapSize, PerlinNoise perlinNoise)
 {
     return(perlinNoise.GenerateNoiseMap(mapSize));
 }