예제 #1
0
        public static void Restore(string backupName)
        {
            List <GStylizedTerrain> terrains = new List <GStylizedTerrain>(GStylizedTerrain.ActiveTerrains);

            for (int i = 0; i < terrains.Count; ++i)
            {
                GStylizedTerrain t = terrains[i];
                if (t.TerrainData == null)
                {
                    continue;
                }
                try
                {
#if UNITY_EDITOR
                    GCommonGUI.ProgressBar("Restoring", "Restoring " + t.name + " data...", 1f);
#endif
                    RestoreTerrain(t, backupName);
                }
                catch (System.Exception e)
                {
                    Debug.LogError(string.Format("Error on restoring {0}: {1}", e.ToString(), t.name));
                }
                finally
                {
#if UNITY_EDITOR
                    GCommonGUI.ClearProgressBar();
#endif
                }
            }
            GStylizedTerrain.MatchEdges(-1);
            GUndoCompatibleBuffer.Instance.CurrentBackupName = backupName;
        }
예제 #2
0
        public List <GStylizedTerrain> Convert()
        {
            try
            {
                Validate();
                Initialize();
                if (DataTemplate == null)
                {
                    CreateSharedData();
                }
                ImportDataAndCreateTerrain();
                FinishingUp();
            }
            catch (GProgressCancelledException)
            {
                Debug.Log("Converting process canceled!");
            }
            catch (System.Exception e)
            {
                Debug.LogError(e.ToString());
            }
            finally
            {
#if UNITY_EDITOR
                GCommonGUI.ClearProgressBar();
#endif
            }

            return(ConvertedTerrains);
        }
        public void Convert()
        {
            try
            {
                Validate();
                SaveAssets();
                Initialize();
                CreateSharedData();
                CreateTerrainAndImportData();
                FinishingUp();
            }
            catch (GProgressCancelledException)
            {
                Debug.Log("Converting process canceled!");
            }
            catch (System.Exception e)
            {
                Debug.LogError(e.ToString());
            }
            finally
            {
#if UNITY_EDITOR
                GCommonGUI.ClearProgressBar();
#endif
            }
        }
예제 #4
0
        public void CreateStaticObstacles()
        {
            transform.root.position   = Vector3.zero;
            transform.root.rotation   = Quaternion.identity;
            transform.root.localScale = Vector3.one;
            transform.position        = Vector3.zero;
            transform.rotation        = Quaternion.identity;
            transform.localScale      = Vector3.one;

            try
            {
                IEnumerator <GStylizedTerrain> terrains = GStylizedTerrain.ActiveTerrains.GetEnumerator();
                while (terrains.MoveNext())
                {
                    GStylizedTerrain t = terrains.Current;
                    if (groupId < 0 ||
                        (groupId >= 0 && groupId == t.GroupId))
                    {
                        CreateStaticObstacles(t);
                    }
                }
            }
            catch (GProgressCancelledException)
            {
                Debug.Log("Create static obstacles process canceled!");
#if UNITY_EDITOR
                GCommonGUI.ClearProgressBar();
#endif
            }
        }
예제 #5
0
        public void Apply()
        {
            if (falloffTexture != null)
            {
                Object.DestroyImmediate(falloffTexture);
            }
            Internal_UpdateFalloffTexture();
            Internal_UpdateLayerTransitionTextures();
            IEnumerator <GStylizedTerrain> terrains = GStylizedTerrain.ActiveTerrains.GetEnumerator();

            try
            {
                while (terrains.MoveNext())
                {
                    GStylizedTerrain t = terrains.Current;
                    if (groupId < 0 ||
                        (groupId >= 0 && groupId == t.GroupId))
                    {
                        Apply(t);
                    }
                }
            }
            catch (GProgressCancelledException)
            {
                Debug.Log("Stamp process canceled, result may be incorrect. Use History to clean up!");
#if UNITY_EDITOR
                GCommonGUI.ClearProgressBar();
#endif
            }
        }
예제 #6
0
        public static bool TryCreateBackup(string namePrefix, GStylizedTerrain terrain, List <GTerrainResourceFlag> flags, bool showProgress = true)
        {
            bool success = false;

#if UNITY_EDITOR
            if (showProgress)
            {
                GCommonGUI.ProgressBar("Backing up", "Creating terrain backup...", 1f);
            }
#endif

            try
            {
                string historyPrefix = GBackupFile.GetHistoryPrefix(namePrefix);
                string backupName    = string.Format("{0}_{1}", historyPrefix, GBackupFile.GetBackupNameByTimeNow());
                GUndoCompatibleBuffer.Instance.RecordUndo();
                GBackup.Create(backupName, terrain, flags);
                success = true;
            }
            catch (System.Exception e)
            {
                Debug.Log("Fail to creating terrain backup: " + e.ToString());
            }
            finally
            {
#if UNITY_EDITOR
                GCommonGUI.ClearProgressBar();
#endif
            }

            return(success);
        }
        public void Export()
        {
            try
            {
#if UNITY_EDITOR
                GCommonGUI.ProgressBar("Working", "Exporting RAW file...", 1f);
#endif
                if (BitDepth == GBitDepth.Bit8)
                {
                    DoExportRaw8();
                }
                else if (BitDepth == GBitDepth.Bit16)
                {
                    DoExportRaw16();
                }
            }
            catch (System.Exception e)
            {
                Debug.LogError(e);
            }
            finally
            {
#if UNITY_EDITOR
                GCommonGUI.ClearProgressBar();
#endif
            }
        }
예제 #8
0
        private void SaveAssets()
        {
#if UNITY_EDITOR
            GCommonGUI.ProgressBar("Saving", "Saving unsaved assets...", 1f);
            AssetDatabase.SaveAssets();
            GCommonGUI.ClearProgressBar();
#endif
        }
예제 #9
0
        public static bool TryCreateInitialBackup(string namePrefix, int terrainGroupId, List <GTerrainResourceFlag> flags, bool showProgress = true)
        {
            bool success = false;

#if UNITY_EDITOR
            if (showProgress)
            {
                GCommonGUI.ProgressBar("Backing up", "Creating terrain backup...", 1f);
            }
#endif

            try
            {
                List <string> createdBackup = new List <string>(GBackupFile.GetAllBackupNames());
                string        prefix        = GBackupFile.GetHistoryPrefix(namePrefix);
                string        initialPrefix = GBackupFile.GetInitialHistoryPrefix(namePrefix);

                bool willCreateInitialBackup = true;
                for (int i = createdBackup.Count - 1; i >= 0; --i)
                {
                    if (createdBackup[i].StartsWith(prefix))
                    {
                        continue;
                    }
                    else if (createdBackup[i].StartsWith(initialPrefix))
                    {
                        willCreateInitialBackup = false;
                        break;
                    }
                    else
                    {
                        willCreateInitialBackup = true;
                        break;
                    }
                }

                if (willCreateInitialBackup)
                {
                    string backupName = string.Format("{0}_{1}", initialPrefix, GBackupFile.GetBackupNameByTimeNow());
                    GUndoCompatibleBuffer.Instance.RecordUndo();
                    GBackup.Create(backupName, terrainGroupId, flags);
                    success = true;
                }
            }
            catch (System.Exception e)
            {
                Debug.Log("Fail to creating terrain backup: " + e.ToString());
            }
            finally
            {
#if UNITY_EDITOR
                GCommonGUI.ClearProgressBar();
#endif
            }
            return(success);
        }
        private void FinishingUp()
        {
#if UNITY_EDITOR
            GCommonGUI.ProgressBar("Finishing Up", "Matching geometry...", 1f);
#endif
            GStylizedTerrain.ConnectAdjacentTiles();
            GStylizedTerrain.MatchEdges(-1);
            Root.gameObject.SetActive(false);
#if UNITY_EDITOR
            GCommonGUI.ClearProgressBar();
#endif
        }
예제 #11
0
        public void Import()
        {
            try
            {
                if (ImportSplats)
                {
#if UNITY_EDITOR
                    GCommonGUI.CancelableProgressBar("Working...", "Importing Splats...", 1f);
#endif
                    DoImportSplats();
                }
                if (ImportTrees)
                {
#if UNITY_EDITOR
                    GCommonGUI.CancelableProgressBar("Working...", "Importing Trees...", 1f);
#endif
                    DoImportTrees();
                }
                if (ImportGrasses)
                {
#if UNITY_EDITOR
                    GCommonGUI.CancelableProgressBar("Working...", "Importing Grasses & Details...", 1f);
#endif
                    DoImportGrasses();
                }
                if (ImportGeometry)
                {
#if UNITY_EDITOR
                    GCommonGUI.CancelableProgressBar("Working...", "Importing Geometry...", 1f);
#endif
                    DoImportGeometry();
                }
            }
            catch (GProgressCancelledException)
            {
                Debug.Log("Importing process canceled!");
            }
            catch (System.Exception e)
            {
                Debug.LogError(e.ToString());
            }
            finally
            {
#if UNITY_EDITOR
                GCommonGUI.ClearProgressBar();
#endif
            }
        }
예제 #12
0
        private void FinishingUp()
        {
#if UNITY_EDITOR
            GCommonGUI.ProgressBar("Finishing Up", "Matching geometry...", 1f);
#endif

            for (int i = 0; i < ConvertedTerrains.Count; ++i)
            {
                ConvertedTerrains[i].ConnectNeighbor();
                ConvertedTerrains[i].MatchEdges();
            }

            Root.gameObject.SetActive(false);
#if UNITY_EDITOR
            GCommonGUI.ClearProgressBar();
#endif
        }
예제 #13
0
        public void Export()
        {
            try
            {
#if UNITY_EDITOR
                GCommonGUI.ProgressBar("Working", "Exporting terrain textures...", 1f);
#endif
                if (ExportHeightMap)
                {
                    DoExportHeightMap();
                }
                if (ExportVisibilityMap)
                {
                    DoExportVisibilityMap();
                }
                if (ExportAlbedoMap)
                {
                    DoExportAlbedoMap();
                }
                if (ExportMetallicMap)
                {
                    DoExportMetallicMap();
                }
                if (ExportGradientLookupMaps)
                {
                    DoExportGradientLookupMaps();
                }
                if (ExportSplatControlMaps)
                {
                    DoExportSplatControlMaps();
                }
#if UNITY_EDITOR
                AssetDatabase.Refresh();
#endif
            }
            catch (System.Exception e)
            {
                Debug.LogError(e);
            }
            finally
            {
#if UNITY_EDITOR
                GCommonGUI.ClearProgressBar();
#endif
            }
        }
        public void Export()
        {
            try
            {
#if UNITY_EDITOR
                GCommonGUI.ProgressBar("Working", "Saving unsaved assets...", 1f);
                SaveAssets();
                GCommonGUI.ProgressBar("Working", "Exporting", 1f);
#endif

                InitializeAssets();
                if (ExportGeometry)
                {
                    DoExportGeometry();
                }
                if (ExportSplats)
                {
                    DoExportSplats();
                }
                if (ExportTrees)
                {
                    DoExportTrees();
                }
                if (ExportGrasses)
                {
                    DoExportGrasses();
                }

#if UNITY_EDITOR
                GCommonGUI.ProgressBar("Working", "Saving unsaved assets...", 1f);
                SaveAssets();
#endif
            }
            catch (System.Exception e)
            {
                Debug.LogError(e.ToString());
            }
            finally
            {
#if UNITY_EDITOR
                GCommonGUI.ClearProgressBar();
#endif
            }
        }
예제 #15
0
        public void Import()
        {
            try
            {
#if UNITY_EDITOR
                GCommonGUI.ProgressBar("Working", "Importing RAW...", 1f);
#endif
                if (BitDepth == GBitDepth.Bit8)
                {
                    ImportRaw8();
                }
                else if (BitDepth == GBitDepth.Bit16)
                {
                    ImportRaw16();
                }
                if (Terrain != null)
                {
                    DesData.Foliage.SetTreeRegionDirty(GCommon.UnitRect);
                    DesData.Foliage.SetGrassRegionDirty(GCommon.UnitRect);
                    Terrain.UpdateTreesPosition(true);
                    Terrain.UpdateGrassPatches(-1, true);
                    DesData.Foliage.ClearTreeDirtyRegions();
                    DesData.Foliage.ClearGrassDirtyRegions();
                }
            }
            catch (System.Exception e)
            {
                Debug.LogError(e);
            }
            finally
            {
#if UNITY_EDITOR
                GCommonGUI.ClearProgressBar();
#endif
            }
        }
        private void Apply(GStylizedTerrain t)
        {
            if (t.TerrainData == null)
            {
                return;
            }
            if (Layers.Count == 0)
            {
                return;
            }

            GetQuad(worldPoints);
            GetUvPoints(t, worldPoints, uvPoints);
            Rect dirtyRect = GUtilities.GetRectContainsPoints(uvPoints);

            if (!dirtyRect.Overlaps(new Rect(0, 0, 1, 1)))
            {
                return;
            }

            RenderTexture[] brushes = new RenderTexture[Layers.Count];
            for (int i = 0; i < Layers.Count; ++i)
            {
                brushes[i] = GetRenderTexture("brush" + i.ToString());
            }
            Internal_RenderBrushes(brushes, t, uvPoints);

            for (int i = 0; i < Layers.Count; ++i)
            {
                StampLayer(t, brushes[i], i);
            }

#if UNITY_EDITOR
            GCommonGUI.ClearProgressBar();
#endif
        }
예제 #17
0
        private void SpawnGrassOnTerrain(GStylizedTerrain t, Color[] maskData, int layerIndex)
        {
            GFoliageStampLayer layer     = Layers[layerIndex];
            Vector3            centerPos = Vector3.zero;
            Vector3            samplePos = Vector3.zero;
            Vector2            uv        = Vector2.zero;
            float   maskValue            = 0;
            Vector3 terrainSize          = new Vector3(
                t.TerrainData.Geometry.Width,
                t.TerrainData.Geometry.Height,
                t.TerrainData.Geometry.Length);
            Vector3 scale = new Vector3(
                GUtilities.InverseLerpUnclamped(0, terrainSize.x, Scale.x),
                1,
                GUtilities.InverseLerpUnclamped(0, terrainSize.z, Scale.z));
            Matrix4x4 matrix = Matrix4x4.TRS(
                t.WorldPointToNormalized(Position),
                Rotation,
                scale);

            int grassIndex                = -1;
            int instanceCount             = 0;
            int attempt                   = 0;
            int maxAttempt                = layer.GrassInstanceCount * 100;
            List <GGrassInstance> grasses = new List <GGrassInstance>();

#if UNITY_EDITOR
            string title           = "Stamping on " + t.name;
            string info            = string.Format("Layer: {0}", !string.IsNullOrEmpty(layer.Name) ? layer.Name : layerIndex.ToString());
            int    currentPercent  = 0;
            int    attemptPercent  = 0;
            int    instancePercent = 0;
            GCommonGUI.CancelableProgressBar(title, info, 0);
#endif

            while (instanceCount < layer.GrassInstanceCount && attempt <= maxAttempt)
            {
                attempt += 1;

#if UNITY_EDITOR
                attemptPercent  = (int)(attempt * 100.0f / maxAttempt);
                instancePercent = (int)(instanceCount * 100.0f / layer.GrassInstanceCount);
                if (currentPercent != Mathf.Max(attemptPercent, instancePercent))
                {
                    currentPercent = Mathf.Max(attemptPercent, instancePercent);
                    GCommonGUI.CancelableProgressBar(title, string.Format("{0} ... {1}%", info, currentPercent), currentPercent / 100.0f);
                }
#endif

                grassIndex = layer.GrassIndices[Random.Range(0, layer.GrassIndices.Count)];

                centerPos.Set(Random.value - 0.5f, 0, Random.value - 0.5f);
                samplePos = matrix.MultiplyPoint(centerPos);
                if (samplePos.x < 0 || samplePos.x > 1 ||
                    samplePos.z < 0 || samplePos.z > 1)
                {
                    continue;
                }
                uv.Set(samplePos.x, samplePos.z);
                maskValue = GUtilities.GetColorBilinear(maskData, MaskResolution, MaskResolution, uv).r;
                if (Random.value > maskValue)
                {
                    continue;
                }

                GGrassInstance grass = GGrassInstance.Create(grassIndex);
                grass.Position = new Vector3(samplePos.x, 0, samplePos.z);
                grass.Rotation = Quaternion.Euler(0, Random.Range(layer.MinRotation, layer.MaxRotation), 0);
                grass.Scale    = Vector3.Lerp(layer.MinScale, layer.MaxScale, Random.value);

                grasses.Add(grass);
                instanceCount += 1;
            }

            t.TerrainData.Foliage.AddGrassInstances(grasses);

#if UNITY_EDITOR
            GCommonGUI.ClearProgressBar();
#endif
        }
예제 #18
0
        private void Apply(GStylizedTerrain t)
        {
            if (t.TerrainData == null)
            {
                return;
            }
            if (Layers.Count == 0)
            {
                return;
            }

            GetQuad(worldPoints);
            GetUvPoints(t, worldPoints, uvPoints);
            Rect dirtyRect = GUtilities.GetRectContainsPoints(uvPoints);

            if (!dirtyRect.Overlaps(new Rect(0, 0, 1, 1)))
            {
                return;
            }

            RenderTexture[] brushes = new RenderTexture[Layers.Count];
            for (int i = 0; i < Layers.Count; ++i)
            {
                brushes[i] = GetRenderTexture("brush" + i.ToString());
            }
            Internal_RenderBrushes(brushes, t, uvPoints);

            for (int i = 0; i < Layers.Count; ++i)
            {
                StampLayer(t, brushes[i], i);
            }

            bool willUpdateTree  = Layers.Exists(l => l.StampTrees && l.TreeInstanceCount > 0);
            bool willUpdateGrass = Layers.Exists(l => l.StampGrasses && l.TreeInstanceCount > 0);

#if UNITY_EDITOR
            string title = "Stamping on " + t.name;
            string info  = "Finishing up...";
            GCommonGUI.ProgressBar(title, info, 1);
#endif

            try
            {
                t.TerrainData.Foliage.SetTreeRegionDirty(dirtyRect);
                t.TerrainData.Foliage.SetGrassRegionDirty(dirtyRect);
                if (willUpdateTree)
                {
                    t.UpdateTreesPosition();
                }
                if (willUpdateGrass)
                {
                    t.UpdateGrassPatches(-1, true);
                }
                t.TerrainData.Foliage.ClearTreeDirtyRegions();
                t.TerrainData.Foliage.ClearGrassDirtyRegions();
            }
            catch (System.Exception e)
            {
                Debug.LogError(e);
            }

#if UNITY_EDITOR
            GCommonGUI.ClearProgressBar();
#endif

            t.TerrainData.SetDirty(GTerrainData.DirtyFlags.Foliage);
        }
        private void CreateTerrainAndImportData()
        {
            GameObject terrainRoot = new GameObject(string.Format("{0}-{1}", Root.name, ConversionName));

            terrainRoot.transform.parent   = Root.transform.parent;
            terrainRoot.transform.position = Root.transform.position;

            for (int i = 0; i < Terrains.Count; ++i)
            {
#if UNITY_EDITOR
                GCommonGUI.CancelableProgressBar("Converting", "Converting " + Terrains[i].name, 1f);
#endif
                GStylizedTerrain t = CreateTerrain();
                t.transform.parent   = terrainRoot.transform;
                t.transform.position = Terrains[i].transform.position;
                t.name = Terrains[i].name;

#if !UNITY_2018_1 && !UNITY_2018_2
                t.GroupId = Terrains[i].groupingID;
#endif
                if (ImportSplats)
                {
                    t.TerrainData.Shading.Splats = SplatGroups[SplatGroupIndices[i]];
                    GSplatsModel splatModel = t.TerrainData.Shading.Splats.Prototypes.Count <= 4 ?
                                              GSplatsModel.Splats4Normals4 :
                                              GSplatsModel.Splats8;
                    Material mat = GGriffinSettings.Instance.WizardSettings.GetClonedMaterial(GLightingModel.PBR, GTexturingModel.Splat, splatModel);
                    t.TerrainData.Shading.MaterialToRender.shader = mat.shader;
                    t.TerrainData.Shading.UpdateMaterials();
                    GUtilities.DestroyObject(mat);
                }
                if (ImportTrees)
                {
                    t.TerrainData.Foliage.Trees = TreeGroups[TreeGroupIndices[i]];
                }
                if (ImportGrasses)
                {
                    t.TerrainData.Foliage.Grasses = GrassGroups[GrassGroupIndices[i]];
                }

                GUnityTerrainDataImporter importer = new GUnityTerrainDataImporter();
                importer.SrcData                       = Terrains[i].terrainData;
                importer.SrcTerrain                    = Terrains[i];
                importer.DesData                       = t.TerrainData;
                importer.DesTerrain                    = t;
                importer.ImportGeometry                = ImportGeometry;
                importer.UseUnityTerrainSize           = true;
                importer.ImportSplats                  = ImportSplats;
                importer.ImportSplatsAsAlbedo          = ImportSplatsAsAlbedo;
                importer.CreateNewSplatPrototypesGroup = false;
                importer.ImportTrees                   = ImportTrees;
                importer.CreateNewTreePrototypesGroup  = false;
                importer.ImportGrasses                 = ImportGrasses;
                importer.CreateNewGrassPrototypesGroup = false;
                importer.GrassDensity                  = GUnityTerrainDataImporter.GetAdjustedGrassDensity(importer.SrcData, 1);
                importer.Import();

#if UNITY_EDITOR
                SaveAssets();
                GCommonGUI.ClearProgressBar();
#endif
            }
        }
        private void SpawnObjectOnTerrain(GStylizedTerrain t, Color[] maskData, int layerIndex)
        {
            GObjectStampLayer layer       = Layers[layerIndex];
            Vector3           centerPos   = Vector3.zero;
            Vector3           samplePos   = Vector3.zero;
            Vector2           uv          = Vector2.zero;
            float             maskValue   = 0;
            Vector3           terrainSize = new Vector3(
                t.TerrainData.Geometry.Width,
                t.TerrainData.Geometry.Height,
                t.TerrainData.Geometry.Length);
            Vector3 scale = new Vector3(
                GUtilities.InverseLerpUnclamped(0, terrainSize.x, Scale.x),
                1,
                GUtilities.InverseLerpUnclamped(0, terrainSize.z, Scale.z));
            Matrix4x4 matrix = Matrix4x4.TRS(
                t.WorldPointToNormalized(Position),
                Rotation,
                scale);

            int        index         = -1;
            int        instanceCount = 0;
            int        attempt       = 0;
            int        maxAttempt    = layer.InstanceCount * 100;
            RaycastHit hit;

#if UNITY_EDITOR
            string title           = "Stamping on " + t.name;
            string info            = string.Format("Layer: {0}", !string.IsNullOrEmpty(layer.Name) ? layer.Name : layerIndex.ToString());
            int    currentPercent  = 0;
            int    attemptPercent  = 0;
            int    instancePercent = 0;
            GCommonGUI.CancelableProgressBar(title, info, 0);
#endif

            while (instanceCount < layer.InstanceCount && attempt <= maxAttempt)
            {
                attempt += 1;

#if UNITY_EDITOR
                attemptPercent  = (int)(attempt * 100.0f / maxAttempt);
                instancePercent = (int)(instanceCount * 100.0f / layer.InstanceCount);
                if (currentPercent != Mathf.Max(attemptPercent, instancePercent))
                {
                    currentPercent = Mathf.Max(attemptPercent, instancePercent);
                    GCommonGUI.CancelableProgressBar(title, string.Format("{0} ... {1}%", info, currentPercent), currentPercent / 100.0f);
                }
#endif

                index = layer.PrototypeIndices[Random.Range(0, layer.PrototypeIndices.Count)];
                if (index < 0 || index >= layer.Prototypes.Count)
                {
                    continue;
                }
                GameObject g = layer.Prototypes[index];
                if (g == null)
                {
                    continue;
                }

                centerPos.Set(Random.value - 0.5f, 0, Random.value - 0.5f);
                samplePos = matrix.MultiplyPoint(centerPos);
                if (samplePos.x < 0 || samplePos.x > 1 ||
                    samplePos.z < 0 || samplePos.z > 1)
                {
                    continue;
                }
                uv.Set(samplePos.x, samplePos.z);
                maskValue = GUtilities.GetColorBilinear(maskData, MaskResolution, MaskResolution, uv).r;
                if (Random.value > maskValue)
                {
                    continue;
                }

                if (t.Raycast(samplePos, out hit))
                {
                    GameObject instance = GSpawner.Spawn(t, g, hit.point);
                    instance.transform.rotation   = Quaternion.Euler(0, Random.Range(layer.MinRotation, layer.MaxRotation), 0);
                    instance.transform.localScale = Vector3.Lerp(layer.MinScale, layer.MaxScale, Random.value);
                    if (layer.AlignToSurface)
                    {
                        instance.transform.up = hit.normal;
                    }

                    instanceCount += 1;
                }
            }
#if UNITY_EDITOR
            GCommonGUI.ClearProgressBar();
#endif
        }
예제 #21
0
        private void CreateStaticObstacles(GStylizedTerrain t)
        {
            if (t.TerrainData == null)
            {
                return;
            }
            if (t.TerrainData.Foliage.Trees == null)
            {
                return;
            }
            if (t.TerrainData.Foliage.Trees.Prototypes.Count == 0)
            {
                return;
            }

#if UNITY_EDITOR
            string title = "Creating static obstacles";
            string info  = t.name;
            GCommonGUI.CancelableProgressBar(title, info, 0);
#endif

            Vector3 terrainSize = new Vector3(
                t.TerrainData.Geometry.Width,
                t.TerrainData.Geometry.Height,
                t.TerrainData.Geometry.Length);

            Transform             root       = GUtilities.GetChildrenWithName(transform, string.Format("{0}_{1}", t.name, t.GetInstanceID()));
            List <GTreePrototype> prototypes = t.TerrainData.Foliage.Trees.Prototypes;

            GameObject[] templates = new GameObject[prototypes.Count];
            for (int i = 0; i < prototypes.Count; ++i)
            {
                if (!prototypes[i].IsValid)
                {
                    continue;
                }
                GameObject  template   = Instantiate(prototypes[i].Prefab) as GameObject;
                Component[] components = template.GetComponentsInChildren <Component>();
                for (int j = 0; j < components.Length; ++j)
                {
                    if (components[j] is Collider)
                    {
                        GUtilities.DestroyObject(components[j]);
                    }
                    if (components[j] is MeshRenderer)
                    {
                        MeshRenderer mr = components[j] as MeshRenderer;
                        mr.sharedMaterials   = new Material[] { GInternalMaterials.NavHelperDummyGameObjectMaterial };
                        mr.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
                        mr.receiveShadows    = false;
                    }
                }
#if UNITY_EDITOR
                GameObjectUtility.SetStaticEditorFlags(template, StaticEditorFlags.NavigationStatic);
#endif
                template.name = prototypes[i].Prefab.name;
                templates[i]  = template;
            }

            List <GTreeInstance> instances = t.TerrainData.Foliage.TreeInstances;
            for (int i = 0; i < instances.Count; ++i)
            {
#if UNITY_EDITOR
                GCommonGUI.CancelableProgressBar(title, info, i * 1.0f / instances.Count);
#endif
                GTreeInstance tree = instances[i];
                if (templates[tree.PrototypeIndex] == null)
                {
                    continue;
                }

                GameObject g = Instantiate(templates[tree.PrototypeIndex]) as GameObject;
                g.transform.parent = root;

                Vector3 localPos = new Vector3(
                    tree.Position.x * terrainSize.x,
                    tree.Position.y * terrainSize.y,
                    tree.Position.z * terrainSize.z);
                Vector3 worldPos = t.transform.TransformPoint(localPos);
                g.transform.position   = worldPos;
                g.transform.rotation   = tree.Rotation;
                g.transform.localScale = tree.Scale;
                g.name = templates[tree.PrototypeIndex].name;
            }

            for (int i = 0; i < templates.Length; ++i)
            {
                GUtilities.DestroyGameobject(templates[i]);
            }
#if UNITY_EDITOR
            GCommonGUI.ClearProgressBar();
#endif
        }
        public static List <GStylizedTerrain> CreateTerrains(GameObject root)
        {
            GEditorSettings.WizardToolsSettings settings = GEditorSettings.Instance.wizardTools;
            List <GStylizedTerrain>             terrains = new List <GStylizedTerrain>();

#if UNITY_EDITOR
            if (!Application.isPlaying)
            {
                GUtilities.EnsureDirectoryExists(settings.dataDirectory);
            }
#endif
            try
            {
                float totalTile = settings.tileCountX * settings.tileCountZ;
                float tileCount = 0;
                for (int z = 0; z < settings.tileCountZ; ++z)
                {
                    for (int x = 0; x < settings.tileCountX; ++x)
                    {
                        tileCount += 1;
#if UNITY_EDITOR
                        GCommonGUI.CancelableProgressBar(
                            "Creating Terrains",
                            string.Format("Creating tile ({0},{1})", x, z),
                            tileCount / totalTile);
#endif
                        GameObject g = new GameObject();
                        g.transform.parent     = root.transform;
                        g.transform.position   = new Vector3(x * settings.tileSize.x, 0, z * settings.tileSize.z) + settings.origin;
                        g.transform.rotation   = Quaternion.identity;
                        g.transform.localScale = Vector3.one;
                        g.name = string.Format("{0}_({1},{2})", settings.terrainNamePrefix, x, z);

                        GTerrainData data = ScriptableObject.CreateInstance <GTerrainData>();

                        if (Application.isPlaying) //Reset() only called in edit mode
                        {
                            data.Reset();
                            data.Geometry.Reset();
                            data.Shading.Reset();
                            data.Rendering.Reset();
                            data.Foliage.Reset();
                            data.Mask.Reset();
                        }
                        data.name            = string.Format("TerrainData_{0}", data.Id);
                        data.Geometry.Width  = settings.tileSize.x;
                        data.Geometry.Height = settings.tileSize.y;
                        data.Geometry.Length = settings.tileSize.z;
                        if (settings.texturingModel == GTexturingModel.VertexColor)
                        {
                            data.Geometry.AlbedoToVertexColorMode = GAlbedoToVertexColorMode.Sharp;
                        }

#if UNITY_EDITOR
                        if (!Application.isPlaying)
                        {
                            string dataAssetPath = Path.Combine(settings.dataDirectory, data.name + ".asset");
                            AssetDatabase.CreateAsset(data, dataAssetPath);
                        }
#endif

                        Material material = GRuntimeSettings.Instance.terrainRendering.GetClonedMaterial(
                            GCommon.CurrentRenderPipeline,
                            settings.lightingModel,
                            settings.texturingModel,
                            settings.splatsModel);
                        if (material != null)
                        {
                            material.name = string.Format("TerrainMaterial_{0}", data.Id);
#if UNITY_EDITOR
                            if (!Application.isPlaying)
                            {
                                string materialAssetPath = Path.Combine(settings.dataDirectory, material.name + ".mat");
                                AssetDatabase.CreateAsset(material, materialAssetPath);
                            }
#endif
                        }
                        data.Shading.CustomMaterial = material;
                        data.Shading.UpdateMaterials();

                        GStylizedTerrain terrain = g.AddComponent <GStylizedTerrain>();
                        terrain.GroupId     = settings.groupId;
                        terrain.TerrainData = data;

#if UNITY_EDITOR
                        Undo.RegisterCreatedObjectUndo(g, "Creating Low Poly Terrain");
#endif

                        GameObject colliderGO = new GameObject("Tree Collider");
                        colliderGO.transform.parent        = g.transform;
                        colliderGO.transform.localPosition = Vector3.zero;
                        colliderGO.transform.localRotation = Quaternion.identity;
                        colliderGO.transform.localScale    = Vector3.one;

                        GTreeCollider collider = colliderGO.AddComponent <GTreeCollider>();
                        collider.Terrain = terrain;
                    }
                }
            }
            catch (GProgressCancelledException)
            {
            }

            GStylizedTerrain.ConnectAdjacentTiles();

#if UNITY_EDITOR
            GCommonGUI.ClearProgressBar();
#endif

            return(terrains);
        }
예제 #23
0
        private void ImportDataAndCreateTerrain()
        {
            GameObject terrainRoot = new GameObject(string.Format("{0}-{1}", Root.name, ConversionName));

            terrainRoot.transform.parent   = Root.transform.parent;
            terrainRoot.transform.position = Root.transform.position;

            for (int i = 0; i < Terrains.Count; ++i)
            {
#if UNITY_EDITOR
                GCommonGUI.CancelableProgressBar("Converting", "Converting " + Terrains[i].name, 1f);
#endif

                GTerrainData data = ScriptableObject.CreateInstance <GTerrainData>();
                if (DataTemplate != null)
                {
                    DataTemplate.Geometry.CopyTo(data.Geometry);
                    DataTemplate.Shading.CopyTo(data.Shading);
                    DataTemplate.Rendering.CopyTo(data.Rendering);
                    DataTemplate.Foliage.CopyTo(data.Foliage);
                    DataTemplate.Mask.CopyTo(data.Mask);
                }
                else
                {
                    if (Application.isPlaying) //Reset() only called in edit mode
                    {
                        data.Reset();
                        data.Geometry.Reset();
                        data.Shading.Reset();
                        data.Rendering.Reset();
                        data.Foliage.Reset();
                        data.Mask.Reset();
                    }
                }

#if UNITY_EDITOR
                if (!Application.isPlaying)
                {
                    string assetName = "TerrainData_" + data.Id;
                    AssetDatabase.CreateAsset(data, string.Format("{0}.asset", Path.Combine(DataDirectory, assetName)));
                }
#endif

                Material templateMaterial = null;
                if (DataTemplate != null)
                {
                    templateMaterial = DataTemplate.Shading.CustomMaterial;
                }

                Material material = null;
                if (templateMaterial != null)
                {
                    material = new Material(templateMaterial.shader);
                }
                else
                {
                    if (ImportSplats)
                    {
                        if (ImportSplatsAsAlbedo && AlbedoUsage == GAlbedoUsage.ColorMap)
                        {
                            material = GRuntimeSettings.Instance.terrainRendering.GetClonedMaterial(GCommon.CurrentRenderPipeline, GLightingModel.PBR, GTexturingModel.ColorMap);
                        }
                        else if (ImportSplatsAsAlbedo && AlbedoUsage == GAlbedoUsage.VertexColor)
                        {
                            material = GRuntimeSettings.Instance.terrainRendering.GetClonedMaterial(GCommon.CurrentRenderPipeline, GLightingModel.PBR, GTexturingModel.VertexColor);
                            data.Geometry.AlbedoToVertexColorMode = GAlbedoToVertexColorMode.Sharp;
                        }
                        else
                        {
                            GSplatPrototypeGroup splats     = DataTemplate ? DataTemplate.Shading.Splats : SplatGroups[SplatGroupIndices[i]];
                            GSplatsModel         splatModel = (splats == null || splats.Prototypes.Count <= 4) ?
                                                              GSplatsModel.Splats4Normals4 :
                                                              GSplatsModel.Splats8;
                            material = GRuntimeSettings.Instance.terrainRendering.GetClonedMaterial(GCommon.CurrentRenderPipeline, GLightingModel.PBR, GTexturingModel.Splat, splatModel);
                        }
                    }
                    else
                    {
                        material = GRuntimeSettings.Instance.terrainRendering.GetClonedMaterial(GCommon.CurrentRenderPipeline, GLightingModel.PBR, GTexturingModel.Splat, GSplatsModel.Splats4);
                    }
                }
                data.Shading.CustomMaterial = material;

#if UNITY_EDITOR
                if (!Application.isPlaying && material != null)
                {
                    string matName = "TerrainMaterial_" + data.Id;
                    material.name = matName;
                    AssetDatabase.CreateAsset(material, string.Format("{0}.mat", Path.Combine(DataDirectory, matName)));
                }
#endif

                if (ImportSplats)
                {
                    data.Shading.Splats = DataTemplate ? DataTemplate.Shading.Splats : SplatGroups[SplatGroupIndices[i]];
                    data.Shading.UpdateMaterials();
                }
                if (ImportTrees)
                {
                    data.Foliage.Trees = DataTemplate ? DataTemplate.Foliage.Trees : TreeGroups[TreeGroupIndices[i]];
                }
                if (ImportGrasses)
                {
                    data.Foliage.Grasses = DataTemplate ? DataTemplate.Foliage.Grasses : GrassGroups[GrassGroupIndices[i]];
                }

                GUnityTerrainDataImporter importer = new GUnityTerrainDataImporter();
                importer.SrcData                         = Terrains[i].terrainData;
                importer.SrcTerrain                      = Terrains[i];
                importer.DesData                         = data;
                importer.DesTerrain                      = null;
                importer.ImportGeometry                  = ImportGeometry;
                importer.UseUnityTerrainSize             = true;
                importer.ImportSplats                    = ImportSplats;
                importer.ImportSplatsAsAlbedo            = ImportSplatsAsAlbedo;
                importer.ImportSplatControlMapsOnly      = DataTemplate != null && DataTemplate.Shading.Splats != null;
                importer.ImportSplatControlMapResolution = DataTemplate == null;
                importer.CreateNewSplatPrototypesGroup   = false;
                importer.ImportTrees                     = ImportTrees;
                importer.ImportTreeInstancesOnly         = DataTemplate != null && DataTemplate.Foliage.Trees != null;
                importer.CreateNewTreePrototypesGroup    = false;
                importer.ImportGrasses                   = ImportGrasses;
                importer.ImportGrassInstancesOnly        = DataTemplate != null && DataTemplate.Foliage.Grasses != null;
                importer.CreateNewGrassPrototypesGroup   = false;
                importer.GrassDensity                    = 1;
                importer.SkipFoliageSnap                 = SkipFoliageSnap;
                importer.Import();

                GStylizedTerrain t = CreateTerrain();
                t.transform.parent   = terrainRoot.transform;
                t.transform.position = Terrains[i].transform.position;
                t.name = Terrains[i].name;

#if UNITY_2018_3_OR_NEWER
                t.GroupId = Terrains[i].groupingID;
#endif

                t.TerrainData = data;

                if (ImportTrees || ImportGrasses)
                {
                    data.Foliage.SetTreeRegionDirty(GCommon.UnitRect);
                    data.Foliage.SetGrassRegionDirty(GCommon.UnitRect);
                    t.UpdateTreesPosition();
                    t.UpdateGrassPatches();
                    data.Foliage.ClearTreeDirtyRegions();
                    data.Foliage.ClearGrassDirtyRegions();
                }

                ConvertedTerrains.Add(t);
#if UNITY_EDITOR
                //SaveAssets();
                GCommonGUI.ClearProgressBar();
#endif
            }
        }
예제 #24
0
        public void Import()
        {
            try
            {
#if UNITY_EDITOR
                GCommonGUI.ProgressBar("Working", "Importing textures...", 1f);
#endif
                if (HeightMap != null || VisibilityMap != null)
                {
                    Color[] oldHeightMapColors = DesData.Geometry.HeightMap.GetPixels();

                    Texture2D hm = null;
                    if (HeightMap != null)
                    {
                        hm = GCommon.CloneTexture(HeightMap);
                    }
                    Texture2D vm = null;
                    if (VisibilityMap != null)
                    {
                        vm = GCommon.CloneTexture(VisibilityMap);
                    }

                    int     desResolution = DesData.Geometry.HeightMapResolution;
                    Color[] newColor      = new Color[desResolution * desResolution];
                    Vector2 uv            = Vector2.zero;
                    Vector2 enc           = Vector2.zero;
                    for (int y = 0; y < desResolution; ++y)
                    {
                        for (int x = 0; x < desResolution; ++x)
                        {
                            uv.Set(
                                Mathf.InverseLerp(0, desResolution, x),
                                Mathf.InverseLerp(0, desResolution, y));

                            Color c = Color.clear;
                            if (hm != null)
                            {
                                enc = GCommon.EncodeTerrainHeight(hm.GetPixelBilinear(uv.x, uv.y).r);
                                c.r = enc.x;
                                c.g = enc.y;
                            }
                            else
                            {
                                c = DesData.Geometry.HeightMap.GetPixelBilinear(uv.x, uv.y);
                            }

                            if (vm != null)
                            {
                                c.a = 1 - vm.GetPixelBilinear(uv.x, uv.y).r;
                            }
                            else
                            {
                                c.a = DesData.Geometry.HeightMap.GetPixelBilinear(uv.x, uv.y).a;
                            }

                            newColor[GUtilities.To1DIndex(x, y, desResolution)] = c;
                        }
                    }

                    DesData.Geometry.HeightMap.SetPixels(newColor);
                    DesData.Geometry.HeightMap.Apply();

                    if (hm != null || vm != null)
                    {
                        Color[]            newHeightMapColors = DesData.Geometry.HeightMap.GetPixels();
                        IEnumerable <Rect> dirtyRects         = GCommon.CompareTerrainTexture(DesData.Geometry.ChunkGridSize, oldHeightMapColors, newHeightMapColors);
                        DesData.Geometry.SetRegionDirty(dirtyRects);
                        DesData.SetDirty(GTerrainData.DirtyFlags.GeometryTimeSliced);

                        if (Terrain != null)
                        {
                            DesData.Foliage.SetTreeRegionDirty(GCommon.UnitRect);
                            DesData.Foliage.SetGrassRegionDirty(GCommon.UnitRect);
                            Terrain.UpdateTreesPosition(true);
                            Terrain.UpdateGrassPatches(-1, true);
                            DesData.Foliage.ClearTreeDirtyRegions();
                            DesData.Foliage.ClearGrassDirtyRegions();
                        }
                    }

                    if (hm != null)
                    {
                        GUtilities.DestroyObject(hm);
                    }
                    if (vm != null)
                    {
                        GUtilities.DestroyObject(vm);
                    }
                }

                if (MaskMap != null)
                {
                    GCommon.CopyTexture(MaskMap, DesData.Mask.MaskMap);
                }
                if (AlbedoMap != null)
                {
                    GCommon.CopyTexture(AlbedoMap, DesData.Shading.AlbedoMap);
                    DesData.SetDirty(GTerrainData.DirtyFlags.Shading);
                }
                if (MetallicMap != null)
                {
                    GCommon.CopyTexture(MetallicMap, DesData.Shading.MetallicMap);
                    DesData.SetDirty(GTerrainData.DirtyFlags.Shading);
                }
                if (SplatControlMaps != null)
                {
                    int count = Mathf.Min(SplatControlMaps.Length, DesData.Shading.SplatControlMapCount);
                    for (int i = 0; i < count; ++i)
                    {
                        if (SplatControlMaps[i] != null)
                        {
                            GCommon.CopyTexture(SplatControlMaps[i], DesData.Shading.GetSplatControl(i));
                        }
                    }
                    DesData.SetDirty(GTerrainData.DirtyFlags.Shading);
                }
            }
            catch (System.Exception e)
            {
                Debug.LogError(e);
            }
            finally
            {
#if UNITY_EDITOR
                GCommonGUI.ClearProgressBar();
#endif
            }
        }