public void TerrainToolboxUtilities_WhenSplitTerrain_HeightmapResolutionIsCorrect(int xSplit, int zSplit, int originalHeightmapRes)
        {
            TerrainToolboxWindow toolboxWindow   = EditorWindow.GetWindow(typeof(TerrainToolboxWindow)) as TerrainToolboxWindow;
            Texture2D            gradientTexture = CreateGradientTexture();
            int baseLevel     = 0;
            int remapLevel    = 1;
            int numberOfTiles = 1;

            ToolboxHelper.CopyTextureToTerrainHeight(m_TerrainComponent.terrainData, gradientTexture, Vector2Int.zero, originalHeightmapRes, numberOfTiles, baseLevel, remapLevel);

            Selection.activeGameObject = m_TerrainGO;
            m_TerrainGO.name           = "TestTerrain";
            m_TerrainComponent.name    = "TestComponent";

            RenderTexture oldRT = RenderTexture.active;

            RenderTexture.active = m_TerrainComponent.terrainData.heightmapTexture;

            // Run the test
            TestSplitTerrainHeightmapResolution(toolboxWindow, originalHeightmapRes, xSplit, zSplit);

            AssetDatabase.Refresh();
            RenderTexture.active = oldRT;
            toolboxWindow.Close();
        }
        void GetAndSetActiveRenderPipelineSettings()
        {
            ToolboxHelper.RenderPipeline m_ActiveRenderPipeline = ToolboxHelper.GetRenderPipeline();
            m_VisualizationMaterial = AssetDatabase.LoadAssetAtPath <Material>("Packages/com.unity.terrain-tools/editor/terraintoolbox/materials/terrainvisualization.mat");

            switch (m_ActiveRenderPipeline)
            {
            case ToolboxHelper.RenderPipeline.HD:
                m_VisualizationMaterial.shader = AssetDatabase.LoadAssetAtPath <Shader>(k_HDRPShaderPath);
                break;

            case ToolboxHelper.RenderPipeline.Universal:
                m_VisualizationMaterial.shader = AssetDatabase.LoadAssetAtPath <Shader>(k_URPShaderPath);
                break;

            default:
                if (m_Terrains == null || m_Terrains.Count == 0)
                {
                    break;
                }
#if UNITY_2019_2_OR_NEWER
#else
                m_TerrainMaterialType = m_Terrains[0].materialType;
                if (m_TerrainMaterialType == Terrain.MaterialType.BuiltInLegacySpecular)
                {
                    m_TerrainLegacyShininess = m_Terrains[0].legacyShininess;
                    m_TerrainLegacySpecular  = m_Terrains[0].legacySpecular;
                }
#endif
                m_VisualizationMaterial.shader = Shader.Find("Hidden/Builtin_TerrainVisualization");
                break;
            }
        }
        public void ToggleVisualization()
        {
            if (GameObject.FindObjectOfType <Terrain>() == null)
            {
                m_selectedMode         = VISUALIZERMODE.None;
                m_Settings.ModeWarning = true;
                return;
            }

            if (m_Terrains == null || GameObject.FindObjectsOfType <Terrain>().Length != m_Terrains.Count || m_Terrains[0] == null)
            {
                m_Terrains.Clear();
                m_Terrains.AddRange(ToolboxHelper.GetAllTerrainsInScene());
                m_Settings.TerrainMaxHeight = m_Terrains[0].terrainData.size.y;
            }


            switch (m_selectedMode)
            {
            case VISUALIZERMODE.AltitudeHeatmap:
                RevertMaterial();
                RefreshTerrainInScene();
                UpdateHeatmapSettings();
                break;

            case VISUALIZERMODE.None:
                RevertMaterial();
                break;
            }

            m_ModeWarning  = false;
            m_previousMode = m_selectedMode;
        }
 public void HeightmapResolutionsArePowerOfTwoPlusOne()
 {
     // this currently doesn't fail, but its possible that there are times
     foreach (var heightmapResolution in ToolboxHelper.GUIHeightmapResolutions)
     {
         Assert.That(ToolboxHelper.IsPowerOfTwo(heightmapResolution - 1), Is.True);
     }
 }
 public void IsPowerOfTwo()
 {
     // confirm for the first 100 powers of two
     for (int i = 0; i < 100; i++)
     {
         Assert.That(ToolboxHelper.IsPowerOfTwo((int)Mathf.Pow(2, i)), Is.True);
     }
 }
 public void GetValidSaveDirectory()
 {
     // when requesting outside application data path, return a path relative to assets
     Assert.That(ToolboxHelper.GetProjectRelativeSaveDirectory(Application.dataPath + "/.."), Is.EqualTo("Assets"));
     Assert.That(ToolboxHelper.GetProjectRelativeSaveDirectory("Assets"), Is.EqualTo("Assets"));
     Assert.That(ToolboxHelper.GetProjectRelativeSaveDirectory("Assets/Test/"), Is.EqualTo("Assets/Test/"));
     Assert.That(ToolboxHelper.IsDirectoryWithinAssets("Assets/Test/"), Is.True);
     Assert.That(ToolboxHelper.IsDirectoryWithinAssets("Assets/../.."), Is.False);
     Assert.That(ToolboxHelper.IsDirectoryWithinAssets("Assetsasdf"), Is.False);
     // prefixed slashes to raise an exception within this function
     Assert.That(ToolboxHelper.IsDirectoryWithinAssets("/Assets"), Is.False);
 }
        public void TerrainToolboxUtilites_WhenExportHeightmap_LevelCorrectionWorks(float min, float max, Heightmap.Format format, Heightmap.Depth depth = Heightmap.Depth.Bit16)
        {
            TerrainToolboxWindow toolboxWindow   = EditorWindow.GetWindow(typeof(TerrainToolboxWindow)) as TerrainToolboxWindow;
            Texture2D            gradientTexture = CreateGradientTexture();

            int heightmapResolution = 513;
            int numberOfTiles       = 1;
            int baseLevel           = 0;
            int remapLevel          = 1;

            ToolboxHelper.CopyTextureToTerrainHeight(m_TerrainComponent.terrainData, gradientTexture, Vector2Int.zero, heightmapResolution, numberOfTiles, baseLevel, remapLevel);

            Selection.activeGameObject = m_TerrainGO;
            m_TerrainGO.name           = "TestTerrain";
            m_TerrainComponent.name    = "TestComponent";

            RenderTexture oldRT = RenderTexture.active;

            RenderTexture.active = m_TerrainComponent.terrainData.heightmapTexture;

            //Run Tests and Cleanup files
            string fileName = m_TerrainGO.name + "_heightmap";
            string path     = Path.Combine(toolboxWindow.m_TerrainUtilitiesMode.m_Settings.HeightmapFolderPath, fileName);

            switch (format)
            {
            case Heightmap.Format.PNG:
                path += ".png";
                Assert.IsTrue(TestLevelCorrection(toolboxWindow, new Vector2(min, max), path, format));
                FileUtil.DeleteFileOrDirectory(path);
                FileUtil.DeleteFileOrDirectory(path + ".meta");
                break;

            case Heightmap.Format.TGA:
                path += ".tga";
                Assert.IsTrue(TestLevelCorrection(toolboxWindow, new Vector2(min, max), path, format));
                FileUtil.DeleteFileOrDirectory(path);
                FileUtil.DeleteFileOrDirectory(path + ".meta");
                break;

            case Heightmap.Format.RAW:
                path += ".raw";
                Assert.IsTrue(TestLevelCorrection(toolboxWindow, new Vector2(min, max), path, depth));
                FileUtil.DeleteFileOrDirectory(path);
                FileUtil.DeleteFileOrDirectory(path + ".meta");
                break;
            }

            AssetDatabase.Refresh();
            RenderTexture.active = oldRT;
            toolboxWindow.Close();
        }
        void LoadSettings()
        {
            string filePath = ToolboxHelper.GetPrefFilePath(ToolboxHelper.ToolboxPrefsWindow);

            if (File.Exists(filePath))
            {
                string windowSettingsData = File.ReadAllText(filePath);
                int    value = 0;
                if (int.TryParse(windowSettingsData, out value))
                {
                    m_SelectedMode = (TerrainManagerMode)value;
                }
            }
        }
예제 #9
0
        public void SaveSettings()
        {
            if (m_SelectedPreset != null)
            {
                m_Settings.PresetPath = AssetDatabase.GetAssetPath(m_SelectedPreset);
            }
            else
            {
                m_Settings.PresetPath = string.Empty;
            }

            string filePath     = ToolboxHelper.GetPrefFilePath(ToolboxHelper.ToolboxPrefsSettings);
            string settingsData = JsonUtility.ToJson(m_Settings);

            File.WriteAllText(filePath, settingsData);
        }
        public void FlipTexture()
        {
            var texture = new Texture2D(2, 2);

            texture.SetPixels(new [] { Color.white, Color.black, Color.black, Color.black });
            texture.Apply();
            ToolboxHelper.FlipTexture(texture, true);
            var horizontalFlip = texture.GetPixels();

            Assert.That(horizontalFlip[1], Is.EqualTo(Color.white));

            ToolboxHelper.FlipTexture(texture, false);
            var verticalFlip = texture.GetPixels();

            Assert.That(verticalFlip[3], Is.EqualTo(Color.white));
        }
        // Unity PNG encoder does not support 16bit export, change will come later 2019
        public static void ExportTerrainHeightsToTexture(TerrainData terrainData, Heightmap.Format format, string path, bool flipVertical, Vector2 inputLevelsRange)
        {
            RenderTexture oldRT   = RenderTexture.active;
            int           width   = terrainData.heightmapTexture.width - 1;
            int           height  = terrainData.heightmapTexture.height - 1;
            var           texture = new Texture2D(width, height, terrainData.heightmapTexture.graphicsFormat, TextureCreationFlags.None);

            RenderTexture.active = terrainData.heightmapTexture;
            texture.ReadPixels(new Rect(0, 0, width, height), 0, 0);

            //Remap Texture
            Color[] pixels = texture.GetPixels();
            for (int i = 0; i < pixels.Length; i += 4)
            {
                pixels[i].r     = (pixels[i].r * 2) * (inputLevelsRange.y - inputLevelsRange.x) + inputLevelsRange.x;
                pixels[i + 1].r = (pixels[i + 1].r * 2) * (inputLevelsRange.y - inputLevelsRange.x) + inputLevelsRange.x;
                pixels[i + 2].r = (pixels[i + 2].r * 2) * (inputLevelsRange.y - inputLevelsRange.x) + inputLevelsRange.x;
                pixels[i + 3].r = (pixels[i + 3].r * 2) * (inputLevelsRange.y - inputLevelsRange.x) + inputLevelsRange.x;
            }
            texture.SetPixels(pixels);
            texture.Apply();

            //Flip Texture
            if (flipVertical)
            {
                ToolboxHelper.FlipTexture(texture, true);
            }

            byte[] bytes;
            switch (format)
            {
            case Heightmap.Format.TGA:
                bytes = texture.EncodeToTGA();
                path  = path + ".tga";
                break;

            default:
                bytes = texture.EncodeToPNG();
                path  = path + ".png";
                break;
            }

            File.WriteAllBytes(path, bytes);
            RenderTexture.active = oldRT;
        }
예제 #12
0
        void GetAndSetActiveRenderPipelineSettings()
        {
            ToolboxHelper.RenderPipeline m_ActiveRenderPipeline = ToolboxHelper.GetRenderPipeline();
            switch (m_ActiveRenderPipeline)
            {
            case ToolboxHelper.RenderPipeline.HD:
                m_MaxLayerCount = kMaxLayerHD;
                break;

            case ToolboxHelper.RenderPipeline.LW:
                m_MaxLayerCount = kMaxNoLimit;
                break;

            default:
                m_MaxLayerCount = kMaxNoLimit;
                break;
            }
        }
예제 #13
0
        public void LoadSettings()
        {
            string filePath = ToolboxHelper.GetPrefFilePath(ToolboxHelper.ToolboxPrefsSettings);

            if (File.Exists(filePath))
            {
                string settingsData = File.ReadAllText(filePath);
                JsonUtility.FromJsonOverwrite(settingsData, m_Settings);
            }

            if (m_Settings.PresetPath == string.Empty)
            {
                m_SelectedPreset = null;
            }
            else
            {
                m_SelectedPreset = AssetDatabase.LoadAssetAtPath(m_Settings.PresetPath, typeof(TerrainSettings)) as TerrainSettings;
            }
        }
        void RefreshTerrainInScene()
        {
            m_Terrains.Clear();
            m_Terrains.AddRange(ToolboxHelper.GetAllTerrainsInScene());
            if (m_Terrains.Count == 0)
            {
                m_ModeWarning = true;
                return;
            }

            m_TerrainMaxHeight = m_Terrains.Max(t => t.terrainData.size.y);

            m_TerrainMaterials.Clear();
            foreach (Terrain terrain in m_Terrains)
            {
                m_TerrainMaterials.Add(terrain.materialTemplate);
            }

            m_ModeWarning = false;
        }
        public void SaveSettings()
        {
            if (m_SelectedPreset != null)
            {
                m_PresetPath = AssetDatabase.GetAssetPath(m_SelectedPreset);
            }
            else
            {
                m_PresetPath = string.Empty;
            }

            string filePath     = ToolboxHelper.GetPrefFilePath(ToolboxHelper.ToolboxPrefsVisualization);
            string settingsData = JsonUtility.ToJson(m_Settings);

            File.WriteAllText(filePath, settingsData);
            SceneView.RepaintAll();

            EditorSceneManager.sceneSaving         -= OnSceneSaving;
            EditorSceneManager.sceneSaved          -= OnSceneSaved;
            EditorSceneManager.sceneOpened         -= OnSceneOpened;
            EditorApplication.playModeStateChanged -= PlayModeChanged;
            Undo.undoRedoPerformed -= OnUndo;
        }
        public void LoadSettings()
        {
            string filePath = ToolboxHelper.GetPrefFilePath(ToolboxHelper.ToolboxPrefsVisualization);

            if (File.Exists(filePath))
            {
                string settingsData = File.ReadAllText(filePath);
                JsonUtility.FromJsonOverwrite(settingsData, m_Settings);
            }

            if (m_PresetPath == string.Empty)
            {
                m_SelectedPreset = null;
            }
            else
            {
                m_SelectedPreset = AssetDatabase.LoadAssetAtPath(m_PresetPath, typeof(TerrainVisualizationSettings)) as TerrainVisualizationSettings;
            }
            EditorSceneManager.sceneSaving         += OnSceneSaving;
            EditorSceneManager.sceneSaved          += OnSceneSaved;
            EditorSceneManager.sceneOpened         += OnSceneOpened;
            EditorApplication.playModeStateChanged += PlayModeChanged;
            Undo.undoRedoPerformed += OnUndo;
        }
예제 #17
0
        void ApplySettingsToTerrains(Terrain[] terrains, string errorContext = "")
        {
            int index = 0;

            try
            {
                bool continueEdit = true;

                // Only show this warning if the user has Mesh Settings enabled.
                if (m_Settings.EnableMeshResSettings)
                {
                    var newSize = new Vector3(m_Settings.TerrainWidth, m_Settings.TerrainHeight,
                                              m_Settings.TerrainLength);
                    foreach (var terrain in terrains)
                    {
                        // If any terrain has a size that's different from the specified settings, let's confirm
                        // the action.
                        if (terrain.terrainData.size != newSize)
                        {
                            var message =
                                "Some terrains have different sizes than the settings specified. This operation will resize the terrains potentially resulting in gaps and/or overlaps.";
                            if (string.IsNullOrEmpty(errorContext))
                            {
                                continueEdit = EditorUtility.DisplayDialog("Confirm",
                                                                           $"{message}\nAre you sure you want to continue?",
                                                                           "Continue", "Cancel");
                            }
                            else
                            {
                                continueEdit = EditorUtility.DisplayDialog("Confirm",
                                                                           $"1. {errorContext}\n2. {message}\n\nAre you sure you want to continue?",
                                                                           "Continue", "Cancel");
                            }
                            break;
                        }
                    }
                }

                if (continueEdit)
                {
                    foreach (var terrain in terrains)
                    {
                        EditorUtility.DisplayProgressBar("Applying settings changes on terrains",
                                                         string.Format("Updating terrain tile {0}", terrain.name),
                                                         ((float)index / terrains.Length));

                        if (m_Settings.EnableBasicSettings)
                        {
                            Undo.RecordObject(terrain, "Terrain property change");

                            terrain.groupingID           = m_Settings.GroupingID;
                            terrain.allowAutoConnect     = m_Settings.AutoConnect;
                            terrain.drawHeightmap        = m_Settings.DrawHeightmap;
                            terrain.drawInstanced        = m_Settings.DrawInstanced;
                            terrain.heightmapPixelError  = m_Settings.PixelError;
                            terrain.basemapDistance      = m_Settings.BaseMapDistance;
                            terrain.shadowCastingMode    = m_Settings.ShadowCastingMode;
                            terrain.materialTemplate     = m_Settings.MaterialTemplate;
                            terrain.reflectionProbeUsage = m_Settings.ReflectionProbeUsage;
#if UNITY_2019_2_OR_NEWER
#else
                            terrain.materialType = m_Settings.MaterialType;
                            if (m_Settings.MaterialType != Terrain.MaterialType.Custom)
                            {
                                terrain.legacySpecular  = m_Settings.LegacySpecular;
                                terrain.legacyShininess = m_Settings.LegacyShininess;
                            }
#endif
                        }

                        if (m_Settings.EnableMeshResSettings)
                        {
                            Undo.RecordObject(terrain.terrainData, "TerrainData property change");
                            Vector3 size = new Vector3(m_Settings.TerrainWidth, m_Settings.TerrainHeight,
                                                       m_Settings.TerrainLength);
                            terrain.terrainData.size = size;
                            terrain.terrainData.SetDetailResolution(m_Settings.DetailResolutaion,
                                                                    m_Settings.DetailResolutionPerPatch);
                        }

                        if (m_Settings.EnableTextureResSettings)
                        {
                            terrain.terrainData.baseMapResolution = m_Settings.BaseTextureResolution;
                            if (m_Settings.AlphaMapResolution != terrain.terrainData.alphamapResolution)
                            {
                                ToolboxHelper.ResizeControlTexture(terrain.terrainData, m_Settings.AlphaMapResolution);
                            }

                            if (m_Settings.HeightMapResolution != terrain.terrainData.heightmapResolution)
                            {
                                ToolboxHelper.ResizeHeightmap(terrain.terrainData, m_Settings.HeightMapResolution);
                            }
                        }

                        if (m_Settings.EnableTreeSettings)
                        {
                            Undo.RecordObject(terrain, "Terrain property change");

                            terrain.drawTreesAndFoliage         = m_Settings.DrawTreesAndFoliage;
                            terrain.bakeLightProbesForTrees     = m_Settings.BakeLightProbesForTrees;
                            terrain.deringLightProbesForTrees   = m_Settings.DeringLightProbesForTrees;
                            terrain.preserveTreePrototypeLayers = m_Settings.PreserveTreePrototypeLayers;
                            terrain.detailObjectDistance        = m_Settings.DetailObjectDistance;
                            terrain.collectDetailPatches        = m_Settings.CollectDetailPatches;
                            terrain.detailObjectDensity         = m_Settings.DetailObjectDensity;
                            terrain.treeDistance            = m_Settings.TreeDistance;
                            terrain.treeBillboardDistance   = m_Settings.TreeBillboardDistance;
                            terrain.treeCrossFadeLength     = m_Settings.TreeCrossFadeLength;
                            terrain.treeMaximumFullLODCount = m_Settings.TreeMaximumFullLODCount;
                        }

                        if (m_Settings.EnableWindSettings)
                        {
                            Undo.RecordObject(terrain.terrainData, "TerrainData property change");
                            terrain.terrainData.wavingGrassStrength = m_Settings.WavingGrassStrength;
                            terrain.terrainData.wavingGrassSpeed    = m_Settings.WavingGrassSpeed;
                            terrain.terrainData.wavingGrassAmount   = m_Settings.WavingGrassAmount;
                            terrain.terrainData.wavingGrassTint     = m_Settings.WavingGrassTint;
                        }

                        index++;
                    }
                }
            }
            finally
            {
                AssetDatabase.Refresh();
                EditorUtility.ClearProgressBar();
            }
        }
        void SaveSettings()
        {
            string filePath = ToolboxHelper.GetPrefFilePath(ToolboxHelper.ToolboxPrefsWindow);

            File.WriteAllText(filePath, ((int)m_SelectedMode).ToString());
        }