/// <summary> /// Returns terrain names of terrains that intersect with the given bounds object /// </summary> /// <param name="bounds">A bounds object to check against the terrains. Needs to be in absolute world space position, mind the current origin offset!</param> /// <returns></returns> public static string[] GetTerrainsIntersectingBounds(BoundsDouble bounds) { //Reduce the bounds size a bit to prevent selecting terrains that are perfectly aligned with the bounds border //-this leads to too many terrains being logged as affected by an operation otherwise. Bounds intersectingBounds = new BoundsDouble(); intersectingBounds.center = bounds.center; intersectingBounds.size = bounds.size - new Vector3Double(0.001f, 0.001f, 0.001f); if (GaiaUtils.HasDynamicLoadedTerrains()) { GaiaSessionManager sessionManager = GaiaSessionManager.GetSessionManager(); if (sessionManager == null) { Debug.LogError("Trying to get terrains that intersect with bounds, but there is no session manager in scene."); return(null); } return(TerrainLoaderManager.TerrainScenes.Where(x => x.m_bounds.Intersects(intersectingBounds)).Select(x => x.GetTerrainName()).ToArray()); } else { List <string> affectedTerrainNames = new List <string>(); foreach (Terrain t in Terrain.activeTerrains) { if (intersectingBounds.Intersects(TerrainHelper.GetWorldSpaceBounds(t))) { affectedTerrainNames.Add(t.name); } } return(affectedTerrainNames.ToArray()); } }
/// <summary> /// Get current basic scene information /// </summary> /// <returns></returns> public static GaiaSceneInfo GetSceneInfo() { GaiaSceneInfo sceneInfo = new GaiaSceneInfo(); //Get or create a session in order to get a sea level GaiaSessionManager sessionMgr = GaiaSessionManager.GetSessionManager(); //Get the sea level sceneInfo.m_seaLevel = sessionMgr.GetSeaLevel(); //Not used anywhere - obsolete? //Terrain terrain = Gaia.TerrainHelper.GetActiveTerrain(); ////Get the terrain bounds //Gaia.TerrainHelper.GetTerrainBounds(terrain, ref sceneInfo.m_sceneBounds); ////Grab the central point on the terrain - handy for placing player etc //sceneInfo.m_centrePointOnTerrain = new Vector3(sceneInfo.m_sceneBounds.center.x, terrain.SampleHeight(sceneInfo.m_sceneBounds.center), sceneInfo.m_sceneBounds.center.z); return(sceneInfo); }
/// <summary> /// Get current basic scene information /// </summary> /// <returns></returns> public static GaiaSceneInfo GetSceneInfo() { GaiaSceneInfo sceneInfo = new GaiaSceneInfo(); Terrain terrain = Gaia.TerrainHelper.GetActiveTerrain(); if (terrain == null) { Debug.LogWarning("You must have a valid terrain for sceneinfo to work correctly."); } else { //Get or create a session in order to get a sea level GaiaSessionManager sessionMgr = GaiaSessionManager.GetSessionManager(); //Get the terrain bounds Gaia.TerrainHelper.GetTerrainBounds(terrain, ref sceneInfo.m_sceneBounds); //Get the sea level sceneInfo.m_seaLevel = sessionMgr.GetSeaLevel(); //Grab the central point on the terrain - handy for placing player etc sceneInfo.m_centrePointOnTerrain = new Vector3(sceneInfo.m_sceneBounds.center.x, terrain.SampleHeight(sceneInfo.m_sceneBounds.center), sceneInfo.m_sceneBounds.center.z); } return(sceneInfo); }
public static void FinalizePlayerObjectEditor(GameObject playerObj, GaiaSettings gaiaSettings) { if (playerObj != null) { playerObj.transform.SetParent(GaiaUtils.GetPlayerObject().transform); #if UNITY_EDITOR //Adjust the scene view to see the camera if (SceneView.lastActiveSceneView != null) { if (gaiaSettings.m_focusPlayerOnSetup) { SceneView.lastActiveSceneView.LookAtDirect(playerObj.transform.position, playerObj.transform.rotation); } } #endif } GaiaSessionManager session = GaiaSessionManager.GetSessionManager(); if (session != null) { if (session.m_session != null) { if (playerObj.transform.position.y < session.m_session.m_seaLevel) { playerObj.transform.position = new Vector3(playerObj.transform.position.x, session.m_session.m_seaLevel + 5f, playerObj.transform.position.z); } } } #if GAIA_PRO_PRESENT //Add the simple terrain culling script, useful in any case if (GaiaUtils.CheckIfSceneProfileExists()) { GaiaGlobal.Instance.SceneProfile.m_terrainCullingEnabled = true; } #endif bool dynamicLoadedTerrains = GaiaUtils.HasDynamicLoadedTerrains(); if (dynamicLoadedTerrains) { #if GAIA_PRO_PRESENT TerrainLoader loader = playerObj.GetComponent <TerrainLoader>(); if (loader == null) { loader = playerObj.AddComponent <TerrainLoader>(); } loader.LoadMode = LoadMode.RuntimeAlways; float tileSize = 512; if (TerrainLoaderManager.Instance.TerrainSceneStorage.m_terrainTilesSize > 0) { tileSize = TerrainLoaderManager.Instance.TerrainSceneStorage.m_terrainTilesSize; } float size = tileSize * 1.25f * 2f; loader.m_loadingBoundsRegular = new BoundsDouble(playerObj.transform.position, new Vector3(size, size, size)); loader.m_loadingBoundsImpostor = new BoundsDouble(playerObj.transform.position, new Vector3(size * 3f, size * 3f, size * 3f)); loader.m_loadingBoundsCollider = new BoundsDouble(playerObj.transform.position, new Vector3(size, size, size)); #endif } }
public static string GetTerrainMeshExportDirectory(GaiaSession gaiaSession = null) { if (gaiaSession == null) { gaiaSession = GaiaSessionManager.GetSessionManager().m_session; } return(CreatePathIfDoesNotExist(GetExportDirectory(gaiaSession) + TERRAIN_MESH_EXPORT_DIRECTORY)); }
public static string GetMaskMapExportDirectory(GaiaSession gaiaSession = null) { if (gaiaSession == null) { gaiaSession = GaiaSessionManager.GetSessionManager().m_session; } return(CreatePathIfDoesNotExist(GetExportDirectory(gaiaSession) + MASK_MAP_EXPORT_DIRECTORY)); }
/// <summary> /// Returns the path to store terrain layer files in /// </summary> /// <param name="gaiaSession">The current session to get / create this directory for</param> /// <returns></returns> public static string GetTerrainLayerPath(GaiaSession gaiaSession = null) { if (gaiaSession == null) { gaiaSession = GaiaSessionManager.GetSessionManager().m_session; } return(CreatePathIfDoesNotExist(GetScenePath(gaiaSession) + TERRAIN_LAYERS_DIRECTORY)); }
/// <summary> /// Returns the path to store scene files in, according to the Gaia Session path /// </summary> /// <param name="gaiaSession">The session to get / create the directory for</param> /// <returns></returns> public static string GetScenePath(GaiaSession gaiaSession = null) { if (gaiaSession == null) { gaiaSession = GaiaSessionManager.GetSessionManager().m_session; } return(GetSessionSubFolderPath(gaiaSession)); }
/// <summary> /// Returns the path to store impostor scenes in, according to the session filename /// </summary> /// <param name="gaiaSession">The session to get / create this path for</param> /// <returns></returns> public static string GetBackupScenePath(GaiaSession gaiaSession = null) { if (gaiaSession == null) { gaiaSession = GaiaSessionManager.GetSessionManager().m_session; } return(CreatePathIfDoesNotExist(GetScenePath(gaiaSession) + BACKUP_SCENES_DIRECTORY)); }
/// <summary> /// Returns the path to store collider scenes in, according to the session filename /// </summary> /// <param name="gaiaSession">The session to get / create this path for</param> /// <returns></returns> public static string GetColliderScenePath(GaiaSession gaiaSession = null) { if (gaiaSession == null) { gaiaSession = GaiaSessionManager.GetSessionManager().m_session; } return(CreatePathIfDoesNotExist(GetScenePath(gaiaSession) + COLLIDER_SCENES_DIRECTORY)); }
/// <summary> /// Returns the path to store impostor scenes in, according to the session filename /// </summary> /// <param name="gaiaSession">The session to get / create this path for</param> /// <returns></returns> public static string GetImpostorScenePath(GaiaSession gaiaSession = null) { if (gaiaSession == null) { gaiaSession = GaiaSessionManager.GetSessionManager().m_session; } return(CreatePathIfDoesNotExist(GetScenePath(gaiaSession) + IMPOSTOR_SCENES_DIRECTORY)); }
public static void BakeMaskStack(ImageMask[] maskStack, Terrain terrain, Transform transform, float range, int resolution, string path) { //Simulate an operation to allow the image masks to acces the current terrain data GaiaMultiTerrainOperation operation = new GaiaMultiTerrainOperation(terrain, transform, range); operation.GetHeightmap(); operation.GetNormalmap(); operation.CollectTerrainBakedMasks(); float maxCurrentTerrainHeight = 0f; float minCurrentTerrainHeight = 0f; float seaLevel; GaiaSessionManager gsm = GaiaSessionManager.GetSessionManager(); gsm.GetWorldMinMax(ref minCurrentTerrainHeight, ref maxCurrentTerrainHeight); seaLevel = gsm.GetSeaLevel(); if (maskStack.Length > 0) { //We start from a white texture, so we need the first mask action in the stack to always be "Multiply", otherwise there will be no result. maskStack[0].m_blendMode = ImageMaskBlendMode.Multiply; //Iterate through all image masks and set up the required data that masks might need to function properly foreach (ImageMask mask in maskStack) { //mask.m_heightmapContext = heightmapContext; //mask.m_normalmapContext = normalmapContext; //mask.m_collisionContext = collisionContext; mask.m_multiTerrainOperation = operation; mask.m_seaLevel = seaLevel; mask.m_maxWorldHeight = maxCurrentTerrainHeight; mask.m_minWorldHeight = minCurrentTerrainHeight; } } RenderTexture inputTexture = RenderTexture.GetTemporary(resolution, resolution, 0, RenderTextureFormat.ARGBFloat); RenderTexture currentRT = RenderTexture.active; RenderTexture.active = inputTexture; GL.Clear(true, true, Color.white); RenderTexture.active = currentRT; RenderTexture localOutputTexture = RenderTexture.GetTemporary(inputTexture.descriptor); RenderTexture globalOutputTexture = RenderTexture.GetTemporary(inputTexture.descriptor); localOutputTexture = ImageProcessing.ApplyMaskStack(inputTexture, localOutputTexture, maskStack, ImageMaskInfluence.Local); globalOutputTexture = ImageProcessing.ApplyMaskStack(localOutputTexture, globalOutputTexture, maskStack, ImageMaskInfluence.Global); WriteRenderTexture(path, globalOutputTexture); RenderTexture.ReleaseTemporary(inputTexture); RenderTexture.ReleaseTemporary(localOutputTexture); RenderTexture.ReleaseTemporary(globalOutputTexture); inputTexture = null; localOutputTexture = null; globalOutputTexture = null; operation.CloseOperation(); }
/// <summary> /// Create the terrain defined by these settings - and apply the resources to it /// </summary> public void CreateTerrain(GaiaResource resources) { Terrain[,] world; //Update the resouces ny associating them with their assets resources.AssociateAssets(); //Update the session GaiaSessionManager sessionMgr = GaiaSessionManager.GetSessionManager(); if (sessionMgr != null && sessionMgr.IsLocked() != true) { //Update terrain settings in session sessionMgr.m_session.m_terrainWidth = m_tilesX * m_terrainSize; sessionMgr.m_session.m_terrainDepth = m_tilesZ * m_terrainSize; sessionMgr.m_session.m_terrainHeight = m_terrainHeight; //Add the defaults sessionMgr.AddDefaults(this); //Set the sea level - but only if it is zero - if not zero then its been deliberately set if (Gaia.GaiaUtils.Math_ApproximatelyEqual(sessionMgr.m_session.m_seaLevel, 0f)) { sessionMgr.SetSeaLevel(m_seaLevel); } //Grab the resources scriptable object sessionMgr.AddResource(resources); //Adjust them if they are different to the defaults resources.ChangeSeaLevel(sessionMgr.m_session.m_seaLevel); //Then add the operation sessionMgr.AddOperation(GetTerrainCreationOperation(resources)); } //Create the terrains array world = new Terrain[m_tilesX, m_tilesZ]; //And iterate through and create each terrain for (int x = 0; x < m_tilesX; x++) { for (int z = 0; z < m_tilesZ; z++) { CreateTile(x, z, ref world, resources); } } //Now join them together and remove their seams RemoveWorldSeams(ref world); }
/// <summary> /// Looks up terrain layer asset files matching a Gaia terrain, and returns them as an array. /// </summary> /// <param name="terrainName">The Gaia terrain name to look up terrain layer asset files for.</param> /// <returns></returns> // private static TerrainLayer[] LookupTerrainLayerAssetFiles(string terrainName) // { //#if UNITY_EDITOR // string gaiaDirectory = ""; // string terrainLayerDirectory = gaiaDirectory + "Profiles/TerrainLayers"; // DirectoryInfo info = new DirectoryInfo(terrainLayerDirectory); // FileInfo[] fileInfo = info.GetFiles(terrainName + "*.asset"); // TerrainLayer[] returnArray = new TerrainLayer[fileInfo.Length]; // for (int i = 0; i < fileInfo.Length; i++) // { // returnArray[i] = (TerrainLayer)AssetDatabase.LoadAssetAtPath("Assets" + fileInfo[i].FullName.Substring(Application.dataPath.Length), typeof(TerrainLayer)); // } // return returnArray; //#else // Debug.LogError("Runtime Gaia operation is not supported"); // return new TerrainLayer[0]; //#endif // } /// <summary> /// Saves a unity terrain layer as asset file and returns a reference to the newly created Terrain Layerfile. /// </summary> /// <param name="terrainName">The name of the current Gaia terrain (for the filename).</param> /// <param name="layerId">The layer ID of the layer that is to be saved (for the filename).</param> /// <param name="terrainLayer">The terrain layer object to save.</param> /// <returns>Reference to the created TerrainLayer</returns> public static TerrainLayer SaveTerrainLayerAsAsset(string terrainName, string layerId, TerrainLayer terrainLayer) { #if UNITY_EDITOR GaiaSessionManager gsm = GaiaSessionManager.GetSessionManager(); //The combination of terrain name and layer id should be unique enough so that users don't overwrite layers between terrains. string path = GaiaDirectories.GetTerrainLayerPath(gsm.m_session) + "/" + terrainName + "_" + layerId + ".asset"; AssetDatabase.CreateAsset(terrainLayer, path); AssetDatabase.ImportAsset(path); return(AssetDatabase.LoadAssetAtPath <TerrainLayer>(path)); #else Debug.LogError("Runtime Gaia operation is not supported"); return(new TerrainLayer()); #endif }
private void AddNewCollisionMaskCacheEntry(RenderTexture texture, Terrain terrain, string fileName) { BakedMaskCacheEntry[] newArray = new BakedMaskCacheEntry[m_cacheEntries.Length + 1]; int length2 = m_cacheEntries.Length; for (int i = 0; i < length2; i++) { newArray[i] = m_cacheEntries[i]; } newArray[newArray.Length - 1] = new BakedMaskCacheEntry(); WriteCacheEntry(newArray[newArray.Length - 1], texture, terrain, fileName); m_cacheEntries = newArray; //EditorUtility.SetDirty(this); #if UNITY_EDITOR EditorUtility.SetDirty(GaiaSessionManager.GetSessionManager(false)); #endif }
/// <summary> /// Get the terrain scene that matches this location, otherwise return null /// </summary> /// <param name="locationWU">Location to check in world units</param> /// <returns>Terrain here or null</returns> public static TerrainScene GetDynamicLoadedTerrain(Vector3 locationWU, GaiaSessionManager gsm = null) { if (gsm == null) { gsm = GaiaSessionManager.GetSessionManager(false); } foreach (TerrainScene terrainScene in TerrainLoaderManager.TerrainScenes) { if (terrainScene.m_bounds.min.x <= locationWU.x && terrainScene.m_bounds.min.z <= locationWU.z && terrainScene.m_bounds.max.x >= locationWU.x && terrainScene.m_bounds.max.z >= locationWU.z) { return(terrainScene); } } return(null); }
/// <summary> /// Create the terrain defined by these settings /// </summary> public void CreateTerrain() { Terrain[,] world; //Update the session GaiaSessionManager sessionMgr = GaiaSessionManager.GetSessionManager(); if (sessionMgr != null && sessionMgr.IsLocked() != true) { //Update terrain settings in session sessionMgr.m_session.m_terrainWidth = m_tilesX * m_terrainSize; sessionMgr.m_session.m_terrainDepth = m_tilesZ * m_terrainSize; sessionMgr.m_session.m_terrainHeight = m_terrainHeight; sessionMgr.AddDefaults(this); sessionMgr.SetSeaLevel(m_seaLevel); //Then add the operation GaiaOperation op = new GaiaOperation(); op.m_description = "Creating terrain"; op.m_generatedByID = m_defaultsID; op.m_generatedByName = this.name; op.m_generatedByType = this.GetType().ToString(); op.m_isActive = true; op.m_operationDateTime = DateTime.Now.ToString(); op.m_operationType = GaiaOperation.OperationType.CreateTerrain; sessionMgr.AddOperation(op); } //Create the terrains array world = new Terrain[m_tilesX, m_tilesZ]; //And iterate through and create each terrain for (int x = 0; x < m_tilesX; x++) { for (int z = 0; z < m_tilesZ; z++) { CreateTile(x, z, ref world, null); } } //Now join them together and remove their seams RemoveWorldSeams(ref world); }
private void ExportMask() { GaiaWorldManager mgr = new GaiaWorldManager(Terrain.activeTerrains); if (mgr.TileCount > 0) { GaiaSessionManager gsm = GaiaSessionManager.GetSessionManager(); string path = GaiaDirectories.GetExportDirectory(gsm.m_session); path = Path.Combine(path, PWCommon4.Utils.FixFileName(m_maskName)); mgr.ExportSplatmapAsPng(path, m_selectedMask); Debug.Log("Created " + path); AssetDatabase.Refresh(); EditorUtility.FocusProjectWindow(); EditorUtility.DisplayDialog("Export complete", " Your texture mask has been saved to : " + path, "OK"); } else { EditorUtility.DisplayDialog("OOPS!", "You must have a valid terrain!!", "OK"); } }
public static void FinalizePlayerObjectRuntime(GameObject playerObj) { GaiaSessionManager session = GaiaSessionManager.GetSessionManager(); if (session != null) { if (session.m_session != null) { if (playerObj.transform.position.y < session.m_session.m_seaLevel) { playerObj.transform.position = new Vector3(playerObj.transform.position.x, session.m_session.m_seaLevel + 5f, playerObj.transform.position.z); } } } #if GAIA_PRO_PRESENT //Add the simple terrain culling script, useful in any case if (GaiaUtils.CheckIfSceneProfileExists()) { GaiaGlobal.Instance.SceneProfile.m_terrainCullingEnabled = true; } #endif bool dynamicLoadedTerrains = GaiaUtils.HasDynamicLoadedTerrains(); if (dynamicLoadedTerrains) { #if GAIA_PRO_PRESENT Terrain terrain = TerrainHelper.GetActiveTerrain(); TerrainLoader loader = playerObj.GetComponent <TerrainLoader>(); if (loader == null) { loader = playerObj.AddComponent <TerrainLoader>(); } loader.LoadMode = LoadMode.RuntimeAlways; float size = terrain.terrainData.size.x * 1.25f * 2f; loader.m_loadingBoundsRegular = new BoundsDouble(playerObj.transform.position, new Vector3(size, size, size)); loader.m_loadingBoundsImpostor = new BoundsDouble(playerObj.transform.position, new Vector3(size * 3f, size * 3f, size * 3f)); #endif } }
private void ExportNormal() { if (Terrain.activeTerrain == null) { EditorUtility.DisplayDialog("OOPS!", "You must have a valid terrain in your scene!!", "OK"); return; } GaiaWorldManager mgr = new GaiaWorldManager(Terrain.activeTerrains); if (mgr.TileCount > 0) { GaiaSessionManager gsm = GaiaSessionManager.GetSessionManager(); string path = GaiaDirectories.GetExportDirectory(gsm.m_session); mgr.LoadFromWorld(); path = Path.Combine(path, PWCommon4.Utils.FixFileName(m_maskName)); mgr.ExportNormalmapAsPng(path); AssetDatabase.Refresh(); EditorUtility.DisplayDialog("Export complete", " Your normal map has been saved to : " + path, "OK"); } }
/// <summary> /// Returns a folder that is named as the session asset, to store session related data into. /// </summary> /// <param name="gaiaSession">The session to create the directory for</param> /// <returns></returns> public static string GetSessionSubFolderPath(GaiaSession gaiaSession, bool create = true) { #if UNITY_EDITOR string masterScenePath = AssetDatabase.GetAssetPath(gaiaSession).Replace(".asset", ""); if (String.IsNullOrEmpty(masterScenePath)) { GaiaSessionManager gsm = GaiaSessionManager.GetSessionManager(false); gsm.SaveSession(); masterScenePath = AssetDatabase.GetAssetPath(gsm.m_session).Replace(".asset", ""); } if (create) { return(CreatePathIfDoesNotExist(masterScenePath)); } else { return(masterScenePath); } #else return(""); #endif }
void OnGUI() { //Set up the box style if (m_boxStyle == null) { m_boxStyle = new GUIStyle(GUI.skin.box); m_boxStyle.normal.textColor = GUI.skin.label.normal.textColor; m_boxStyle.fontStyle = FontStyle.Bold; m_boxStyle.alignment = TextAnchor.UpperLeft; } //Setup the wrap style if (m_wrapStyle == null) { m_wrapStyle = new GUIStyle(GUI.skin.label); m_wrapStyle.fontStyle = FontStyle.Normal; m_wrapStyle.wordWrap = true; } //Text intro GUILayout.BeginVertical("Gaia WaterFlow Mask Exporter", m_boxStyle); GUILayout.Space(20); EditorGUILayout.LabelField("The Gaia waterflow exporter allows you to calculate and export a water flow mask from your terrain.", m_wrapStyle); GUILayout.EndVertical(); if (string.IsNullOrEmpty(m_maskName)) { m_maskName = string.Format("TerrainWaterFlow-{0:yyyyMMdd-HHmmss}", DateTime.Now); } m_maskName = EditorGUILayout.TextField(GetLabel("Mask Name"), m_maskName); m_waterFlowMap.m_dropletVolume = EditorGUILayout.Slider(GetLabel("Droplet Volume"), m_waterFlowMap.m_dropletVolume, 0.1f, 2f); m_waterFlowMap.m_dropletAbsorbtionRate = EditorGUILayout.Slider(GetLabel("Droplet Absorbtion Rate"), m_waterFlowMap.m_dropletAbsorbtionRate, 0.01f, 1f); m_waterFlowMap.m_waterflowSmoothIterations = EditorGUILayout.IntSlider(GetLabel("Smooth Iterations"), m_waterFlowMap.m_waterflowSmoothIterations, 0, 10); GUILayout.Space(5); EditorGUI.indentLevel++; if (DisplayButton(GetLabel("Create Mask"))) { Terrain terrain = Gaia.TerrainHelper.GetActiveTerrain(); if (terrain == null) { EditorUtility.DisplayDialog("OOPS!", "You must have a valid terrain!!", "OK"); return; } GaiaSessionManager gsm = GaiaSessionManager.GetSessionManager(); string path = GaiaDirectories.GetExportDirectory(gsm.m_session); path = Path.Combine(path, PWCommon4.Utils.FixFileName(m_maskName)); m_waterFlowMap.CreateWaterFlowMap(terrain); m_waterFlowMap.ExportWaterMapToPath(path); GaiaWorldManager mgr = new GaiaWorldManager(Terrain.activeTerrains); mgr.LoadFromWorld(); path += "WaterFlow"; mgr.ExportWaterflowMapAsPng(m_waterFlowMap.m_waterflowSmoothIterations, path); AssetDatabase.Refresh(); EditorUtility.DisplayDialog("Done!", "Your mask is available at " + path, "OK"); } EditorGUI.indentLevel--; }
/// <summary> /// Crate post processing instance profile /// </summary> /// <param name="sceneProfile"></param> public static void CreatePostFXProfileInstance(SceneProfile sceneProfile, GaiaLightingProfileValues profile) { try { if (sceneProfile == null) { return; } #if UPPipeline VolumeProfile volumeProfile = AssetDatabase.LoadAssetAtPath <VolumeProfile>(GaiaUtils.GetAssetPath("URP Global Post Processing Profile.asset")); if (profile.PostProcessProfileURP != null) { volumeProfile = profile.PostProcessProfileURP; } if (volumeProfile == null) { return; } GaiaSessionManager session = GaiaSessionManager.GetSessionManager(); if (session != null) { string path = GaiaDirectories.GetSceneProfilesFolderPath(session.m_session); if (!string.IsNullOrEmpty(path)) { if (EditorSceneManager.GetActiveScene() != null) { if (!string.IsNullOrEmpty(EditorSceneManager.GetActiveScene().path)) { path = path + "/" + EditorSceneManager.GetActiveScene().name + " " + volumeProfile.name + " Profile.asset"; } else { path = path + "/" + volumeProfile.name + " HDRP Post FX Profile.asset"; } } else { path = path + "/" + volumeProfile.name + " HDRP Post FX Profile.asset"; } if (sceneProfile.m_universalPostFXProfile != null) { if (!sceneProfile.m_isUserProfileSet) { if (!sceneProfile.m_universalPostFXProfile.name.Contains(volumeProfile.name)) { AssetDatabase.DeleteAsset(AssetDatabase.GetAssetPath(sceneProfile.m_universalPostFXProfile)); sceneProfile.m_universalPostFXProfile = null; } } } if (AssetDatabase.LoadAssetAtPath <VolumeProfile>(path) == null) { FileUtil.CopyFileOrDirectory(AssetDatabase.GetAssetPath(volumeProfile), path); AssetDatabase.ImportAsset(path); } sceneProfile.m_universalPostFXProfile = AssetDatabase.LoadAssetAtPath <VolumeProfile>(path); } } #endif } catch (Exception e) { Console.WriteLine(e); throw; } }
public static void ShowWorldMapStampSpawner() { Terrain worldMapTerrain = TerrainHelper.GetWorldMapTerrain(); if (worldMapTerrain == null) { Debug.LogError("No world map created yet! Please create a world map first before opening the random terrain generator"); return; } GaiaSessionManager gsm = GaiaSessionManager.GetSessionManager(false); //Get the Gaia Settings GaiaSettings settings = GaiaUtils.GetGaiaSettings(); //Create or find the stamper GameObject spawnerObj = GaiaUtils.GetOrCreateWorldDesigner(); Spawner spawner = spawnerObj.GetComponent <WorldDesigner>(); if (spawner == null) { spawner = spawnerObj.AddComponent <WorldDesigner>(); if (settings != null) { if (settings.m_defaultStampSpawnSettings != null) { spawner.LoadSettings(settings.m_defaultStampSpawnSettings); } } spawner.m_settings.m_isWorldmapSpawner = true; spawner.m_worldMapTerrain = worldMapTerrain; //set up the export settings with the current Gaia Settings / defaults spawner.m_worldCreationSettings.m_targeSizePreset = settings.m_targeSizePreset; spawner.m_worldCreationSettings.m_xTiles = settings.m_tilesX; spawner.m_worldCreationSettings.m_zTiles = settings.m_tilesZ; spawner.m_worldTileSize = GaiaUtils.IntToEnvironmentSize(settings.m_currentDefaults.m_terrainSize); spawner.m_worldCreationSettings.m_tileSize = settings.m_currentDefaults.m_terrainSize; spawner.m_worldCreationSettings.m_tileHeight = settings.m_currentDefaults.m_terrainHeight; spawner.m_worldCreationSettings.m_createInScene = settings.m_createTerrainScenes; spawner.m_worldCreationSettings.m_autoUnloadScenes = settings.m_unloadTerrainScenes; spawner.m_worldCreationSettings.m_applyFloatingPointFix = settings.m_floatingPointFix; spawner.m_worldCreationSettings.m_qualityPreset = settings.m_currentEnvironment; if (spawner.m_worldCreationSettings.m_gaiaDefaults == null) { spawner.m_worldCreationSettings.m_gaiaDefaults = settings.m_currentDefaults; } spawner.StoreWorldSize(); //spawner.StoreHeightmapResolution(); //Check if we do have an existing terrain already, if yes, we would want to re-use it for the world map -> terrain export if (GaiaUtils.HasTerrains()) { spawner.m_useExistingTerrainForWorldMapExport = true; } else { //No terrains yet - set up the terrain tiles in the session according to the current world creation settings //so that the stamp previews will come out right. TerrainLoaderManager.Instance.TerrainSceneStorage.m_terrainTilesX = settings.m_tilesX; TerrainLoaderManager.Instance.TerrainSceneStorage.m_terrainTilesZ = settings.m_tilesZ; } spawner.FitToTerrain(); spawner.UpdateMinMaxHeight(); } else { spawner.m_settings.m_isWorldmapSpawner = true; spawner.m_worldMapTerrain = worldMapTerrain; spawner.FitToTerrain(); spawner.UpdateMinMaxHeight(); } gsm.m_session.m_worldBiomeMaskSettings = spawner.m_settings; TerrainLoaderManager.Instance.SwitchToWorldMap(); #if UNITY_EDITOR Selection.activeGameObject = spawnerObj; #endif }
private void DrawTerrains(bool helpEnabled) { bool originalGUIState = GUI.enabled; #if GAIA_PRO_PRESENT EditorGUILayout.BeginHorizontal(); m_editorUtils.Label("IngestTerrain", GUILayout.Width(100)); m_ingestTerrain = (Terrain)EditorGUILayout.ObjectField(m_ingestTerrain, typeof(Terrain), true); if (m_editorUtils.Button("Ingest")) { ////Try to find the X and Z coordinate for the scene name //double minX = m_terrainLoaderManager.TerrainSceneStorage.m_terrainScenes.Select(x => x.m_pos.x).Min(); //double maxX = m_terrainLoaderManager.TerrainSceneStorage.m_terrainScenes.Select(x => x.m_pos.x).Max(); //double minZ = m_terrainLoaderManager.TerrainSceneStorage.m_terrainScenes.Select(x => x.m_pos.z).Min(); //double maxZ = m_terrainLoaderManager.TerrainSceneStorage.m_terrainScenes.Select(x => x.m_pos.z).Max(); GaiaSessionManager sessionManager = GaiaSessionManager.GetSessionManager(); WorldCreationSettings worldCreationSettings = new WorldCreationSettings() { m_autoUnloadScenes = false, m_applyFloatingPointFix = TerrainLoaderManager.Instance.TerrainSceneStorage.m_useFloatingPointFix, m_isWorldMap = false }; TerrainScene newScene = TerrainSceneCreator.CreateTerrainScene(m_ingestTerrain.gameObject.scene, TerrainLoaderManager.Instance.TerrainSceneStorage, sessionManager.m_session, m_ingestTerrain.gameObject, worldCreationSettings); TerrainLoaderManager.Instance.TerrainSceneStorage.m_terrainScenes.Add(newScene); TerrainLoaderManager.Instance.SaveStorageData(); GaiaSessionManager.AddTerrainScenesToBuildSettings(new List <TerrainScene>() { newScene }); } EditorGUILayout.EndHorizontal(); GUILayout.Space(EditorGUIUtility.singleLineHeight); #endif EditorGUILayout.BeginHorizontal(); if (m_editorUtils.Button("AddToBuildSettings")) { if (TerrainLoaderManager.ColliderOnlyLoadingActive) { if (EditorUtility.DisplayDialog(m_editorUtils.GetTextValue("AddColliderScenesToBuildSettingsPopupTitle"), m_editorUtils.GetTextValue("AddColliderScenesToBuildSettingsPopupText"), m_editorUtils.GetTextValue("Continue"), m_editorUtils.GetTextValue("Cancel"))) { #if GAIA_PRO_PRESENT GaiaSessionManager.AddOnlyColliderScenesToBuildSettings(m_terrainLoaderManager.TerrainSceneStorage.m_terrainScenes); #endif } } else { if (EditorUtility.DisplayDialog(m_editorUtils.GetTextValue("AddToBuildSettingsPopupTitle"), m_editorUtils.GetTextValue("AddToBuildSettingsPopupText"), m_editorUtils.GetTextValue("Continue"), m_editorUtils.GetTextValue("Cancel"))) { #if GAIA_PRO_PRESENT GaiaSessionManager.AddTerrainScenesToBuildSettings(m_terrainLoaderManager.TerrainSceneStorage.m_terrainScenes); #endif } } } EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(); if (m_editorUtils.Button("UnloadAll")) { m_terrainLoaderManager.SetLoadingRange(0, 0); m_terrainLoaderManager.UnloadAll(true); } if (m_editorUtils.Button("LoadAll")) { if (EditorUtility.DisplayDialog(m_editorUtils.GetTextValue("LoadAllPopupTitle"), m_editorUtils.GetTextValue("LoadAllPopupText"), m_editorUtils.GetTextValue("Continue"), m_editorUtils.GetTextValue("Cancel"))) { foreach (TerrainScene terrainScene in m_terrainLoaderManager.TerrainSceneStorage.m_terrainScenes) { m_terrainLoaderManager.SetLoadingRange(100000, m_terrainLoaderManager.GetImpostorLoadingRange()); terrainScene.AddRegularReference(m_terrainLoaderManager.gameObject); } } } EditorGUILayout.EndHorizontal(); if (!GaiaUtils.HasImpostorTerrains()) { GUI.enabled = false; } EditorGUILayout.BeginHorizontal(); if (m_editorUtils.Button("UnloadAllImpostors")) { m_terrainLoaderManager.SetLoadingRange(m_terrainLoaderManager.GetLoadingRange(), 0); m_terrainLoaderManager.UnloadAllImpostors(true); } if (m_editorUtils.Button("LoadAllImpostors")) { if (EditorUtility.DisplayDialog(m_editorUtils.GetTextValue("LoadAllPopupTitle"), m_editorUtils.GetTextValue("LoadAllImpostorsPopupText"), m_editorUtils.GetTextValue("Continue"), m_editorUtils.GetTextValue("Cancel"))) { m_terrainLoaderManager.SetLoadingRange(m_terrainLoaderManager.GetLoadingRange(), 100000); foreach (TerrainScene terrainScene in m_terrainLoaderManager.TerrainSceneStorage.m_terrainScenes) { terrainScene.AddImpostorReference(m_terrainLoaderManager.gameObject); } } } EditorGUILayout.EndHorizontal(); GUI.enabled = originalGUIState; GUILayout.Space(EditorGUIUtility.singleLineHeight); float buttonWidth1 = 110; float buttonWidth2 = 60; if (m_terrainBoxStyle == null || m_terrainBoxStyle.normal.background == null) { m_terrainBoxStyle = new GUIStyle(EditorStyles.helpBox); m_terrainBoxStyle.margin = new RectOffset(0, 0, 0, 0); m_terrainBoxStyle.padding = new RectOffset(3, 3, 3, 3); } int removeIndex = -99; int currentIndex = 0; foreach (TerrainScene terrainScene in m_terrainLoaderManager.TerrainSceneStorage.m_terrainScenes) { EditorGUILayout.BeginVertical(m_terrainBoxStyle); { EditorGUILayout.LabelField(terrainScene.GetTerrainName()); EditorGUILayout.BeginHorizontal(); bool isLoaded = terrainScene.m_regularLoadState == LoadState.Loaded && terrainScene.TerrainObj != null && terrainScene.TerrainObj.activeInHierarchy; bool isImpostorLoaded = terrainScene.m_impostorLoadState == LoadState.Loaded || terrainScene.m_impostorLoadState == LoadState.Cached; bool currentGUIState = GUI.enabled; GUI.enabled = isLoaded; if (m_editorUtils.Button("SelectPlaceholder", GUILayout.Width(buttonWidth1))) { Selection.activeGameObject = GameObject.Find(terrainScene.GetTerrainName()); EditorGUIUtility.PingObject(Selection.activeObject); } GUI.enabled = currentGUIState; if (isLoaded) { if (m_editorUtils.Button("UnloadPlaceholder", GUILayout.Width(buttonWidth2))) { if (ResetToWorldOriginLoading()) { terrainScene.RemoveAllReferences(true); } } } else { if (m_editorUtils.Button("LoadPlaceholder", GUILayout.Width(buttonWidth2))) { if (ResetToWorldOriginLoading()) { terrainScene.AddRegularReference(m_terrainLoaderManager.gameObject); } } } if (string.IsNullOrEmpty(terrainScene.m_impostorScenePath)) { GUI.enabled = false; } if (isImpostorLoaded) { if (m_editorUtils.Button("UnLoadImpostor", GUILayout.Width(buttonWidth1))) { if (ResetToWorldOriginLoading()) { terrainScene.RemoveImpostorReference(m_terrainLoaderManager.gameObject, 0, true); } } } else { if (m_editorUtils.Button("LoadImpostor", GUILayout.Width(buttonWidth1))) { if (ResetToWorldOriginLoading()) { terrainScene.AddImpostorReference(m_terrainLoaderManager.gameObject); } } } GUI.enabled = originalGUIState; if (m_editorUtils.Button("RemoveScene")) { if (EditorUtility.DisplayDialog(m_editorUtils.GetTextValue("RemoveSceneTitle"), m_editorUtils.GetTextValue("RemoveSceneText"), m_editorUtils.GetTextValue("Continue"), m_editorUtils.GetTextValue("Cancel"))) { removeIndex = currentIndex; } } EditorGUILayout.EndHorizontal(); if (terrainScene.RegularReferences.Count > 0) { EditorGUI.indentLevel++; terrainScene.m_isFoldedOut = m_editorUtils.Foldout(terrainScene.m_isFoldedOut, "ShowTerrainReferences"); if (terrainScene.m_isFoldedOut) { foreach (GameObject go in terrainScene.RegularReferences) { EditorGUILayout.BeginHorizontal(); GUILayout.Space(20); m_editorUtils.Label(new GUIContent(go.name, m_editorUtils.GetTextValue("TerrainReferenceToolTip"))); if (m_editorUtils.Button("TerrainReferenceSelect", GUILayout.Width(buttonWidth1))) { Selection.activeObject = go; SceneView.lastActiveSceneView.FrameSelected(); } if (m_editorUtils.Button("TerrainReferenceRemove", GUILayout.Width(buttonWidth2))) { terrainScene.RemoveRegularReference(go); } GUILayout.Space(100); EditorGUILayout.EndHorizontal(); } } EditorGUI.indentLevel--; } if (terrainScene.ImpostorReferences.Count > 0) { EditorGUI.indentLevel++; terrainScene.m_isFoldedOut = m_editorUtils.Foldout(terrainScene.m_isFoldedOut, "ShowImpostorReferences"); if (terrainScene.m_isFoldedOut) { foreach (GameObject go in terrainScene.ImpostorReferences) { EditorGUILayout.BeginHorizontal(); GUILayout.Space(20); m_editorUtils.Label(new GUIContent(go.name, m_editorUtils.GetTextValue("TerrainReferenceToolTip"))); if (m_editorUtils.Button("TerrainReferenceSelect", GUILayout.Width(buttonWidth1))) { Selection.activeObject = go; SceneView.lastActiveSceneView.FrameSelected(); } if (m_editorUtils.Button("TerrainReferenceRemove", GUILayout.Width(buttonWidth2))) { terrainScene.RemoveImpostorReference(go); } GUILayout.Space(100); EditorGUILayout.EndHorizontal(); } } EditorGUI.indentLevel--; } } GUILayout.EndVertical(); GUILayout.Space(5f); currentIndex++; } if (removeIndex != -99) { AssetDatabase.DeleteAsset(m_terrainLoaderManager.TerrainSceneStorage.m_terrainScenes[removeIndex].m_scenePath); m_terrainLoaderManager.TerrainSceneStorage.m_terrainScenes.RemoveAt(removeIndex); m_terrainLoaderManager.SaveStorageData(); } }
/// <summary> /// Clear all the trees on all the terrains /// </summary> public static void ClearSpawns(SpawnerResourceType resourceType, ClearSpawnFor clearSpawnFor, ClearSpawnFrom clearSpawnFrom, List <string> terrainNames = null, Spawner spawner = null) { if (terrainNames == null) { if (clearSpawnFor == ClearSpawnFor.AllTerrains) { if (GaiaUtils.HasDynamicLoadedTerrains()) { GaiaSessionManager sessionManager = GaiaSessionManager.GetSessionManager(); terrainNames = TerrainLoaderManager.TerrainScenes.Select(x => x.GetTerrainName()).ToList(); } else { terrainNames = Terrain.activeTerrains.Select(x => x.name).ToList(); } } else { terrainNames = new List <string> { spawner.GetCurrentTerrain().name }; } } string progressBarTitle = "Clearing..."; Action <Terrain> act = null; switch (resourceType) { case SpawnerResourceType.TerrainTexture: progressBarTitle = "Clearing Textures"; //Not supported, should not be required throw new NotSupportedException("Clearing of Textures is currently not supported via the terrain helper"); case SpawnerResourceType.TerrainDetail: progressBarTitle = "Clearing Terrain Details"; act = (t) => ClearDetailsOnSingleTerrain(t, spawner, clearSpawnFrom); break; case SpawnerResourceType.TerrainTree: progressBarTitle = "Clearing Trees"; act = (t) => ClearTreesOnSingleTerrain(t, spawner, clearSpawnFrom); break; case SpawnerResourceType.GameObject: progressBarTitle = "Clearing Game Objects"; act = (t) => ClearGameObjectsOnSingleTerrain(t, spawner, clearSpawnFrom); break; case SpawnerResourceType.Probe: progressBarTitle = "Clearing Probes"; act = (t) => ClearGameObjectsOnSingleTerrain(t, spawner, clearSpawnFrom); break; case SpawnerResourceType.SpawnExtension: progressBarTitle = "Clearing Spawn Extensions"; act = (t) => ClearSpawnExtensionsOnSingleTerrain(t, spawner, clearSpawnFrom); break; case SpawnerResourceType.StampDistribution: //Not supported, should not be required throw new NotSupportedException("Clearing of Stamps is currently not supported via the terrain helper"); } if (GaiaUtils.HasDynamicLoadedTerrains()) { GaiaUtils.CallFunctionOnDynamicLoadedTerrains(act, true, terrainNames); } else { for (int idx = 0; idx < terrainNames.Count; idx++) { ProgressBar.Show(ProgressBarPriority.Spawning, progressBarTitle, progressBarTitle, idx + 1, terrainNames.Count(), true); GameObject go = GameObject.Find(terrainNames[idx]); if (go != null) { Terrain terrain = go.GetComponent <Terrain>(); act(terrain); } ProgressBar.Clear(ProgressBarPriority.Spawning); } } }
/// <summary> /// Get the bounds of the terrain at this location or fail with a null /// </summary> /// <param name="locationWU">Location to check and get terrain for</param> /// <returns>Bounds of selected terrain or null if invalid for some reason</returns> public static bool GetTerrainBounds(ref BoundsDouble bounds, bool activeTerrainsOnly = false) { //Terrain terrain = GetTerrain(locationWU); //if (terrain == null) //{ // return false; //} //bounds.center = terrain.transform.position; //bounds.size = terrain.terrainData.size; //bounds.center += bounds.extents; Vector3Double accumulatedCenter = new Vector3Double(); //Do we use dynamic loaded terrains in the scene? if (GaiaUtils.HasDynamicLoadedTerrains() && !activeTerrainsOnly) { #if GAIA_PRO_PRESENT //we do have dynamic terrains -> calculate the bounds according to the terrain scene data in the session GaiaSessionManager gsm = GaiaSessionManager.GetSessionManager(false); foreach (TerrainScene t in TerrainLoaderManager.TerrainScenes) { accumulatedCenter += t.m_bounds.center; } bounds.center = accumulatedCenter / TerrainLoaderManager.TerrainScenes.Count; foreach (TerrainScene t in TerrainLoaderManager.TerrainScenes) { bounds.Encapsulate(t.m_bounds); } #endif } else { //no placeholder -> calculate bounds according to the active terrains in the scene if (Terrain.activeTerrains.Length > 0) { foreach (Terrain t in Terrain.activeTerrains) { if (!TerrainHelper.IsWorldMapTerrain(t)) { if (t.terrainData != null) { accumulatedCenter += new Vector3Double(t.transform.position) + new Vector3Double(t.terrainData.bounds.extents); } else { Debug.LogWarning("Terrain " + t.name + " in the scene is missing the terrain data object!"); } } } bounds.center = accumulatedCenter / Terrain.activeTerrains.Length; foreach (Terrain t in Terrain.activeTerrains) { if (!TerrainHelper.IsWorldMapTerrain(t)) { if (t.terrainData != null) { Bounds newBounds = new Bounds(); newBounds.center = t.transform.position; newBounds.size = t.terrainData.size; newBounds.center += t.terrainData.bounds.extents; bounds.Encapsulate(newBounds); } } } } else { bounds = new BoundsDouble(Vector3Double.zero, Vector3Double.zero); //No active terrains? There might be mesh terrains we can use then GameObject meshTerrainExportObject = GaiaUtils.GetTerrainExportObject(false); if (meshTerrainExportObject != null) { foreach (Transform t in meshTerrainExportObject.transform) { MeshRenderer mr = t.GetComponent <MeshRenderer>(); if (mr != null) { bounds.Encapsulate(mr.bounds); } } } } } return(true); }
public void LoadStorageData() { #if UNITY_EDITOR //Try to get the terrain scene storage file from the last used GUID first if (!String.IsNullOrEmpty(m_lastUsedGUID)) { m_terrainSceneStorage = (TerrainSceneStorage)AssetDatabase.LoadAssetAtPath(AssetDatabase.GUIDToAssetPath(m_lastUsedGUID), typeof(TerrainSceneStorage)); } //No guid / storage object? Then we need to create one in the current session directory if (m_terrainSceneStorage == null) { GaiaSessionManager gsm = GaiaSessionManager.GetSessionManager(); if (gsm != null && gsm.m_session != null) { string path = GaiaDirectories.GetScenePath(gsm.m_session) + "/TerrainScenes.asset"; if (File.Exists(path)) { m_terrainSceneStorage = (TerrainSceneStorage)AssetDatabase.LoadAssetAtPath(path, typeof(TerrainSceneStorage)); } else { m_terrainSceneStorage = ScriptableObject.CreateInstance <TerrainSceneStorage>(); if (TerrainHelper.GetWorldMapTerrain() != null) { m_terrainSceneStorage.m_hasWorldMap = true; } AssetDatabase.CreateAsset(m_terrainSceneStorage, path); AssetDatabase.ImportAsset(path); } } else { m_terrainSceneStorage = ScriptableObject.CreateInstance <TerrainSceneStorage>(); } } //Check if there are scene files existing already and if they are in the storage data - if not, we should pick them up accordingly string directory = GaiaDirectories.GetTerrainScenePathForStorageFile(m_terrainSceneStorage); var dirInfo = new DirectoryInfo(directory); bool madeChanges = false; if (dirInfo != null) { FileInfo[] allFiles = dirInfo.GetFiles(); foreach (FileInfo fileInfo in allFiles) { if (fileInfo.Extension == ".unity") { string path = GaiaDirectories.GetPathStartingAtAssetsFolder(fileInfo.FullName); if (!m_terrainSceneStorage.m_terrainScenes.Exists(x => x.GetTerrainName() == x.GetTerrainName(path))) { string firstSegment = fileInfo.Name.Split('-')[0]; int xCoord = -99; int zCoord = -99; bool successX, successZ; try { successX = Int32.TryParse(firstSegment.Substring(firstSegment.IndexOf('_') + 1, firstSegment.LastIndexOf('_') - (firstSegment.IndexOf('_') + 1)), out xCoord); successZ = Int32.TryParse(firstSegment.Substring(firstSegment.LastIndexOf('_') + 1, firstSegment.Length - 1 - firstSegment.LastIndexOf('_')), out zCoord); } catch (Exception ex) { if (ex.Message == "123") { } successX = false; successZ = false; } if (successX && successZ) { //double centerX = (xCoord - (m_terrainSceneStorage.m_terrainTilesX / 2f)) * m_terrainSceneStorage.m_terrainTilesSize + (m_terrainSceneStorage.m_terrainTilesSize /2f); //double centerZ = (zCoord - (m_terrainSceneStorage.m_terrainTilesZ / 2f)) * m_terrainSceneStorage.m_terrainTilesSize + (m_terrainSceneStorage.m_terrainTilesSize / 2f); Vector2 offset = new Vector2(-m_terrainSceneStorage.m_terrainTilesSize * m_terrainSceneStorage.m_terrainTilesX * 0.5f, -m_terrainSceneStorage.m_terrainTilesSize * m_terrainSceneStorage.m_terrainTilesZ * 0.5f); Vector3Double position = new Vector3(m_terrainSceneStorage.m_terrainTilesSize * xCoord + offset.x, 0, m_terrainSceneStorage.m_terrainTilesSize * zCoord + offset.y); Vector3Double center = new Vector3Double(position + new Vector3Double(m_terrainSceneStorage.m_terrainTilesSize / 2f, 0f, m_terrainSceneStorage.m_terrainTilesSize / 2f)); BoundsDouble bounds = new BoundsDouble(center, new Vector3Double(m_terrainSceneStorage.m_terrainTilesSize, m_terrainSceneStorage.m_terrainTilesSize * 4, m_terrainSceneStorage.m_terrainTilesSize)); //Use forward slashes in the path - The Unity scene management classes expect it that way path = path.Replace("\\", "/"); TerrainScene terrainScene = new TerrainScene() { m_scenePath = path, m_pos = position, m_bounds = bounds, m_useFloatingPointFix = m_terrainSceneStorage.m_useFloatingPointFix }; if (File.Exists(path.Replace("Terrain", GaiaConstants.ImpostorTerrainName))) { terrainScene.m_impostorScenePath = path.Replace("Terrain", GaiaConstants.ImpostorTerrainName); } if (File.Exists(path.Replace("Terrain", "Collider"))) { terrainScene.m_colliderScenePath = path.Replace("Terrain", "Collider"); } if (File.Exists(path.Replace("Terrain", "Backup"))) { terrainScene.m_backupScenePath = path.Replace("Terrain", "Backup"); } m_terrainSceneStorage.m_terrainScenes.Add(terrainScene); madeChanges = true; } } } } if (madeChanges) { EditorUtility.SetDirty(m_terrainSceneStorage); AssetDatabase.SaveAssets(); } } m_lastUsedGUID = AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(m_terrainSceneStorage)); RefreshTerrainsWithCurrentData(); RefreshSceneViewLoadingRange(); ////Go over the currently open scene and close the ones that do not seem to have a reference on them //for (int i = EditorSceneManager.loadedSceneCount-1; i >= 0; i--) //{ // Scene scene = EditorSceneManager.GetSceneAt(i); // if (EditorSceneManager.GetActiveScene().Equals(scene)) // { // continue; // } // TerrainScene terrainScene = m_terrainSceneStorage.m_terrainScenes.Find(x => x.m_scenePath == scene.path || x.m_impostorScenePath == scene.path || x.m_colliderScenePath == scene.path); // if (terrainScene != null) // { // terrainScene.UpdateWithCurrentData(); // } // else // { // EditorSceneManager.UnloadSceneAsync(scene); // } //} #endif }
public override void OnInspectorGUI() { //Get our resource m_session = (GaiaSession)target; //Set up the box style if (m_boxStyle == null) { m_boxStyle = new GUIStyle(GUI.skin.box); m_boxStyle.normal.textColor = GUI.skin.label.normal.textColor; m_boxStyle.fontStyle = FontStyle.Bold; m_boxStyle.alignment = TextAnchor.UpperLeft; } //Setup the wrap style if (m_wrapStyle == null) { m_wrapStyle = new GUIStyle(GUI.skin.label); m_wrapStyle.wordWrap = true; } //Set up the description wrap style if (m_descWrapStyle == null) { m_descWrapStyle = new GUIStyle(GUI.skin.textArea); m_descWrapStyle.wordWrap = true; } //Create a nice text intro GUILayout.BeginVertical("Gaia Session", m_boxStyle); GUILayout.Space(20); EditorGUILayout.LabelField("Contains the data used to backup, share and play back sessions. Use the session manager to view, edit or play back sessions.", m_wrapStyle); GUILayout.Space(4); GUILayout.EndVertical(); //Make some space GUILayout.Space(4); //Wrap it up in a box GUILayout.BeginVertical(m_boxStyle); GUILayout.BeginVertical("Summary:", m_boxStyle); GUILayout.Space(20); //Display the basic details EditorGUILayout.LabelField("Name", m_session.m_name); EditorGUILayout.LabelField("Description", m_session.m_description, m_wrapStyle); EditorGUILayout.LabelField("Created", m_session.m_dateCreated); EditorGUILayout.LabelField("Dimensions", string.Format("w{0} d{1} h{2} meters", m_session.m_terrainWidth, m_session.m_terrainDepth, m_session.m_terrainHeight)); EditorGUILayout.LabelField("Sea Level", string.Format("{0} meters", m_session.m_seaLevel)); EditorGUILayout.LabelField("Locked", m_session.m_isLocked.ToString()); Texture2D previewImage = m_session.m_previewImage; if (previewImage != null) { //Get aspect ratio and available space and display the image float width = Screen.width - 43f; float height = previewImage.height * (width / previewImage.width); GUILayout.Label(previewImage, GUILayout.MaxWidth(width), GUILayout.MaxHeight(height)); } GUILayout.EndVertical(); //Iterate through the operations GUILayout.BeginVertical("Operations:", m_boxStyle); GUILayout.Space(20); if (m_session.m_operations.Count == 0) { GUILayout.Space(5); GUILayout.Label("No operations yet..."); GUILayout.Space(5); } else { GaiaOperation op; EditorGUI.indentLevel++; for (int opIdx = 0; opIdx < m_session.m_operations.Count; opIdx++) { op = m_session.m_operations[opIdx]; if (op.m_isActive) { op.m_isFoldedOut = EditorGUILayout.Foldout(op.m_isFoldedOut, op.m_description, true); } else { op.m_isFoldedOut = EditorGUILayout.Foldout(op.m_isFoldedOut, op.m_description + " [inactive]", true); } if (op.m_isFoldedOut) { EditorGUI.indentLevel++; EditorGUILayout.LabelField("Description", op.m_description, m_wrapStyle); EditorGUILayout.LabelField("Created", op.m_operationDateTime); EditorGUILayout.LabelField("Active", op.m_isActive.ToString()); EditorGUI.indentLevel--; } } EditorGUI.indentLevel--; } GUILayout.EndVertical(); GUILayout.EndVertical(); if (GUILayout.Button("Play Session")) { GaiaSessionManager gsm = GaiaSessionManager.GetSessionManager(false, false); if (gsm == null) { GameObject gaiaObj = GaiaUtils.GetGaiaGameObject(); GameObject mgrObj = new GameObject("Session Manager"); gsm = mgrObj.AddComponent <GaiaSessionManager>(); mgrObj.transform.parent = gaiaObj.transform; } GaiaLighting.SetDefaultAmbientLight(GaiaUtils.GetGaiaSettings().m_gaiaLightingProfile); //make a copy of the session - otherwise there is the danger of conflicting with the old session data while playing back the session GaiaSession sessionCopy = Instantiate(m_session); sessionCopy.m_name = GaiaSessionManager.GetNewSessionName(); sessionCopy.name = sessionCopy.m_name; gsm.m_session = sessionCopy; string path = GaiaDirectories.GetSessionDirectory(); AssetDatabase.CreateAsset(sessionCopy, path + "/" + sessionCopy.m_name + ".asset"); AssetDatabase.SaveAssets(); GaiaSessionManager.PlaySession(sessionCopy); } if (GUILayout.Button("Open Session in Manager")) { GaiaSessionManager.LoadSession(m_session); } }
/// <summary> /// Draw gizmos /// </summary> void OnDrawGizmos() { if (m_resources == null) { return; } if (m_spawner == null) { return; } if (m_terrainHeightMap == null) { return; } //Lets visualise fitness float x, y = transform.position.y, z; float xStart = transform.position.x - m_range; float xEnd = transform.position.x + m_range; float zStart = transform.position.z - m_range; float zEnd = transform.position.z + m_range; float ballsize = Mathf.Clamp(m_resolution * 0.25f, 0.5f, 5f); m_spawner.m_settings.m_spawnRange = m_range; m_spawner.m_spawnerBounds = new Bounds(transform.position, new Vector3(m_range * 2f, m_range * 20f, m_range * 2f)); SpawnInfo spawnInfo = new SpawnInfo(); Vector3 location = new Vector3(); float fitness = 0f; //Create caches if ((DateTime.Now - m_lastCacheUpdateDate).TotalSeconds > 5) { m_lastCacheUpdateDate = DateTime.Now; m_spawner.DeleteSpawnCaches(); m_spawner.CreateSpawnCaches(m_selectedResourceType, m_selectedResourceIdx); //Also update the location so make moving it easier Terrain terrain = TerrainHelper.GetTerrain(transform.position); if (terrain != null) { transform.position = new Vector3(transform.position.x, terrain.SampleHeight(transform.position) + 5f, transform.position.z); } } //Set up the texture layer array in spawn info spawnInfo.m_textureStrengths = new float[Terrain.activeTerrain.terrainData.alphamapLayers]; //Now visualise fitness for (x = xStart; x < xEnd; x += m_resolution) { for (z = zStart; z < zEnd; z += m_resolution) { location.Set(x, y, z); if (m_spawner.CheckLocation(location, ref spawnInfo)) { fitness = GetFitness(ref spawnInfo); if (fitness < m_minimumFitness) { continue; } Gizmos.color = Color.Lerp(m_unfitColour, m_fitColour, fitness); Gizmos.DrawSphere(spawnInfo.m_hitLocationWU, ballsize); } } } //Now draw water //Water if (m_resources != null) { BoundsDouble bounds = new BoundsDouble(); if (TerrainHelper.GetTerrainBounds(ref bounds) == true) { bounds.center = new Vector3Double(bounds.center.x, GaiaSessionManager.GetSessionManager().GetSeaLevel(), bounds.center.z); bounds.size = new Vector3Double(bounds.size.x, 0.05f, bounds.size.z); Gizmos.color = new Color(Color.blue.r, Color.blue.g, Color.blue.b, Color.blue.a / 4f); Gizmos.DrawCube(bounds.center, bounds.size); } } }