public void Respawn()
    {
        StopCoroutine(AnnualReproduction());

        if (ThreadedScaleUpdater.Instance)
        {
            ThreadedScaleUpdater.Instance.RemoveAll();
        }

        if (forestContainer)
        {
            MiscUtils.DeleteChildren(forestContainer);
        }

        for (int index = 0; index < foliageTypes.Length; index++)
        {
            foliageTypes[index].cummulativeTotalOfThisType = 0;
        }

        int seed = CustomMathf.GetRandomSeed();

        if (LevelController.Instance)
        {
            seed = LevelController.Instance.seed;
        }

        InitalSpawn(seed);
    }
    private bool IsFarEnough(Vector2 sample)
    {
        GridPos pos = new GridPos(sample, cellSize);

        int xmin = Mathf.Max(pos.x - 2, 0);
        int ymin = Mathf.Max(pos.y - 2, 0);
        int xmax = Mathf.Min(pos.x + 2, grid.GetLength(0) - 1);
        int ymax = Mathf.Min(pos.y + 2, grid.GetLength(1) - 1);

        //randomly modify the radius to cluster the samples
        float modRad2 = radius2 * CustomMathf.RemapValue(Mathf.PerlinNoise(sample.x + Random.seed, sample.y + Random.seed), clusterRange.x, clusterRange.y);

        for (int y = ymin; y <= ymax; y++)
        {
            for (int x = xmin; x <= xmax; x++)
            {
                Vector2 s = grid[x, y];
                if (s != Vector2.zero)
                {
                    Vector2 d = s - sample;
                    if (d.x * d.x + d.y * d.y < modRad2)
                    {
                        return(false);
                    }
                }
            }
        }

        return(true);

        // Note: we use the zero vector to denote an unfilled cell in the grid. This means that if we were
        // to randomly pick (0, 0) as a sample, it would be ignored for the purposes of proximity-testing
        // and we might end up with another sample too close from (0, 0). This is a very minor issue.
    }
Esempio n. 3
0
    public void DebugRotation()
    {
        float deltaTime = CustomMathf.TicksToSeconds(System.DateTime.Now.Ticks - lastRotation);

        rotationContainer.Rotate(rotationAxis, (360f / debugRotationLength) * deltaTime);
        lastRotation = System.DateTime.Now.Ticks;
    }
Esempio n. 4
0
 public float GetValue()
 {
     if (dataType == CurveDataType.FLOAT)
     {
         return(value);
     }
     else
     {
         return(CustomMathf.GetMean(values));
     }
 }
 private void CalculateLerpValue()
 {
     if (easing)
     {
         lerpValue = CustomMathf.CalculateLerpValueClamp01(step, type, isZeroToOne);
     }
     else
     {
         lerpValue = step;
     }
 }
Esempio n. 6
0
    public override void OnInspectorGUI()
    {
        var script = target as GradientSettings;

        DrawDefaultInspector();

        if (script.lastPath.Length > 0)
        {
            script.autoupdate = EditorGUILayout.Foldout(script.autoupdate, "Autoupdate Texture On Gradient Change");
        }
        else
        {
            script.autoupdate = false;
        }

        if (script.autoupdate)
        {
            script.autoupdateRate = EditorGUILayout.FloatField("Autoupdate Rate: ", script.autoupdateRate);

            EditorGUILayout.Space();

            long currentTime = System.DateTime.Now.Ticks;
            //convert the autoupdateRate from seconds to ticks (10,000,000 ticks in one second)
//			long updateIntervalInTicks = (long)(script.autoupdateRate * 10000000);
            long updateIntervalInTicks = CustomMathf.SecondsToTicks(script.autoupdateRate);
            if (script.lastAutoUpdate + updateIntervalInTicks < currentTime)
            {
                int checkPointCount = 6;
                for (int i = 0; i < checkPointCount; i++)
                {
                    float checkPointPercent = (float)i / (float)(checkPointCount - 1);
                    if (script.lastGradient.Evaluate(checkPointPercent) != script.gradient.Evaluate(checkPointPercent))
                    {
                        CreateGradientTexture.SaveTexture(script.lastPath, script);
                        script.lastAutoUpdate = currentTime;
                        break;
                    }
                }
            }
        }

        EditorGUILayout.Space();

        script.textureSizePow = EditorGUILayout.IntSlider("Texture Size: " + script.textureSize.ToString() + " px", script.textureSizePow, 1, 11);
        script.textureSize    = (int)Mathf.Pow(2, script.textureSizePow);

        EditorGUILayout.Space();


        if (GUILayout.Button("Save As Texture"))
        {
            CreateGradientTexture.CreateWizard();
        }
    }
    public void GenerateInitialWalls(Transform newTerrainObject, Vector3[] newTerrainVertices, Vector2Int newGridSize, Vector3 newMapSize)
    {
        terrainObject   = newTerrainObject;
        terrainVertices = newTerrainVertices;
        gridSize        = newGridSize;
        mapSize         = newMapSize;

        normalBumpiness.Initialize(CustomMathf.GetRandomSeed());
        vertexDisplacementSettings.displacementNoise.Initialize(CustomMathf.GetRandomSeed());

        CreateWallObjects();
        CreateWallMeshes();
    }
    public void GetNoise(Vector3 newMapSize)
    {
        mapSize = newMapSize;

        if (!LevelController.Instance)
        {
            if (!useSeed)
            {
                seed = CustomMathf.GetRandomSeed();
            }
        }
        else
        {
            seed = LevelController.Instance.seed;
        }

        heightmap = new float[heightmapResolution, heightmapResolution];

        //first the main features
        for (int i = 0; i < largeScaleNoisePasses.Length; i++)
        {
            if (largeScaleNoisePasses[i].isActive)
            {
                largeScaleNoisePasses[i].noiseSettings.ModifyGrid(ref heightmap, mapSize.y, seed);
            }
        }

        //flatten any peaks
        for (int i = 0; i < flattenPeaksPasses.Length; i++)
        {
            if (flattenPeaksPasses[i].filterRadius > 0)
            {
                heightmap = flattenPeaksPasses[i].Flatten(heightmap, mapSize.x / (float)heightmapResolution, mapSize.z / (float)heightmapResolution);
            }
        }

        //do a final smoothing
        for (int i = 0; i < smoothingPasses.Length; i++)
        {
            if (smoothingPasses[i].filterRadius > 0)
            {
                heightmap = smoothingPasses[i].SmoothGrid(heightmap);
            }
        }

        //prepare the normalmap-like final pass for use when interpolating
        if (finalDetailPass.isActive)
        {
            finalDetailPass.noiseSettings.InstantiatePassType(seed);
        }
    }
    public float InterpolateValue(Vector2 uvPosition)
    {
        if (mapSize.x > mapSize.z)
        {
            uvPosition.y *= mapSize.z / mapSize.x;
        }
        else if (mapSize.x < mapSize.z)
        {
            uvPosition.x *= mapSize.x / mapSize.z;
        }

        uvPosition *= .99f + .005f;         //add just a bit of cushion
        Vector2 floatPixelPoint = GetPixelFromUV(uvPosition, FloatToIntMethod.NONE);

        Vector2Int topLeftPixelPoint     = Vector2Int.ToInt(GetPixelFromUV(uvPosition, FloatToIntMethod.FLOOR));
        Vector2Int bottomRightPixelPoint = Vector2Int.ToInt(GetPixelFromUV(uvPosition, FloatToIntMethod.CEIL));

        Vector2Int topRightPixelPoint   = new Vector2Int(bottomRightPixelPoint.x, topLeftPixelPoint.y);
        Vector2Int bottomLeftPixelPoint = new Vector2Int(topLeftPixelPoint.x, bottomRightPixelPoint.y);

        Vector2 interpolationPercents = floatPixelPoint - topLeftPixelPoint;

        if (cubicInterpolation)
        {
            interpolationPercents.x = CustomMathf.Hermite(interpolationPercents.x);
            interpolationPercents.y = CustomMathf.Hermite(interpolationPercents.y);
        }

        Vector4 interpolatedValues = new Vector4((1f - interpolationPercents.x) * (1f - interpolationPercents.y),
                                                 (interpolationPercents.x) * (1f - interpolationPercents.y),
                                                 (1f - interpolationPercents.x) * (interpolationPercents.y),
                                                 (interpolationPercents.x) * (interpolationPercents.y));

        float output = SampleArray(topLeftPixelPoint) * interpolatedValues.x;

        output += SampleArray(topRightPixelPoint) * interpolatedValues.y;

        output += SampleArray(bottomLeftPixelPoint) * interpolatedValues.z;
        output += SampleArray(bottomRightPixelPoint) * interpolatedValues.w;

        if (finalDetailPass.isActive)
        {
            output += finalDetailPass.noiseSettings.GetNoiseValue(uvPosition.x, uvPosition.y, 1f);
        }

        return(output);
    }
Esempio n. 10
0
    public void Awake()
    {
        if (Instance)
        {
            Destroy(gameObject);
            return;
        }

        Instance = this;

        if (!useSeed)
        {
            seed = CustomMathf.GetRandomSeed();
        }

        CreateMap();
    }
    public void AttemptSpawn(Vector3 samplePoint, TerrainObjectType terrainObjectSettings, bool randomAge, bool checkSurroundings)
    {
        float viability = terrainObjectSettings.TestViability(ref samplePoint, checkSurroundings);

        if (viability <= terrainObjectSettings.viabilitySettings.minViability)
        {
            return;
        }

        float viabilityPercentage = CustomMathf.RemapValue(viability, terrainObjectSettings.viabilitySettings.minViability, 1f, true);
        float num       = !randomAge ? 0.0f : initialAgeDistribution.GetValue(Random.value) * terrainObjectSettings.dna.lifetime.minOutputValue * LevelController.Instance.yearLength;
        var   newObject = terrainObjectSettings.SpawnFoliageObject(samplePoint, Time.time - num, viabilityPercentage, reproduceAnnually);

        if (newObject.GetType() == typeof(FoliageObject))
        {
            AddFoliageObject((FoliageObject)newObject);
        }
        else
        {
            AddTerrainObject(newObject);
        }
    }
    void TerrainGUI()
    {
        var terrain         = GameObject.FindObjectOfType <TerrainGenerator>();
        var levelController = GameObject.FindObjectOfType <LevelController>();

        EditorGUILayout.BeginHorizontal();
        if (GUILayout.Button("Generate From Seed"))
        {
            terrain.proceduralTerrainSettings.useSeed = true;
            terrain.GenerateMesh();
        }

        if (GUILayout.Button("Generate Random Terrain"))
        {
            terrain.proceduralTerrainSettings.seed = CustomMathf.GetRandomSeed();
            terrain.GenerateMesh();
        }
        EditorGUILayout.EndHorizontal();


        EditorGUILayout.BeginHorizontal();
        terrain.proceduralTerrainSettings.seed = EditorGUILayout.IntField(terrain.proceduralTerrainSettings.seed);

        if (GUILayout.Button("Randomize Seed"))
        {
            terrain.proceduralTerrainSettings.seed = CustomMathf.GetRandomSeed();
        }
        EditorGUILayout.EndHorizontal();

        if (GUILayout.Button("Generate Flow Map"))
        {
            terrain.GenerateFlowMap();
            terrain.ChangeTerrainShaderToRainy();
        }

        EditorGUILayout.Separator();
    }
Esempio n. 13
0
    /// <summary>
    /// Obtiene todos los bloques que sostienen este bloque
    /// </summary>
    /// <returns>Lista de bloques soporte</returns>
    protected List <Block> SupportingBlocks()
    {
        var blocks = new List <Block>();

        var myPos          = Position;
        var underBlocksPos = new IntVector3[] {
            CustomMathf.RoundToIntVector(myPos.x, myPos.y - 1, myPos.z - 1),
            CustomMathf.RoundToIntVector(myPos.x - 1, myPos.y - 1, myPos.z),
            CustomMathf.RoundToIntVector(myPos.x, myPos.y - 1, myPos.z),
            CustomMathf.RoundToIntVector(myPos.x + 1, myPos.y - 1, myPos.z),
            CustomMathf.RoundToIntVector(myPos.x, myPos.y - 1, myPos.z + 1)
        };

        foreach (var pos in underBlocksPos)
        {
            var underBlock = Level.Instance.Grid[pos];
            if (underBlock != null && !underBlock.isFalling)
            {
                blocks.Add(underBlock);
            }
        }

        return(blocks);
    }
    public override void OnInspectorGUI()
    {
        DrawDefaultInspector();

        var script = target as NoiseSettings;

        EditorGUILayout.Space();

        DisplayPreview = EditorGUILayout.Foldout(DisplayPreview, "Preview Noise Result");

        if (DisplayPreview)
        {
            if (!gridInitialized)
            {
                previewSeed = GetCurrentSeed();
                UpdateCheck(script);
                gridInitialized = true;
                EditorCoroutine.StartEditorCoroutine(CheckForUpdates(script));
            }

            var   lastRect         = GUILayoutUtility.GetLastRect();
            float previewPixelSize = (float)previewSize * previewScale;

            previewWindowRect = new Rect(new Vector2(lastRect.center.x - previewPixelSize / 2f, lastRect.yMin + 20), new Vector2(previewPixelSize, previewPixelSize));
            float previewOutputRange = 0f;
            if (script.passOperationType == NoiseSettings.PassOperation.ADD)
            {
                previewOutputRange = script.outputCurve.maxOutputValue - script.outputCurve.minOutputValue;
            }
            else if (script.passOperationType == NoiseSettings.PassOperation.MULTIPLY)
            {
                previewOutputRange = 1f;
            }

            NoisePreview.DrawNoise(script.debugPreviewGrid, previewWindowRect, previewOutputRange);
            GUILayout.Space(previewPixelSize + 5f);

            EditorGUI.indentLevel++;

            previewSeed = EditorGUILayout.IntField("Preview Seed: ", previewSeed);

            EditorGUILayout.BeginHorizontal();
            if (GUILayout.Button("Get Current Seed"))
            {
                previewSeed = GetCurrentSeed();
                GeneratePreview(script);
            }
            if (GUILayout.Button("Randomize Seed"))
            {
                previewSeed = CustomMathf.GetRandomSeed();
                GeneratePreview(script);
            }
            EditorGUILayout.EndHorizontal();

            EditorGUI.indentLevel--;
        }

        EditorGUILayout.Space();
        EditorGUILayout.Space();
        EditorGUILayout.Space();

        if (GUILayout.Button("--- Generate Terrain ---"))
        {
            GameObject.FindObjectOfType <TerrainGenerator>().GenerateMesh();
        }
    }
Esempio n. 15
0
 private static float GetRandomRange(AnimationCurve smoothingCurve, float min, float max)
 {
     return(CustomMathf.RemapValue(smoothingCurve.Evaluate(Random.value), min, max, false));
 }
Esempio n. 16
0
    /// <summary>
    /// Administra las acciones estando colgado
    /// </summary>
    protected void HangingManagement()
    {
        // Boton de agarre
        if (_input.BtnA)
        {
            // Hay bloque debajo
            if (Level.Instance.Grid.ExistsStillAt(Position - Vector3.up))
            {
                Debug.Log("Accion: Descolgando");
                HangDrop();
            }
            // No hay bloque debajo
            else
            {
                Debug.Log("Accion: Colgando -> Caer");
                HangToFall();
            }
        }
        // Desplazamiento
        else if (_input.Direction != null)
        {
            // Transforma el input (da prioridad al input vertical)
            var newInput = new Vector3(0, _input.Direction.z, 0);
            if (newInput.y == 0 && _input.Direction.x != 0)
            {
                if (_input.Direction.x > 0)
                {
                    newInput += transform.right;
                }
                else
                {
                    newInput += (transform.right * -1f);
                }
            }

            // Determina la posicion objetivo
            var targetPos = Position + CustomMathf.RoundToIntVector(newInput);

            // Desplazamiento horizontal
            if (newInput.y == 0 && newInput.x != 0)
            {
                // Hay un cubo en el lugar destino? -> Dobla (Acute)
                if (Level.Instance.Grid.ExistsStillAt(targetPos))
                {
                    // Direccion de strafe
                    if (_input.Direction.x > 0)
                    {
                        Debug.Log("Accion: Colgando -> Giro Derecha Concavo");
                        HangRightConcave();
                    }
                    else
                    {
                        Debug.Log("Accion: Colgando -> Giro Izquierda Concavo");
                        HangLeftConcave();
                    }
                }

                // Hay un cubo delante del lugar destino?
                else if (Level.Instance.Grid.ExistsStillAt(targetPos + Direction))
                {
                    // Direccion de strafe
                    if (_input.Direction.x > 0)
                    {
                        Debug.Log("Accion: Colgando -> Derecha");
                        HangRight();
                    }
                    else
                    {
                        Debug.Log("Accion: Colgando -> Izquierda");
                        HangLeft();
                    }
                }

                // No hay cubo en el lugar destino y no hay cubo que impida doblar -> Dobla (Obtuse)
                else
                {
                    if (_input.Direction.x > 0 &&
                        !Level.Instance.Grid.ExistsStillAt(targetPos + Direction + Vector3.up))
                    {
                        Debug.Log("Accion: Colgando -> Giro Derecha Convexo");
                        HangRightConvexe();
                    }
                    else if (_input.Direction.x < 0 &&
                             !Level.Instance.Grid.ExistsStillAt(targetPos + Direction + Vector3.up))
                    {
                        Debug.Log("Accion: Colgando -> Giro Izquierda Convexo");
                        HangLeftConvexe();
                    }
                    else
                    {
                        Hang();
                    }
                }
            }

            // Desplazamiento vertical
            else if (newInput.y != 0)
            {
                // Input: arriba, y no hay bloque que lo impida -> sube
                if (newInput.y == 1 && !Level.Instance.Grid.ExistsStillAt(targetPos + Direction))
                {
                    Debug.Log("Accion: Colgando -> Subir");
                    HangUp();
                }
                // Input: abajo, y hay un bloque debajo -> descuelga
                else if (newInput.y == -1 && Level.Instance.Grid.ExistsStillAt(targetPos))
                {
                    Debug.Log("Accion: Descolgando");
                    HangDrop();
                }
                // Queda colgado
                else
                {
                    Hang();
                }
            }
        }
    }
Esempio n. 17
0
 public float TestViability(ref Vector3 position, bool checkSurroundings, float viabilityModifier = 1f)
 {
     return(TestViability(position, CustomMathf.GetSlopeAtPoint(ref position, terrainLayerMask, objectLayerMask, 400f), checkSurroundings, viabilityModifier));
 }
Esempio n. 18
0
    public TerrainObject SpawnFoliageObject(Vector3 position, float spawnTime, float viabilityPercentage, bool reproduceAnnually)
    {
        float      rollRotation     = Random.value * Random.value * dna.maxRollRotation * CustomMathf.GetRandomSign();
        GameObject newTerrainObject = GameObject.Instantiate(prefab, position, Quaternion.Euler(0f, Random.Range(0f, 360f), rollRotation)) as GameObject;

        newTerrainObject.name             = prefab.name + " #" + cummulativeTotalOfThisType.ToString();
        newTerrainObject.transform.parent = container;
        cummulativeTotalOfThisType++;

        var terrainObject = newTerrainObject.GetComponent <TerrainObject>();

        terrainObject.Initialize(this, spawnTime, viabilityPercentage, reproduceAnnually);

        return(terrainObject);
    }
Esempio n. 19
0
 private void UpdateStep()
 {
     step = isZeroToOne ? step + Time.deltaTime * speed : step - Time.deltaTime * speed;
     step = CustomMathf.ClampMinMax(0f, 1f, step);
 }
Esempio n. 20
0
 public void GenerateNewMap()
 {
     LevelController.Instance.NewMap(CustomMathf.GetRandomSeed());
 }
Esempio n. 21
0
 public void Initialize()
 {
     temperatureFluctuationNoise.Initialize(CustomMathf.GetRandomSeed());
 }