Beispiel #1
0
        public void ErodeOneStep()
        {
            var currentHeightArray = SimpleHeightArray.FromHeightmap(_currentHeightmap);
            var eroder             = new ThermalEroder();

            var extremes = new ArrayExtremes(1517, 6161);
            var tParam   = CalculateFromHillFactor(1, extremes, 24);

            Debug.Log("TPAN IS " + tParam);

            eroder.Erode(currentHeightArray, new ThermalErosionConfiguration()
            {
                StepCount = 5,
                CParam    = 0.3f,
                TParam    = tParam
            });

            var doneTexture =
                HeightmapUtils.CreateTextureFromHeightmap(
                    SimpleHeightArray.ToHeightmap(currentHeightArray));

            //_go.GetComponent<MeshRenderer>().material.SetTexture("_HeightmapTex0", _oldDoneTexture);
            _go.GetComponent <MeshRenderer>().material.SetTexture("_HeightmapTex1", doneTexture);
            _oldDoneTexture = doneTexture;
        }
        public void Start()
        {
            TaskUtils.SetGlobalMultithreading(false);
            //DiamondSquareCreator creator = new DiamondSquareCreator(new RandomProvider(22));
            //_currentHeightmap = creator.CreateDiamondSquareNoiseArray(_sizeOfTexture, 64);
            //MyArrayUtils.Multiply(_currentHeightmap.HeightmapAsArray, 0.1f);
            var heightTex = SavingFileManager.LoadPngTextureFromFile(@"C:\inz\cont\smallCut.png", 240, 240,
                                                                     TextureFormat.RGBA32, true, true);

            _currentHeightmap = HeightmapUtils.CreateHeightmapArrayFromTexture(heightTex);

            MyArrayUtils.Normalize(_currentHeightmap.HeightmapAsArray);
            MyArrayUtils.InvertNormalized(_currentHeightmap.HeightmapAsArray);

            CreateComparisionObject();
            //MyArrayUtils.Multiply(_currentHeightmap.HeightmapAsArray, 400);

            //float[,] newHeightArray = new float[256,256];
            //for (int x = 0; x < 256; x++)
            //{
            //    for (int y = 0; y < 256; y++)
            //    {
            //        var distance = (new Vector2(x,y) - new Vector2(128, 128)).magnitude;
            //        newHeightArray[x, y] = distance;
            //    }
            //}
            //MyArrayUtils.Normalize(newHeightArray);
            //_currentHeightmap = new HeightmapArray(newHeightArray);

            //Hydraulic_RenderComputeShader();

            Thermal_RenderComputeShader();
            //Hydraulic_RenderComputeShader();
        }
Beispiel #3
0
        public void Start()
        {
            //var heightTexture = SavingFileManager.LoadPngTextureFromFile(@"C:\inz\cont\smallCut.png", 240,
            //    240, TextureFormat.RGBA32, true, true);
            //_currentHeightmap = HeightmapUtils.CreateHeightmapArrayFromTexture(heightTexture);

            DiamondSquareCreator creator = new DiamondSquareCreator(new RandomProvider(22));

            _currentHeightmap = creator.CreateDiamondSquareNoiseArray(new IntVector2(240, 240), 64);
            MyArrayUtils.Multiply(_currentHeightmap.HeightmapAsArray, 0.1f);

            _go = GameObject.CreatePrimitive(PrimitiveType.Quad);
            var material = new Material(Shader.Find("Custom/Terrain/Terrain_Debug"));

            _go.GetComponent <MeshRenderer>().material = material;
            _go.name = "Terrain";
            _go.transform.localRotation          = Quaternion.Euler(0, 0, 0);
            _go.transform.localScale             = new Vector3(10, 10, 10);
            _go.transform.localPosition          = new Vector3(0, 0, 0);
            _go.GetComponent <MeshFilter>().mesh = PlaneGenerator.CreateFlatPlaneMesh(240, 240);

            var doneTexture =
                HeightmapUtils.CreateTextureFromHeightmap(_currentHeightmap);

            _go.GetComponent <MeshRenderer>().material.SetTexture("_HeightmapTex0", doneTexture);
            _go.GetComponent <MeshRenderer>().material.SetTexture("_HeightmapTex1", doneTexture);
            _oldDoneTexture = doneTexture;
        }
Beispiel #4
0
        public void Start()
        {
            TaskUtils.SetGlobalMultithreading(false);
            var heightTex = SavingFileManager.LoadPngTextureFromFile(@"C:\inz\cont\smallCut.png", 240, 240,
                                                                     TextureFormat.RGBA32, true, true);

            _currentHeightmap = HeightmapUtils.CreateHeightmapArrayFromTexture(heightTex);

            MyArrayUtils.Normalize(_currentHeightmap.HeightmapAsArray);
            MyArrayUtils.InvertNormalized(_currentHeightmap.HeightmapAsArray);

            //for (int x = 0; x < 40; x++)
            //{
            //    for (int y = 0; y < 40; y++)
            //    {
            //        _currentHeightmap.HeightmapAsArray[90+x, 90+y] = 0;
            //    }
            //}

            CreateComparisionObject();
            MyArrayUtils.Multiply(_currentHeightmap.HeightmapAsArray, 400);


            Mei_RenderComputeShader();
        }
        public void AddElementArray(HeightmapArray heightmap, int textureIndex)
        {
            var colorArray = HeightmapUtils.CreateHeightTextureArray(heightmap);

            _textureArray.SetPixels(colorArray, textureIndex);
            _addedTexturesCount++;
        }
Beispiel #6
0
        public async Task <CoordedPart <MySimpleArray <float> > > GeneratePartAsync(MyRectangle queryArea)
        {
            var heightTexture = (await _terrainShapeDb.Query(new TerrainDescriptionQuery()
            {
                QueryArea = queryArea,
                RequestedElementDetails = new List <TerrainDescriptionQueryElementDetail>()
                {
                    new TerrainDescriptionQueryElementDetail()
                    {
                        Type = TerrainDescriptionElementTypeEnum.HEIGHT_ARRAY,
                        Resolution = _resolution
                    }
                }
            })).GetElementOfType(TerrainDescriptionElementTypeEnum.HEIGHT_ARRAY);

            var encodedTexture = await _transformator.PlainToEncodedHeightTextureAsync(
                heightTexture.TokenizedElement.DetailElement.Texture);

            var heightArray = HeightmapUtils.EncodedHeightToArray(encodedTexture);

            return(new CoordedPart <MySimpleArray <float> >()
            {
                Coords = queryArea,
                Part = heightArray
            });
        }
Beispiel #7
0
        public void Start_Mai()
        {
            var heightTexture1 = SavingFileManager.LoadPngTextureFromFile(@"C:\inz\cont\smallCut.png", 240,
                                                                          240, TextureFormat.RGBA32, true, true);
            var heightmap1 = HeightmapUtils.CreateHeightmapArrayFromTexture(heightTexture1);

            //DiamondSquareCreator creator = new DiamondSquareCreator(new RandomProvider(22));
            //var heightmap2 = creator.CreateDiamondSquareNoiseArray(new IntVector2(240, 240), 64);
            //MyArrayUtils.Multiply(heightmap2.HeightmapAsArray, 0.1f);
            HeightmapArray workingHeightmap = LoadHeightmapFromTextureFile(@"C:\inz\cont\temp3.png");

            MyArrayUtils.Normalize(workingHeightmap.HeightmapAsArray);
            MyArrayUtils.InvertNormalized(workingHeightmap.HeightmapAsArray);

            var generatedArrays = GenerateErodedArrays(workingHeightmap, new List <MeiHydraulicEroderConfiguration>()
            {
                new MeiHydraulicEroderConfiguration()
                {
                    StepCount           = 10,
                    A_PipeCrossSection  = 0.00005f,
                    ConstantWaterAdding = 1 / 16f,
                    GravityAcceleration = 9.81f,
                    DeltaT                   = 1 / 60f,
                    DepositionConstant       = 0.0001f * 12 * 10f,
                    DissolvingConstant       = 0.0001f * 12 * 10f,
                    EvaporationConstant      = 0.00011f * 0.5f * 10,
                    GridSize                 = new Vector2(1, 1),
                    L_PipeLength             = 1,
                    SedimentCapacityConstant = 25000
                },
            });

            CreateTestObject(workingHeightmap, generatedArrays);
        }
Beispiel #8
0
        public void Start_Hydraulic()
        {
            var heightTexture1 =
                SavingFileManager.LoadPngTextureFromFile(@"C:\inz\cont\temp3.png", 240, 240, TextureFormat.RGBA32, true,
                                                         true);
            var heightmap1 = HeightmapUtils.CreateHeightmapArrayFromTexture(heightTexture1);

            //DiamondSquareCreator creator = new DiamondSquareCreator(new RandomProvider(22));
            //var heightmap2 = creator.CreateDiamondSquareNoiseArray(new IntVector2(240, 240), 64);
            //MyArrayUtils.Multiply(heightmap2.HeightmapAsArray, 0.1f);

            var tParam = EroderDebugObject.CalculateFromHillFactor(1, new ArrayExtremes(0, 5000), 24);

            var extents = MyArrayUtils.CalculateExtremes(heightmap1.HeightmapAsArray);

            MyArrayUtils.Normalize(heightmap1.HeightmapAsArray);

            var erodedArrays = GenerateHydraulicErodedArrays(heightmap1, new List <HydraulicEroderConfiguration>()
            {
                new HydraulicEroderConfiguration()
                {
                    StepCount                  = 40,
                    NeighbourFinder            = NeighbourFinders.Big9Finder,
                    kr_ConstantWaterAddition   = 0.001f,
                    ks_GroundToSedimentFactor  = 1f,
                    ke_WaterEvaporationFactor  = 0.05f,
                    kc_MaxSedimentationFactor  = 0.8f,
                    FinalSedimentationToGround = true,
                    WaterGenerator             = HydraulicEroderWaterGenerator.AllFrames,
                    DestinationFinder          = HydraulicEroderWaterDestinationFinder.OnlyBest
                },
            });

            CreateTestObject(heightmap1, erodedArrays);
        }
Beispiel #9
0
        public HeightmapArray LoadHeightmapFromTextureFile(string pathToTemplateFile)
        {
            var tex = SavingFileManager.LoadPngTextureFromFile(pathToTemplateFile, 240, 240,
                                                               TextureFormat.ARGB32, false,
                                                               false);

            return(HeightmapUtils.CreateHeightmapArrayFromTexture(tex));
        }
Beispiel #10
0
        private TextureWithSize CreateBaseTexture(float height, DebugTerrainCharacter character)
        {
            if (character == DebugTerrainCharacter.Noise)
            {
                var texture = new RenderTexture(241, 241, 0, RenderTextureFormat.RFloat);
                texture.wrapMode   = TextureWrapMode.Clamp;
                texture.filterMode = FilterMode.Point;

                var material = new Material(Shader.Find("Custom/Tool/FillHeightTextureWithRandomValues"));
                material.SetTexture("_HeightTexture", texture);
                Graphics.Blit(texture, (RenderTexture)texture, material);
                return(new TextureWithSize()
                {
                    Texture = texture,
                    Size = new IntVector2(241, 241)
                });
            }
            else
            {
                float[,] heightArray;

                if (character == DebugTerrainCharacter.Flat)
                {
                    heightArray = MyArrayUtils.CreateFilled(241, 241, height);
                }
                else //if (character == DebugTerrainCharacter.Volcano)
                {
                    heightArray = new float[241, 241];
                    float minHeight = height * 0.2f;
                    float maxHeight = height;
                    for (int x = 0; x < 241; x++)
                    {
                        for (int y = 0; y < 241; y++)
                        {
                            heightArray[x, y] = Mathf.Lerp(minHeight, maxHeight,
                                                           1 - Vector2.Distance(new Vector2(x, y), new Vector2(120, 120)) / 200f);
                        }
                    }
                }
                var heightTex = HeightmapUtils.CreateTextureFromHeightmap(new HeightmapArray(heightArray));

                var transformator      = new TerrainTextureFormatTransformator(new CommonExecutorUTProxy());
                var plainHeightTexture = transformator.EncodedHeightTextureToPlain(new TextureWithSize()
                {
                    Size    = new IntVector2(241, 241),
                    Texture = heightTex
                });
                plainHeightTexture.wrapMode = TextureWrapMode.Clamp;
                return(new TextureWithSize()
                {
                    Size = new IntVector2(241, 241),
                    Texture = plainHeightTexture
                });
            }
        }
Beispiel #11
0
        public async Task <TextureWithCoords> ApplyFeatureAsync(TextureWithCoords texture,
                                                                TerrainCardinalResolution resolution, bool canMultistep)
        {
            var configuration = _configurations[resolution];

            var detailedHeightmapArray = await TaskUtils
                                         .RunInThreadPool(
                () =>
            {
                var creator      = new DiamondSquareCreator(_randomProviderGenerator.GetRandom());
                var initialArray = creator.CreateDiamondSquareNoiseArray(
                    texture.TextureSize,
                    configuration.DiamondSquareWorkingArrayLength);
                return(initialArray);
            });

            var detailedTexture = await _commonExecutor
                                  .AddAction(() => HeightmapUtils.CreateTextureFromHeightmap(detailedHeightmapArray));


            UniformsPack pack = new UniformsPack();

            pack.SetTexture("_Texture1", texture.Texture);
            pack.SetTexture("_Texture2", detailedTexture);
            pack.SetUniform("_Texture2Weight", configuration.DiamondSquareWeight);

            var renderCoords = new MyRectangle(0, 0, 1, 1);

            var outTextureSize = texture.TextureSize;

            ConventionalTextureInfo outTextureInfo =
                new ConventionalTextureInfo(outTextureSize.X, outTextureSize.Y, TextureFormat.ARGB32, true);
            TextureRenderingTemplate template = new TextureRenderingTemplate()
            {
                CanMultistep        = canMultistep,
                Coords              = renderCoords,
                OutTextureInfo      = outTextureInfo,
                RenderTextureFormat = RenderTextureFormat.RFloat,
                ShaderName          = "Custom/TerrainCreation/DiamondSquareTextureAddingPlain",
                UniformPack         = pack,
                CreateTexture2D     = false
            };

            var renderedTexture = await _rendererProxy.AddOrder(template);

            await _commonExecutor.AddAction(() => GameObject.Destroy(detailedTexture));

            return(new TextureWithCoords(sizedTexture: new TextureWithSize()
            {
                Texture = renderedTexture,
                Size = texture.TextureSize
            }, coords: texture.Coords));
        }
        public HeightmapArray CreateRing1HeightmapArray(HeightmapArray inputHeightmap)
        {
            assertInputHeightmapHasProperSize(inputHeightmap);
            var inputTexture =
                HeightmapUtils.CreateTextureFromHeightmap(inputHeightmap); // input texture is 256x256 (5.7x5.7) p22.3m
            var conventionalRing1Texture = RenderConventionalRing1Texture(inputTexture, new UniformsPack());
            var heightmapArray           = HeightmapUtils.CreateHeightmapArrayFromTexture(conventionalRing1Texture);

            DiamondSquareCreator diamondSquareCreator = new DiamondSquareCreator(new RandomProvider());

            heightmapArray = diamondSquareCreator.AddDetail(heightmapArray);
            return(heightmapArray);
        }
Beispiel #13
0
        public void StartY()
        {
            var heightTexture = SavingFileManager.LoadPngTextureFromFile(@"C:\inz\cont\smallCut.png", 240,
                                                                         240, TextureFormat.RGBA32, true, true);

            _currentHeightmap = HeightmapUtils.CreateHeightmapArrayFromTexture(heightTexture);
            var array = _currentHeightmap.HeightmapAsArray;

            MyArrayUtils.Multiply(array, 65000);
            var extremes = MyArrayUtils.CalculateExtremes(array);

            Debug.Log("Max: " + extremes.Max + " min: " + extremes.Min);
        }
Beispiel #14
0
        public void Start231()
        {
            string        bilFilePath    = @"C:\inz\cont\n49_e019_1arc_v3.bil";
            HeightmapFile heightmapFile  = new HeightmapFile();
            const int     filePixelWidth = 3601;

            heightmapFile.LoadFile(bilFilePath, 3601);
            heightmapFile.MirrorReflectHeightDataInXAxis();
            var heightArray = heightmapFile.GlobalHeightArray;

            var smallArray = HeightmapUtils.CutSubArray(heightArray, new IntArea(100, 100, 240, 240));

            SavingFileManager.SaveTextureToPngFile(@"C:\inz\cont\smallCut.png",
                                                   HeightmapUtils.CreateTextureFromHeightmap(smallArray));
        }
Beispiel #15
0
        public static float GetHeightAt(this Heightmap heightmap, int x, int y)
        {
            if (!IsValidCoordinate(heightmap, x, y) || x == 0 || y == 0 || x == heightmap.Size.X - 1 || y == heightmap.Size.Y - 1)
            {
                return(-heightmap.HeightRange.Y);
            }

            var index      = GetHeightIndex(heightmap, x, y);
            var heightData = heightmap.Shorts[index];

            var height = HeightmapUtils.ConvertToFloatHeight(short.MinValue, short.MaxValue, heightData);

            height *= heightmap.HeightRange.Y;

            return(height);
        }
Beispiel #16
0
        public static float GetTerrainHeight(this Heightmap heightmap, int x, int y)
        {
            if (!IsValidCoordinate(heightmap, x, y))
            {
                return(0.0f);
            }

            var index      = GetHeightIndex(heightmap, x, y);
            var heightData = heightmap.Shorts[index];

            var height = HeightmapUtils.ConvertToFloatHeight(short.MinValue, short.MaxValue, heightData);

            height *= heightmap.HeightRange.Y;

            return(height);
        }
        private void CreateComparisionObject()
        {
            _go = GameObject.CreatePrimitive(PrimitiveType.Quad);
            var material = new Material(Shader.Find("Custom/Terrain/Terrain_Debug"));

            _go.GetComponent <MeshRenderer>().material = material;
            _go.name = "Terrain";
            _go.transform.localRotation          = Quaternion.Euler(0, 0, 0);
            _go.transform.localScale             = new Vector3(10, 1, 10);
            _go.transform.localPosition          = new Vector3(0, 0, 0);
            _go.GetComponent <MeshFilter>().mesh = PlaneGenerator.CreateFlatPlaneMesh(240, 240);

            var doneTexture =
                HeightmapUtils.CreateTextureFromHeightmap(_currentHeightmap);

            _go.GetComponent <MeshRenderer>().material.SetTexture("_HeightmapTex0", doneTexture);
            _go.GetComponent <MeshRenderer>().material.SetTexture("_HeightmapTex1", doneTexture);
        }
Beispiel #18
0
        public void Start_Thermal()
        {
            var heightTexture1 = SavingFileManager.LoadPngTextureFromFile(@"C:\inz\cont\smallCut.png", 240,
                                                                          240, TextureFormat.RGBA32, true, true);
            var heightmap1 = HeightmapUtils.CreateHeightmapArrayFromTexture(heightTexture1);

            DiamondSquareCreator creator = new DiamondSquareCreator(new RandomProvider(22));
            var heightmap2 = creator.CreateDiamondSquareNoiseArray(new IntVector2(240, 240), 64);

            MyArrayUtils.Multiply(heightmap2.HeightmapAsArray, 0.1f);

            var tParam       = EroderDebugObject.CalculateFromHillFactor(1, new ArrayExtremes(0, 5000), 24);
            var erodedArrays = GenerateErodedArrays(heightmap1, new List <ThermalErosionConfiguration>()
            {
                new ThermalErosionConfiguration()
                {
                    CParam          = 0.5f,
                    StepCount       = 10,
                    TParam          = tParam * 0.6f,
                    NeighbourFinder = NeighbourFinders.Big9Finder,
                    GroundMover     = ThermalErosionGroundMovers.OnlyBestMover
                },
                new ThermalErosionConfiguration()
                {
                    CParam          = 0.5f,
                    StepCount       = 10,
                    TParam          = tParam * 0.6f,
                    NeighbourFinder = NeighbourFinders.Big9Finder,
                    GroundMover     = ThermalErosionGroundMovers.AllNeighboursMover
                },
                new ThermalErosionConfiguration()
                {
                    CParam            = 0.5f,
                    StepCount         = 10,
                    TParam            = tParam * 0.6f,
                    NeighbourFinder   = NeighbourFinders.Big9Finder,
                    GroundMover       = ThermalErosionGroundMovers.OnlyBestMoverTweaked,
                    NeighboursChooser = ThermalEroderNeighboursChoosers.LesserEqualThanTChooser
                },
            });

            CreateTestObject(heightmap1, erodedArrays);
        }
        public static UpdatedTerrainTextures GenerateDebugUpdatedTerrainTextures()
        {
            var height      = 1;
            var heightArray = new float[12, 12];

            for (int x = 0; x < 12; x++)
            {
                for (int y = 0; y < 12; y++)
                {
                    heightArray[x, y] = height;
                }
            }
            var ha = new HeightmapArray(heightArray);
            var encodedHeightTex = HeightmapUtils.CreateTextureFromHeightmap(ha);

            var transformer    = new TerrainTextureFormatTransformator(new CommonExecutorUTProxy());
            var plainHeightTex =
                transformer.EncodedHeightTextureToPlain(TextureWithSize.FromTex2D(encodedHeightTex));

            var normalArray = new Vector3[12, 12];

            for (int x = 0; x < 12; x++)
            {
                for (int y = 0; y < 12; y++)
                {
                    normalArray[x, y] = new Vector3(0.0f, 0.0f, 1.0f).normalized;
                }
            }
            var normalTexture = HeightmapUtils.CreateNormalTexture(normalArray);

            return(new UpdatedTerrainTextures()
            {
                HeightTexture = plainHeightTex,
                NormalTexture = normalTexture,
                TextureCoords = new MyRectangle(0, 0, 1, 1),
                TextureGlobalPosition = new MyRectangle(0, 0, 90, 90),
            });
        }
Beispiel #20
0
        public void Start_Hydraulic_Debuggable()
        {
            var heightTexture1 = SavingFileManager.LoadPngTextureFromFile(@"C:\inz\cont\smallCut.png", 240,
                                                                          240, TextureFormat.RGBA32, true, true);
            var heightmap1 = HeightmapUtils.CreateHeightmapArrayFromTexture(heightTexture1);

            //DiamondSquareCreator creator = new DiamondSquareCreator(new RandomProvider(22));
            //var heightmap2 = creator.CreateDiamondSquareNoiseArray(new IntVector2(240, 240), 64);
            //MyArrayUtils.Multiply(heightmap2.HeightmapAsArray, 0.1f);

            var tParam = EroderDebugObject.CalculateFromHillFactor(1, new ArrayExtremes(0, 5000), 24);

            var extents = MyArrayUtils.CalculateExtremes(heightmap1.HeightmapAsArray);

            MyArrayUtils.Normalize(heightmap1.HeightmapAsArray);

            var configuration =
                new HydraulicEroderConfiguration()
            {
                StepCount                  = 20,
                NeighbourFinder            = NeighbourFinders.Big9Finder,
                kr_ConstantWaterAddition   = 0.001f,
                ks_GroundToSedimentFactor  = 1f,
                ke_WaterEvaporationFactor  = 0.05f,
                kc_MaxSedimentationFactor  = 0.8f,
                FinalSedimentationToGround = false,
                WaterGenerator             = HydraulicEroderWaterGenerator.FirstFrame,
                DestinationFinder          = HydraulicEroderWaterDestinationFinder.OnlyBest
            };

            var copyArray          = MyArrayUtils.DeepClone(heightmap1.HeightmapAsArray);
            var currentHeightArray = new SimpleHeightArray(copyArray);
            var eroder             = new DebuggableHydraulicEroder();
            var debuggingOutput    = eroder.Erode(currentHeightArray, configuration, 1);

            var sedimentExtentsArr = debuggingOutput.SedimentSnapshots
                                     .Select(c => MyArrayUtils.CalculateExtremes(c.Array)).ToList();
            var sedimentExtents = new ArrayExtremes(sedimentExtentsArr.Min(c => c.Min),
                                                    sedimentExtentsArr.Max(c => c.Max));

            debuggingOutput.SedimentSnapshots.ForEach(c => MyArrayUtils.Normalize(c.Array, sedimentExtents));

            var waterExtentsArr = debuggingOutput.WaterSnapshots.Select(c => MyArrayUtils.CalculateExtremes(c.Array))
                                  .ToList();
            var waterExtents = new ArrayExtremes(waterExtentsArr.Min(c => c.Min), waterExtentsArr.Max(c => c.Max));

            debuggingOutput.WaterSnapshots.ForEach(c => MyArrayUtils.Normalize(c.Array, waterExtents));


            _go = GameObject.CreatePrimitive(PrimitiveType.Quad);
            var material = new Material(Shader.Find("Custom/Terrain/Terrain_Debug_Comparision_StepByStep"));

            _go.GetComponent <MeshRenderer>().material = material;
            _go.name = "Terrain";
            _go.transform.localRotation          = Quaternion.Euler(0, 0, 0);
            _go.transform.localScale             = new Vector3(10, 1, 10);
            _go.transform.localPosition          = new Vector3(0, 0, 0);
            _go.GetComponent <MeshFilter>().mesh = PlaneGenerator.CreateFlatPlaneMesh(240, 240);

            MyHeightTextureArray heightTextureArray =
                new MyHeightTextureArray(240, 240, 2, TextureFormat.ARGB32, false, true);

            heightTextureArray.AddElementArray(heightmap1, 0);
            heightTextureArray.AddElementArray(new HeightmapArray(currentHeightArray.Array), 1);
            _go.GetComponent <MeshRenderer>().material
            .SetTexture("_HeightmapTexArray", heightTextureArray.ApplyAndRetrive());


            MyHeightTextureArray waterArray = new MyHeightTextureArray(240, 240, debuggingOutput.WaterSnapshots.Count,
                                                                       TextureFormat.ARGB32, false, true);
            int i = 0;

            foreach (var waterSnapshot in debuggingOutput.WaterSnapshots)
            {
                waterArray.AddElementArray(new HeightmapArray(waterSnapshot.Array), i);
                i++;
            }
            _go.GetComponent <MeshRenderer>().material.SetTexture("_WaterArray", waterArray.ApplyAndRetrive());


            MyHeightTextureArray sedimentArray = new MyHeightTextureArray(240, 240,
                                                                          debuggingOutput.SedimentSnapshots.Count, TextureFormat.ARGB32, false, true);
            int j = 0;

            foreach (var sedimentSnapshot in debuggingOutput.SedimentSnapshots)
            {
                sedimentArray.AddElementArray(new HeightmapArray(sedimentSnapshot.Array), j);
                j++;
            }
            _go.GetComponent <MeshRenderer>().material.SetTexture("_SedimentArray", sedimentArray.ApplyAndRetrive());
        }
Beispiel #21
0
        public void Start_Mai_Debug()
        {
            var heightTexture1 = SavingFileManager.LoadPngTextureFromFile(@"C:\inz\cont\smallCut.png", 240,
                                                                          240, TextureFormat.RGBA32, true, true);
            var heightmap1 = HeightmapUtils.CreateHeightmapArrayFromTexture(heightTexture1);

            //DiamondSquareCreator creator = new DiamondSquareCreator(new RandomProvider(22));
            //var heightmap2 = creator.CreateDiamondSquareNoiseArray(new IntVector2(240, 240), 64);
            //MyArrayUtils.Multiply(heightmap2.HeightmapAsArray, 0.1f);
            //HeightmapArray workingHeightmap = LoadHeightmapFromTextureFile(@"C:\inz\cont\temp3.png");
            HeightmapArray workingHeightmap = heightmap1;

            MyArrayUtils.Normalize(workingHeightmap.HeightmapAsArray);
            MyArrayUtils.InvertNormalized(workingHeightmap.HeightmapAsArray);
            HeightmapArray originalMap = new HeightmapArray(MyArrayUtils.DeepClone(workingHeightmap.HeightmapAsArray));

            MyArrayUtils.Multiply(workingHeightmap.HeightmapAsArray, 400);

            var configuration = new MeiHydraulicEroderConfiguration()
            {
                StepCount           = 50,
                A_PipeCrossSection  = 0.05f,
                ConstantWaterAdding = 1 / 64f,
                GravityAcceleration = 9.81f,
                DeltaT                   = 1f,
                DepositionConstant       = 0.0001f * 12 * 2f,
                DissolvingConstant       = 0.0001f * 12 * 2f,
                EvaporationConstant      = 0.05f * 10,
                GridSize                 = new Vector2(1, 1),
                L_PipeLength             = 1,
                SedimentCapacityConstant = 250
            };

            var eroder    = new MeiHydraulicEroder();
            var debOutput = eroder.ErodeWithDebug(SimpleHeightArray.FromHeightmap(workingHeightmap), configuration);

            MyArrayUtils.Multiply(workingHeightmap.HeightmapAsArray, 1f / 400);
            debOutput.NormalizeInGroups();


            _go = GameObject.CreatePrimitive(PrimitiveType.Quad);
            var material = new Material(Shader.Find("Custom/Terrain/Terrain_Mei_Debug_Comparision_StepByStep"));

            _go.GetComponent <MeshRenderer>().material = material;
            _go.name = "Terrain";
            _go.transform.localRotation          = Quaternion.Euler(0, 0, 0);
            _go.transform.localScale             = new Vector3(10, 1, 10);
            _go.transform.localPosition          = new Vector3(0, 0, 0);
            _go.GetComponent <MeshFilter>().mesh = PlaneGenerator.CreateFlatPlaneMesh(240, 240);

            MyHeightTextureArray heightTextureArray =
                new MyHeightTextureArray(240, 240, 2, TextureFormat.ARGB32, false, true);

            heightTextureArray.AddElementArray(originalMap, 0);
            heightTextureArray.AddElementArray(workingHeightmap, 1);
            _go.GetComponent <MeshRenderer>().material
            .SetTexture("_HeightmapTexArray", heightTextureArray.ApplyAndRetrive());


            var arrayListsCount  = debOutput.OneArrayListCount;
            var arrayListsLength = debOutput.OneArrayListLength;
            MyHeightTextureArray detailHeightTexturesArray =
                new MyHeightTextureArray(240, 240, arrayListsCount * arrayListsLength, TextureFormat.ARGB32, false,
                                         true);

            foreach (var snapshot in debOutput.ArraysDict.Values.SelectMany(c => c))
            {
                detailHeightTexturesArray.AddElementArray(snapshot);
            }
            _go.GetComponent <MeshRenderer>().material
            .SetTexture("_DetailTexArray", detailHeightTexturesArray.ApplyAndRetrive());
            _go.GetComponent <MeshRenderer>().material.SetFloat("_DetailTexLength", arrayListsLength);
        }
            protected override Task <ResultStatus> DoCommandOverride(ICommandContext commandContext)
            {
                var assetManager = new ContentManager(MicrothreadLocalDatabases.ProviderService);

                Heightmap heightmap = null;

                var heightType  = Parameters.HeightConversionParameters.HeightType;
                var heightScale = Parameters.HeightConversionParameters.HeightScale;
                var heightRange = Parameters.HeightConversionParameters.HeightRange;

                // Heights

                var source = Parameters.Source;

                using (var textureTool = new TextureTool())
                    using (var texImage = textureTool.Load(source, Parameters.IsSRgb))
                    {
                        // Resize if needed.

                        var size = Parameters.Resizing.Enabled
                        ? Parameters.Resizing.Size
                        : new Int2(texImage.Width, texImage.Height);

                        HeightmapUtils.CheckHeightParameters(size, heightType, heightRange, heightScale, true);

                        // Convert the pixel format to single component one.

                        var isConvertedR16 = false;

                        switch (texImage.Format)
                        {
                        case PixelFormat.R32_Float:
                        case PixelFormat.R16_SNorm:
                        case PixelFormat.R8_UNorm:
                            break;

                        case PixelFormat.R32G32B32A32_Float:
                        case PixelFormat.R16G16B16A16_Float:
                        case PixelFormat.R16_Float:
                            textureTool.Convert(texImage, PixelFormat.R32_Float);
                            break;

                        case PixelFormat.R16_UNorm:
                        case PixelFormat.R16G16B16A16_UNorm:
                        case PixelFormat.R16G16_UNorm:
                            textureTool.Convert(texImage, PixelFormat.R16_SNorm);
                            isConvertedR16 = true;
                            break;

                        case PixelFormat.R16G16B16A16_SNorm:
                        case PixelFormat.R16G16_SNorm:
                            textureTool.Convert(texImage, PixelFormat.R16_SNorm);
                            break;

                        case PixelFormat.R8_SNorm:
                        case PixelFormat.B8G8R8A8_UNorm:
                        case PixelFormat.B8G8R8X8_UNorm:
                        case PixelFormat.R8G8B8A8_UNorm:
                        case PixelFormat.R8G8_UNorm:
                            textureTool.Convert(texImage, PixelFormat.R8_UNorm);
                            break;

                        case PixelFormat.R8G8B8A8_SNorm:
                        case PixelFormat.R8G8_SNorm:
                            textureTool.Convert(texImage, PixelFormat.R8_UNorm);
                            break;

                        case PixelFormat.B8G8R8A8_UNorm_SRgb:
                        case PixelFormat.B8G8R8X8_UNorm_SRgb:
                        case PixelFormat.R8G8B8A8_UNorm_SRgb:
                            textureTool.Convert(texImage, PixelFormat.R8_UNorm);
                            break;

                        default:
                            throw new Exception($"{ texImage.Format } format is not supported.");
                        }

                        // Convert pixels to heights

                        using (var image = textureTool.ConvertToStrideImage(texImage))
                        {
                            var pixelBuffer     = image.PixelBuffer[0];
                            var pixelBufferSize = new Int2(pixelBuffer.Width, pixelBuffer.Height);

                            var minFloat = Parameters.FloatingPointComponentRange.X;
                            var maxFloat = Parameters.FloatingPointComponentRange.Y;
                            var isSNorm  = (Math.Abs(-1 - minFloat) < float.Epsilon) && (Math.Abs(1 - maxFloat) < float.Epsilon);

                            if (maxFloat < minFloat)
                            {
                                throw new Exception($"{ nameof(Parameters.FloatingPointComponentRange) }.{ nameof(Parameters.FloatingPointComponentRange.Y) } should be greater than { nameof(Parameters.FloatingPointComponentRange.X) }.");
                            }

                            var useScaleToRange = Parameters.ScaleToHeightRange;

                            switch (heightType)
                            {
                            case HeightfieldTypes.Float:
                            {
                                float[] floats = null;

                                switch (image.Description.Format)
                                {
                                case PixelFormat.R32_Float:
                                    floats = HeightmapUtils.Resize(pixelBuffer.GetPixels <float>(), pixelBufferSize, size);
                                    floats = isSNorm ?
                                             floats :
                                             HeightmapUtils.ConvertToFloatHeights(floats, minFloat, maxFloat);
                                    break;

                                case PixelFormat.R16_SNorm:
                                    var shorts = HeightmapUtils.Resize(pixelBuffer.GetPixels <short>(), pixelBufferSize, size);
                                    floats = !isConvertedR16 && Parameters.IsSymmetricShortComponent ?
                                             HeightmapUtils.ConvertToFloatHeights(shorts, -short.MaxValue, short.MaxValue) :
                                             HeightmapUtils.ConvertToFloatHeights(shorts);
                                    break;

                                case PixelFormat.R8_UNorm:
                                    var bytes = HeightmapUtils.Resize(pixelBuffer.GetPixels <byte>(), pixelBufferSize, size);
                                    floats = HeightmapUtils.ConvertToFloatHeights(bytes);
                                    break;
                                }

                                if (useScaleToRange)
                                {
                                    ScaleToHeightRange(floats, -1, 1, heightRange, heightScale, commandContext);
                                }

                                heightmap = Heightmap.Create(size, heightType, heightRange, heightScale, floats);
                            }
                            break;

                            case HeightfieldTypes.Short:
                            {
                                short[] shorts = null;

                                switch (image.Description.Format)
                                {
                                case PixelFormat.R32_Float:
                                    var floats = HeightmapUtils.Resize(pixelBuffer.GetPixels <float>(), pixelBufferSize, size);
                                    shorts = HeightmapUtils.ConvertToShortHeights(floats, minFloat, maxFloat);
                                    break;

                                case PixelFormat.R16_SNorm:
                                    shorts = HeightmapUtils.Resize(pixelBuffer.GetPixels <short>(), pixelBufferSize, size);
                                    shorts = !isConvertedR16 && Parameters.IsSymmetricShortComponent ?
                                             shorts :
                                             HeightmapUtils.ConvertToShortHeights(shorts);
                                    break;

                                case PixelFormat.R8_UNorm:
                                    var bytes = HeightmapUtils.Resize(pixelBuffer.GetPixels <byte>(), pixelBufferSize, size);
                                    shorts = HeightmapUtils.ConvertToShortHeights(bytes);
                                    break;
                                }

                                if (useScaleToRange)
                                {
                                    ScaleToHeightRange(shorts, short.MinValue, short.MaxValue, heightRange, heightScale, commandContext);
                                }

                                heightmap = Heightmap.Create(size, heightType, heightRange, heightScale, shorts);
                            }
                            break;

                            case HeightfieldTypes.Byte:
                            {
                                byte[] bytes = null;

                                switch (image.Description.Format)
                                {
                                case PixelFormat.R32_Float:
                                    var floats = HeightmapUtils.Resize(pixelBuffer.GetPixels <float>(), pixelBufferSize, size);
                                    bytes = HeightmapUtils.ConvertToByteHeights(floats, minFloat, maxFloat);
                                    break;

                                case PixelFormat.R16_SNorm:
                                    var shorts = HeightmapUtils.Resize(pixelBuffer.GetPixels <short>(), pixelBufferSize, size);
                                    bytes = !isConvertedR16 && Parameters.IsSymmetricShortComponent ?
                                            HeightmapUtils.ConvertToByteHeights(shorts, -short.MaxValue, short.MaxValue) :
                                            HeightmapUtils.ConvertToByteHeights(shorts);
                                    break;

                                case PixelFormat.R8_UNorm:
                                    bytes = HeightmapUtils.Resize(pixelBuffer.GetPixels <byte>(), pixelBufferSize, size);
                                    break;
                                }

                                if (useScaleToRange)
                                {
                                    ScaleToHeightRange(bytes, byte.MinValue, byte.MaxValue, heightRange, heightScale, commandContext);
                                }

                                heightmap = Heightmap.Create(size, heightType, heightRange, heightScale, bytes);
                            }
                            break;

                            default:
                                throw new Exception($"{ heightType } height type is not supported.");
                            }

                            commandContext.Logger.Info(
                                $"[{Url}] Convert Image(Format={ texImage.Format }, Width={ texImage.Width }, Height={ texImage.Height }) " +
                                $"to Heightmap(HeightType={ heightType }, MinHeight={ heightRange.X }, MaxHeight={ heightRange.Y }, HeightScale={ heightScale }, Size={ size }).");
                        }
                    }

                if (heightmap == null)
                {
                    throw new Exception($"Failed to compile { Url }.");
                }

                assetManager.Save(Url, heightmap);

                return(Task.FromResult(ResultStatus.Successful));
            }