TerrainInfo[] LoadTilesetSpeeds(TileSet tileSet) { var info = new TerrainInfo[tileSet.TerrainsCount]; for (var i = 0; i < info.Length; i++) { info[i] = TerrainInfo.Impassable; } foreach (var kvp in TerrainSpeeds) { int index; if (tileSet.TryGetTerrainIndex(kvp.Key, out index)) { info[index] = kvp.Value; } } return(info); }
public static int[,] GenerateBiomeMap(TerrainInfo info) { int[,] biomes = new int[info.TerrainWidth, info.TerrainHeight]; for (int y = 0; y < info.TerrainHeight; y++) { for (int x = 0; x < info.TerrainWidth; x++) { var biome_idx = GetCorrectBiomeIndex(info, x, y); biomes[x, y] = biome_idx; // initialise our seperated biomes dict, idx represents the index of the biome param (check the parameter list) if (!info.SeperatedBiomes.ContainsKey(biome_idx)) { info.SeperatedBiomes.Add(biome_idx, new List <TerrainPoint>()); } // add the point of our dict info.SeperatedBiomes[biome_idx].Add(new TerrainPoint(y, x)); } } return(biomes); }
private void Awake() { Ins = this; m_QuadTree = new QuadTree(Vector3.zero, QuadTreeConfig.TerrainSize); int terrainSize = QuadTreeConfig.TerrainSize; int gridSize = QuadTreeConfig.GridSize; for (int x = -terrainSize / 2 + gridSize / 2; x < terrainSize / 2; x += gridSize) { //Debug.DrawLine(new Vector3(x, 0, -terrainSize / 2), new Vector3(x, 0, terrainSize / 2), m_GridLineColor); for (int z = -terrainSize / 2 + gridSize / 2; z < terrainSize / 2; z += gridSize) { //Debug.DrawLine(new Vector3(-terrainSize / 2, 0, z), new Vector3(terrainSize / 2, 0, z), m_GridLineColor); Vector3 pos = new Vector3(x, 0, z); m_QuadTree.HandleObject(pos, true); } } }
public override async Task Execute() { TerrainInfo info = GetTerrainInfo(); await TextArea.PrintLine(); await TextArea.PrintLine(); await TextArea.PrintLine("You are in " + info.TerrainName + "."); await TextArea.Print("Travel: ", XleColor.White); await TextArea.Print(info.TravelText, XleColor.Green); await TextArea.Print(" - Food use: ", XleColor.White); await TextArea.Print(info.FoodUseText, XleColor.Green); await TextArea.PrintLine(); }
// Use this for initialization void Start() { Transform turningPointsObject = GameObject.FindGameObjectWithTag("routeTurningPoints").transform; int i = 0; routeTurningPoints.Add(GameObject.FindGameObjectWithTag("startPoint").transform); gridTurningPoints.Add(TerrainInfo.TransformToGrid(GameObject.FindGameObjectWithTag("startPoint").transform.position)); while (i < turningPointsObject.childCount) { routeTurningPoints.Add(turningPointsObject.GetChild(i).transform); gridTurningPoints.Add(TerrainInfo.TransformToGrid(turningPointsObject.GetChild(i).transform.position)); //Debug.Log ("Turning Points" + gridTurningPoints[i]); i++; } loadElevation(12, 6); loadMap(); buildMap(); }
// Use this for initialization void Awake() { var jsonTextFile = Resources.Load <TextAsset>(terrain_filename); myInfo = TerrainInfo.CreateFromJSON(jsonTextFile.text); myInfo.wall_height = wall_height; // a bit ugly... myInfo.CreateCubes(); // this code is used to create new terrains and obstacles //myInfo.TerrainInfo2(); //myInfo.file_name = "test88"; //string myString = myInfo.SaveToString(); //myInfo.WriteDataToFile(myString); Instantiate(flag, myInfo.start_pos, Quaternion.identity); Instantiate(flag, myInfo.goal_pos, Quaternion.identity); r_terrain = new ResolutionTerrain(this, 2); }
// Use this for initialization void Awake() { var jsonTextFile = Resources.Load <TextAsset>(terrain_filename); myInfo = TerrainInfo.CreateFromJSON(jsonTextFile.text); myInfo.wall_height = wall_height; // a bit ugly... myInfo.CreateCubes(); // this code is used to create new terrains and obstacles //myInfo.TerrainInfo2(); //myInfo.file_name = "test88"; //string myString = myInfo.SaveToString(); //myInfo.WriteDataToFile(myString); Instantiate(flag, myInfo.start_pos, Quaternion.identity); Instantiate(flag, myInfo.goal_pos, Quaternion.identity); //GameObject.Find("GraphObj").GetComponent<TravGraph>().makeMap(); }
protected Vector3 getRandomTargetPos(float minHeight = 0f, float maxHeight = 0f) { float maxDot = -1f; Vector3 targetPos = new Vector3(); for (int i = 0; i < 5; i++) { TerrainInfo info = GameObject.Find("Terrain").GetComponent <TerrainInfo>(); Vector3 mapPos = info.getPos(); Vector3 mapSize = info.getSize(); Vector3 pos = new Vector3(Random.Range(mapPos.x + mapSize.x * 0.2f, mapPos.x + mapSize.x * 0.8f), Random.Range(minHeight, maxHeight), Random.Range(mapPos.y + mapSize.y * 0.2f, mapPos.y + mapSize.y * 0.8f)); Vector3 direction = (pos - transform.position).normalized; float dot = Vector3.Dot(transform.forward, direction); if (dot > maxDot) { maxDot = dot; targetPos = pos; } } return(targetPos); }
void Start() { #if UNITY_EDITOR var terrainInfo = AssetDatabase.LoadAssetAtPath <TerrainInfo>(string.Format("Assets/TileMap/TerrainInfo.asset")); #else var terrainInfo = new TerrainInfo(); #endif string tilemapInfoPath = "Assets/TileMap/MapInfo"; string tilemapInfoName = "MapInfo_{0}_{1}"; string itemInfoPath = "Assets/TileMap/ItemInfo"; string itemInfoName = "ItemInfo_{0}_{1}"; string alphaTexInfoPath = "Assets/TileMap/TerrainAlpha"; string alphaTexInfoName = "TerrainAlpha_{0}_{1}"; string tilemapObjPath = "Assets/TileMap/TileMapObj/Prefab/Terrain"; string tilemapObjName = "Terrain@{0}"; string itemObjPath = "Assets/TileMap/TileMapObj/Prefab/Item"; string alphaTexObjPath = "Assets/TileMap/TileMapObj/Prefab/TerrainAlpha"; gen.Init(terrainInfo, size_W, size_H, item_W, item_H, size_W / 2 - 1, size_H / 2 - 1); gen.SetResPath(false, tilemapInfoPath, tilemapInfoName, itemInfoPath, itemInfoName, alphaTexInfoPath, alphaTexInfoName, tilemapObjPath, tilemapObjName, itemObjPath, alphaTexObjPath); // gen.Init(terrainInfo, terrainInfo.MapSize.x, terrainInfo.MapSize.y, terrainInfo.SpiltMapSize.x, terrainInfo.SpiltMapSize.y, size, Vector2.zero); }
public void GenerateBiomeContent(TerrainInfo info) { // testing for some biomes to get grass if (info.ApplyDetail) { PlaceNature(info); } if (info.ApplyContent) { // Totaly noob approach, dont use blue noise or anything, just select a random point and place an item therev for (int i = 0; i < info.SeperatedBiomes.Keys.Count; i++) { // instead of taking the first item, take random ? for (int j = 0; j < info.TerrainParameterList[i].ObjectListCount; j++) { // iterate trough all the objects, then place them, first pass is for random ground bullshit PlaceBiomeContent(info, i, info.TerrainParameterList[i].TerrainParameterObjectCount[j], info.TerrainParameterList[i].TerrainParameterObjectList[j]); } } } }
// placement of objects is invalid, since biomePoint.X and biomePoint.Z are ACTUAL INDICES IN THE ARRAY, NOT POINTS, TODO private void PlaceContent(TerrainInfo info, int biomeType, int objCount, GameObject placeableObject) { // good for debugging //for (int i = 0; i < info.SeperatedBiomes[biomeType].Count; i++) { // var biomePoint = info.SeperatedBiomes[biomeType][i]; // int terrainPositionY = (int)info._Terrain.terrainData.GetHeight(biomePoint.X, biomePoint.Z); // Instantiate(placeableObject, new Vector3(biomePoint.X, terrainPositionY, biomePoint.Z), Quaternion.identity); //} for (int i = 0; i < objCount; i++) { int randomPoint = UnityEngine.Random.Range(0, info.SeperatedBiomes[biomeType].Count - 1); var biomePoint = info.SeperatedBiomes[biomeType][randomPoint]; if (!biomePoint.ContainsItem) { int terrainPositionY = (int)info._Terrain.terrainData.GetHeight(biomePoint.X, biomePoint.Z); Instantiate(placeableObject, new Vector3(biomePoint.X, terrainPositionY, biomePoint.Z), Quaternion.identity, info.ContentManager.BiomeParentGameObjects[biomeType].transform); // to avoid placing multiple objects on one point, since we are doing it randomly info.SeperatedBiomes[biomeType][randomPoint].ContainsItem = true; } } }
public void SaveLightmap() { fogInfo = new FogInfo(); fogInfo.fog = RenderSettings.fog; fogInfo.fogMode = RenderSettings.fogMode; fogInfo.fogColor = RenderSettings.fogColor; fogInfo.fogStartDistance = RenderSettings.fogStartDistance; fogInfo.fogEndDistance = RenderSettings.fogEndDistance; m_RendererInfo = new List <RendererInfo>(); var renderers = GetComponentsInChildren <MeshRenderer>(); foreach (MeshRenderer r in renderers) { if (r.lightmapIndex != -1) { RendererInfo info = new RendererInfo(); info.renderer = r; info.lightmapOffsetScale = r.lightmapScaleOffset; info.lightmapIndex = r.lightmapIndex; m_RendererInfo.Add(info); } } terrains = GetComponentsInChildren <Terrain>(); if (terrains != null) { int cnt = terrains.Length; terrainsRendererInfo = new TerrainInfo[cnt]; for (int i = 0; i < cnt; i++) { var terrainRenderer = new TerrainInfo(); terrainRenderer.lightmapOffsetScale = terrains[i].lightmapScaleOffset; terrainRenderer.lightmapIndex = terrains[i].lightmapIndex; terrainsRendererInfo[i] = terrainRenderer; } } lightmapsMode = LightmapSettings.lightmapsMode; }
public static void FlatTerrainGridTest() { using (WorldWindow game = new WorldWindow()) { Vector3 eye = new Vector3(-4000, 4000, -4000); game.Camera.LookAt(eye, new Vector3()); game.CameraControl.MoveSpeed = 1000; Terrain terrain = new Terrain(); int rows = 80; int cols = 100; TerrainInfo info = new TerrainInfo() { SouthWestLatLong = new Vector2(-37, 174), NorthEastLatLong = new Vector2(-36.9f, 174.1f), DegreesLatitudePerPixel = 0.2 / (double)rows, DegreesLongitudePerPixel = 0.2 / (double)cols }; float[,] altInMetres = info.CreateFlatAltitudes(rows, cols); terrain.Recreate(info, altInMetres); ShaderModelRenderer sm = new ShaderModelRenderer(terrain); game.Models.Add(sm); UserInterface ui = new UserInterface(game); float time = 0; game.UpdateFrame += (o, e) => { time += (float)e.Time; double fps = e.Time == 0 ? 1000 : 1.0 / e.Time; ui.PrintCommonStats(e.Time); }; game.Run(30); } }
private void OnActivate() { // Parameter preset editor works in editor if (_ParameterPresetEditor == null) { _ParameterPresetEditor = new TerrainParameterPresetEditor(); } Script = (TerrainGeneration)target; // Noise parameter editor works in runtime if (Script.TerrainInfo != null) { // We are in runtime, means we can get all the info from runtime if (TerrainInfo == null) { TerrainInfo = Script.TerrainInfo; _NoiseParameterEditor = new NoiseParameterEditor(TerrainInfo); // now just overrwrite this terrain infos parameter property list (biomes) with our serialized editor list TerrainInfo.TerrainParameterList = _ParameterPresetEditor.SerializedTerrainParameters; } } WasInitialised = true; }
void Start() { ContentManager = GetComponent <ContentManager>(); SeasonalChange = GetComponent <SeasonalChange>(); RoadGenerator = GetComponent <RoadGenerator>(); TerrainInfo = new TerrainInfo(GetComponent <Terrain>()); SplineScript = GetComponentInChildren <Spline>(); if (UseCustomTerrainSizeDefinitions) { TerrainInfo.TerrainWidth = TerrainWidth; TerrainInfo.TerrainHeight = TerrainHeight; TerrainInfo.TerrainDepth = TerrainDepth; } // Figure out how to do this better, for now info has "manager" info (so we can use it elsewhere) TerrainInfo.ContentManager = ContentManager; ContentGenerator = GetComponent <ContentGenerator>(); TerrainInfo.ContentGenerator = ContentGenerator; TerrainInfo.RoadGenerator = RoadGenerator; // Initialize manager, need to handle path for different platforms (OSX, Windows) SerializationManager.InitializeManager(); // You can deserialize here and take the first NoiseParameter from the list if you dont want the default values InitializeTerrainWithPresetGeneration(); }
protected TerrainInfo InterfaceTerrainInfoToTerrainInfo(InterfaceTerrainInfo interfaceTerrainInfo) { TerrainInfo terrainInfo; TerrainBlueprintType terrainBlueprintType = InterfaceTerrainToolToTerrainBlueprintType(interfaceTerrainInfo.interfaceTerrainTool); switch (interfaceTerrainInfo.interfaceTerrainType) { case InterfaceTerrainType.Ground: // Ground TerrainGroundStyle terrainGroundStyle = InterfaceTerrainGroundStyleToTerrainGroundStyle(interfaceTerrainInfo.interfaceTerrainGroundStyle); float terrainGroundSegmentLength = InterfaceTerrainGroundGrainToTerrainSegmentLength(interfaceTerrainInfo.interfaceTerrainGroundGrain); terrainInfo = new TerrainInfo(terrainBlueprintType, terrainGroundStyle, terrainGroundSegmentLength); break; case InterfaceTerrainType.Roller: //Roller TerrainRollerStyle terrainRollerStyle = InterfaceTerrainRollerStyleToTerrainRollerStyle(interfaceTerrainInfo.interfaceTerrainRollerStyle); float terrainRollerSpacing = InterfaceTerrainRollerSpacingToTerrainRollerSpacing(interfaceTerrainInfo.interfaceTerrainRollerSpacing); bool terrainRollerFixed = InterfaceTerrainRollerRotationSpeedToTerrainRollerFixed(interfaceTerrainInfo.interfaceTerrainRollerRotationSpeed); float terrainRollerSpeed = InterfaceTerrainRollerRotationSpeedAndInterfaceTerrainRollerRotationToTerrainRollerSpeed(interfaceTerrainInfo.interfaceTerrainRollerRotationSpeed, interfaceTerrainInfo.interfaceTerrainRollerRotationDirection); terrainInfo = new TerrainInfo(terrainBlueprintType, terrainRollerStyle, terrainRollerSpacing, terrainRollerFixed, terrainRollerSpeed); break; default: Debug.LogWarning("Invalid InterfaceTerrainType [" + interfaceTerrainInfo.interfaceTerrainType + "]. Defaulting to InterfaceTerrainType.Ground"); goto case InterfaceTerrainType.Ground; } return(terrainInfo); }
public void HandleStep() { isInFront = true; if (cc.IsGrounded()) { sound.pitch = 1.0f + Random.Range(-0.1f, 0.1f); sound.volume = 1.0f + Random.Range(-0.2f, 0.0f); sound.PlayOneShot(footstepSound); float speedStumbleMultiplier = 1 + Mathf.Pow((cc.rigidbody.velocity.magnitude / (cc.sprintSpeed)), 5); float angleStumbleChance = 1000; int layerMask = 1 << 8; if (Physics.Raycast(transform.position, Vector3.down, out hit, 100, layerMask)) { objectiveSlopeAngle = Vector3.Angle(hit.normal, Vector3.up) * Mathf.Deg2Rad; footstepTerrain = hit.collider.GetComponentInParent <TerrainInfo>(); if (footstepTerrain != null) { angleStumbleChance = Mathf.Max(1, footstepTerrain.SlopeStumbleConstant - footstepTerrain.SlopeStumbleCoefficient * Mathf.Pow(ObjectiveSlopeAngleDeg(), footstepTerrain.SlopeStumbleExponent)); } } float lookingAtFeetMultiplier = Mathf.Min(Mathf.Max(5.5F - 0.05F * Vector3.Angle(Vector3.down, cam.transform.forward), 0.25F), 4F); if (Random.Range(0.0f, 1.0f) < (speedStumbleMultiplier / (angleStumbleChance * lookingAtFeetMultiplier))) { sound.pitch = 1.0f; sound.volume = 1.0f; sound.PlayOneShot(stumbleSound); cc.Stumble(); } else { sound.pitch = 1.0f + Random.Range(-0.1f, 0.1f); sound.volume = 1.0f + Random.Range(-0.2f, 0.0f); sound.PlayOneShot(footstepSound); cc.StableStep(); } } }
public override void Unpack(BinaryReader reader) { Id = reader.ReadUInt32(); RegionNumber = reader.ReadUInt32(); Version = reader.ReadUInt32(); RegionName = reader.ReadPString(); // "Dereth" reader.AlignBoundary(); LandDefs.Unpack(reader); GameTime.Unpack(reader); PartsMask = reader.ReadUInt32(); if ((PartsMask & 0x10) != 0) { SkyInfo.Unpack(reader); } if ((PartsMask & 0x01) != 0) { SoundInfo.Unpack(reader); } if ((PartsMask & 0x02) != 0) { SceneInfo.Unpack(reader); } TerrainInfo.Unpack(reader); if ((PartsMask & 0x0200) != 0) { RegionMisc.Unpack(reader); } }
private (int, int) PickRoadWaypoint(int pointX, int pointZ, TerrainInfo info) { // first get a point out of our list var newWaypoint = RoadPointList[RoadPointList.Count - 1]; pointX = newWaypoint.PointX; pointZ = newWaypoint.PointZ; if (newWaypoint.RoadSpreadDirectionAtCreationTime == RoadSpreadDirection.kUp || newWaypoint.RoadSpreadDirectionAtCreationTime == RoadSpreadDirection.kDown) { SpreadDirection = (RoadSpreadDirection)Random.Range(2, 4); if (SpreadDirection == RoadSpreadDirection.kLeft) { pointZ -= SplineSize; } else { pointZ += SplineSize; } DirectionChanged = true; } else { SpreadDirection = (RoadSpreadDirection)Random.Range(0, 2); if (SpreadDirection == RoadSpreadDirection.kUp) { pointX += SplineSize; } else { pointX -= SplineSize; } DirectionChanged = true; } return(pointX, pointZ); }
public NoiseParameterEditor(TerrainInfo info) { SerializedNoiseParameters = new List <NoiseParameters>(); CurrentSelectedIndexNoise = EditorPrefs.GetInt("ParameterPresetNoiseIdx"); TryGeneratingSavedNoiseParameters(info, true); }
public static void ExportTerrain() { CleanSOCache(); CleanGidTilesetCache(); System.DateTime beforDT = System.DateTime.Now; if (Directory.Exists(Application.dataPath + "/TileMap/MapInfo/")) { Directory.Delete(Application.dataPath + "/TileMap/MapInfo/", true); } Directory.CreateDirectory(Application.dataPath + "/TileMap/MapInfo/"); //加载Map TiledMap map = LoadMap(m_MapName); var globalGridSizeX = map.width; var globalGridSizeZ = map.height; //计算map分块大小,创建分块map配置 int spiltMap_w = Mathf.CeilToInt(globalGridSizeX * 1f / m_MapSpiltSize_x); int spiltMap_h = Mathf.CeilToInt(globalGridSizeZ * 1f / m_MapSpiltSize_y); //创建地形obj配置 TerrainInfo terrainInfo = GetStriptableObject <TerrainInfo>("Assets/TileMap/TerrainInfo.asset"); terrainInfo.MapSize_W = globalGridSizeX; terrainInfo.MapSize_H = globalGridSizeZ; terrainInfo.SpiltMapSize_W = spiltMap_w; terrainInfo.SpiltMapSize_H = spiltMap_h; terrainInfo.SpiltMap_X = m_MapSpiltSize_x; terrainInfo.SpiltMap_Y = m_MapSpiltSize_y; terrainInfo.MapInfoList = new bool[m_MapSpiltSize_x * m_MapSpiltSize_y]; //地形分块数据 Dictionary <string, TiledLayer> _layerDic = new Dictionary <string, TiledLayer>(); for (int i = 0; i < map.layers.Length; i++) { var layer = map.layers[i]; string layerName = layer.name; _layerDic.Add(layerName, layer); } if (_layerDic.ContainsKey(TerrainLayerName)) { var terrainTiles = _layerDic[TerrainLayerName].GetTiles(); int globalSize = terrainTiles.Length; for (int j = 0; j < terrainTiles.Length; j++) { EditorUtility.DisplayProgressBar("ExportTerrain", j + "/" + (globalSize), j / (float)globalSize); var _terrTile = terrainTiles[j]; // int _terrRY = GetRotY(_terrTile); int terrainID = _terrTile.Gid; GetTilesetNameAndIndex(map, _terrTile.Gid, out terrainID); if (terrainID != 0 && !UnSetTerrain.Contains(terrainID)) { int mapIndex_x = _terrTile.X / spiltMap_w; int mapIndex_y = _terrTile.Y / spiltMap_h; terrainInfo.MapInfoList[mapIndex_x * m_MapSpiltSize_x + mapIndex_y] = true; var _mapinfo = GetStriptableObject <TileMapInfo>(string.Format("Assets/TileMap/MapInfo/MapInfo_{0}_{1}.asset", mapIndex_x, mapIndex_y)); int _posIndex = _terrTile.Y * globalGridSizeX + _terrTile.X; int terrainIndex = terrainID == SeaID ? 0 : terrainID; // objInfo.terrainRotY = _terrRY; _mapinfo.posIndex.Add(_posIndex); _mapinfo.terrainIndexList.Add(terrainIndex); // UnityEditor.EditorUtility.SetDirty(_mapinfo); } } } System.DateTime afterDT = System.DateTime.Now; System.TimeSpan ts = afterDT.Subtract(beforDT); Debug.Log(ts.TotalSeconds); EditorUtility.ClearProgressBar(); CleanSOCache(); CleanGidTilesetCache(); // UnityEditor.EditorUtility.SetDirty(terrainInfo); UnityEditor.AssetDatabase.SaveAssets(); }
// Use this for initialization void Start() { if (!isServer) return; if (terrainParent != null) terrainParentInfo = terrainParent.GetComponent<TerrainInfo>(); manager = GameObject.Find("NetworkManager").GetComponent<MyNetworkManager>(); StartCoroutine(GetCollectableAreas()); }
public static void ExportObj() { CleanSOCache(); CleanGidTilesetCache(); System.DateTime beforDT = System.DateTime.Now; if (Directory.Exists(Application.dataPath + "/TileMap/ItemInfo/")) { Directory.Delete(Application.dataPath + "/TileMap/ItemInfo/", true); } Directory.CreateDirectory(Application.dataPath + "/TileMap/ItemInfo/"); //加载Map TiledMap map = LoadMap(m_MapName); var globalGridSizeX = map.width; var globalGridSizeZ = map.height; //计算map分块大小 int spiltMap_w = Mathf.CeilToInt(globalGridSizeX * 1f / m_MapSpiltSize_x); int spiltMap_h = Mathf.CeilToInt(globalGridSizeZ * 1f / m_MapSpiltSize_y); //创建地形obj配置 TerrainInfo terrainInfo = GetStriptableObject <TerrainInfo>("Assets/TileMap/TerrainInfo.asset"); terrainInfo.MapSize_W = globalGridSizeX; terrainInfo.MapSize_H = globalGridSizeZ; terrainInfo.SpiltMapSize_W = spiltMap_w; terrainInfo.SpiltMapSize_H = spiltMap_h; terrainInfo.SpiltMap_X = m_MapSpiltSize_x; terrainInfo.SpiltMap_Y = m_MapSpiltSize_y; terrainInfo.ItemInfoList = new bool[m_MapSpiltSize_x * m_MapSpiltSize_y]; //物件分块数据 Dictionary <string, TiledLayer> _layerDic = new Dictionary <string, TiledLayer>(); for (int i = 0; i < map.layers.Length; i++) { var layer = map.layers[i]; string layerName = layer.name; _layerDic.Add(layerName, layer); } var unRemoveTiles = _layerDic.ContainsKey(UnRemovableItemLayerName) ? _layerDic[UnRemovableItemLayerName].GetTiles() : null; var removableTiles = _layerDic.ContainsKey(RemovableItemLayerName) ? _layerDic[RemovableItemLayerName].GetTiles() : null; int globalSize = globalGridSizeX * globalGridSizeZ; for (int i = 0; i < globalSize; i++) { // EditorUtility.DisplayProgressBar("ExportObj", i+"/"+(globalSize), i / (float)globalSize); TiledLayerTile _unRemoveTile = new TiledLayerTile(); int _unRemoveID = 0; // int _unRemoveRY = 0; string _unRemoveName = ""; if (unRemoveTiles != null) { _unRemoveTile = unRemoveTiles[i]; // _unRemoveRY = GetRotY(_unRemoveTile); _unRemoveID = _unRemoveTile.Gid; _unRemoveName = GetTilesetNameAndIndex(map, _unRemoveTile.Gid, out _unRemoveID); } TiledLayerTile _removableTile = new TiledLayerTile(); int _removableID = 0; // int _removableRY = 0; string _removableName = ""; if (removableTiles != null) { _removableTile = removableTiles[i]; // _removableRY = GetRotY(_removableTile); _removableID = _removableTile.Gid; _removableName = GetTilesetNameAndIndex(map, _removableTile.Gid, out _removableID); } if (_unRemoveID == 1 || _removableID == 1) { int X = _unRemoveID != 0 ? _unRemoveTile.X : _removableTile.X; int Y = _unRemoveID != 0 ? _unRemoveTile.Y : _removableTile.Y; int itemIndex_x = X / spiltMap_w; int itemIndex_y = Y / spiltMap_h; terrainInfo.ItemInfoList[itemIndex_x * m_MapSpiltSize_x + itemIndex_y] = true; var _mapinfo = GetStriptableObject <ItemMapInfo>(string.Format("Assets/TileMap/ItemInfo/ItemInfo_{0}_{1}.asset", itemIndex_x, itemIndex_y)); int _posIndex = Y * globalGridSizeX + X; string itemName = _unRemoveID == 1 ? _unRemoveName : _removableName; // objInfo.itemRotY = _unRemoveID == 1 ? _unRemoveRY : _removableRY; _mapinfo.posIndex.Add(_posIndex); _mapinfo.itemNameList.Add(itemName); // UnityEditor.EditorUtility.SetDirty(_mapinfo); } } System.DateTime afterDT = System.DateTime.Now; System.TimeSpan ts = afterDT.Subtract(beforDT); Debug.Log(ts.TotalSeconds); EditorUtility.ClearProgressBar(); // UnityEditor.EditorUtility.SetDirty(terrainInfo); CleanSOCache(); CleanGidTilesetCache(); UnityEditor.AssetDatabase.SaveAssets(); }
public static void ExportTerrainAlpha() { CleanSOCache(); CleanGidTilesetCache(); System.DateTime beforDT = System.DateTime.Now; if (Directory.Exists(Application.dataPath + "/TileMap/TerrainAlpha/")) { Directory.Delete(Application.dataPath + "/TileMap/TerrainAlpha/", true); } Directory.CreateDirectory(Application.dataPath + "/TileMap/TerrainAlpha/"); //加载Map TiledMap map = LoadMap(m_MapName); var globalGridSizeX = map.width; var globalGridSizeZ = map.height; //计算map分块大小 int spiltMap_w = Mathf.CeilToInt(globalGridSizeX * 1f / m_MapSpiltSize_x); int spiltMap_h = Mathf.CeilToInt(globalGridSizeZ * 1f / m_MapSpiltSize_y); //创建地形obj配置 TerrainInfo terrainInfo = GetStriptableObject <TerrainInfo>("Assets/TileMap/TerrainInfo.asset"); terrainInfo.MapSize_W = globalGridSizeX; terrainInfo.MapSize_H = globalGridSizeZ; terrainInfo.SpiltMapSize_W = spiltMap_w; terrainInfo.SpiltMapSize_H = spiltMap_h; terrainInfo.SpiltMap_X = m_MapSpiltSize_x; terrainInfo.SpiltMap_Y = m_MapSpiltSize_y; terrainInfo.TerrainAlphaList = new bool[m_MapSpiltSize_x * m_MapSpiltSize_y]; //物件分块数据 Dictionary <string, TiledLayer> _layerDic = new Dictionary <string, TiledLayer>(); for (int i = 0; i < map.layers.Length; i++) { var layer = map.layers[i]; string layerName = layer.name; _layerDic.Add(layerName, layer); } var terrainAlphaTiles1 = _layerDic.ContainsKey(TerrainAlphaLayer1Name) ? _layerDic[TerrainAlphaLayer1Name].GetTiles() : null; var terrainAlphaTiles2 = _layerDic.ContainsKey(TerrainAlphaLayer2Name) ? _layerDic[TerrainAlphaLayer2Name].GetTiles() : null; var terrainAlphaTiles3 = _layerDic.ContainsKey(TerrainAlphaLayer3Name) ? _layerDic[TerrainAlphaLayer3Name].GetTiles() : null; int globalSize = globalGridSizeX * globalGridSizeZ; for (int i = 0; i < globalSize; i++) { // EditorUtility.DisplayProgressBar("ExportTerrainAlpha", i+"/"+(globalSize), i / (float)globalSize); TiledLayerTile _terrainAlphaTile = new TiledLayerTile(); int _terrainAlphaIndex = 0; // int _terainAlphaRY = 0; string _terrainAlphaName = ""; uint _level = 0; if (terrainAlphaTiles3 != null) { _terrainAlphaTile = terrainAlphaTiles3[i]; int index; string itemName = GetTilesetNameAndIndex(map, _terrainAlphaTile.Gid, out index); if (index == 1) { _terrainAlphaIndex = index; _terrainAlphaName = itemName; _level = 3; } } if (terrainAlphaTiles2 != null) { _terrainAlphaTile = terrainAlphaTiles2[i]; int index; string itemName = GetTilesetNameAndIndex(map, _terrainAlphaTile.Gid, out index); if (index == 1) { _terrainAlphaIndex = index; _terrainAlphaName = itemName; _level = 2; } } if (terrainAlphaTiles1 != null) { _terrainAlphaTile = terrainAlphaTiles1[i]; int index; string itemName = GetTilesetNameAndIndex(map, _terrainAlphaTile.Gid, out index); if (index == 1) { _terrainAlphaIndex = index; _terrainAlphaName = itemName; _level = 1; } } if (_terrainAlphaIndex == 1) { int X = _terrainAlphaTile.X; int Y = _terrainAlphaTile.Y; int itemIndex_x = X / spiltMap_w; int itemIndex_y = Y / spiltMap_h; terrainInfo.TerrainAlphaList[itemIndex_x * m_MapSpiltSize_x + itemIndex_y] = true; var _mapinfo = GetStriptableObject <AlphaTexInfo>(string.Format("Assets/TileMap/TerrainAlpha/TerrainAlpha_{0}_{1}.asset", itemIndex_x, itemIndex_y)); int _posIndex = Y * globalGridSizeX + X; AlphaTexInfo_S alphaTexInfo = new AlphaTexInfo_S(); alphaTexInfo.objName = _terrainAlphaName; alphaTexInfo.level = _level; _mapinfo.posIndex.Add(_posIndex); _mapinfo.terrainAlphaList.Add(alphaTexInfo); // UnityEditor.EditorUtility.SetDirty(_mapinfo); } } System.DateTime afterDT = System.DateTime.Now; System.TimeSpan ts = afterDT.Subtract(beforDT); Debug.Log(ts.TotalSeconds); EditorUtility.ClearProgressBar(); CleanSOCache(); CleanGidTilesetCache(); UnityEditor.AssetDatabase.SaveAssets(); }
public Terrain(TerrainInfo ti, Point coords) : this() { Ti = ti; Coords = coords; }
void Start() { Initialize(); TerrainInfo.Use(KeyTerm.TREE, GetComponent <Tile>()); }
protected virtual void UpdateTerrain( StarMapTerrain o, TerrainInfo oi, StarMapBase.SyncContext context) { }
//These functions are for taking a PraxisMapper DB and making a workable mobile version. Much less accurate, requires 0 data connectivity. //No longer a high priority but I do want to keep this code around. public static void CreateStandaloneDB(long relationID = 0, GeoArea bounds = null, bool saveToDB = false, bool saveToFolder = true) { //TODO: could rename TerrainInfo to TrailInfo, terrainDataSmall to trailData string name = ""; if (bounds != null) { name = Math.Truncate(bounds.SouthLatitude) + "_" + Math.Truncate(bounds.WestLongitude) + "_" + Math.Truncate(bounds.NorthLatitude) + "_" + Math.Truncate(bounds.EastLongitude) + ".sqlite"; } if (relationID > 0) { name = relationID.ToString() + ".sqlite"; } if (File.Exists(name)) { File.Delete(name); } var mainDb = new PraxisContext(); var sqliteDb = new StandaloneContext(relationID.ToString()); sqliteDb.ChangeTracker.AutoDetectChangesEnabled = false; sqliteDb.Database.EnsureCreated(); Log.WriteLog("Standalone DB created for relation " + relationID + " at " + DateTime.Now); GeoArea buffered; if (relationID > 0) { var fullArea = mainDb.Places.FirstOrDefault(m => m.SourceItemID == relationID && m.SourceItemType == 3); if (fullArea == null) { return; } buffered = Converters.GeometryToGeoArea(fullArea.ElementGeometry); //This should also be able to take a bounding box in addition in the future. } else { buffered = bounds; } //TODO: set a flag to allow this to pull straight from a PBF file? List <DbTables.Place> allPlaces = new List <DbTables.Place>(); var intersectCheck = Converters.GeoAreaToPolygon(buffered); bool pullFromPbf = false; //Set via arg at startup? or setting file? if (!pullFromPbf) { allPlaces = PraxisCore.Place.GetPlaces(buffered); } else { //need a file to read from. //optionally a bounding box on that file. //Starting to think i might want to track some generic parameters I refer to later. like -box|s|w|n|e or -point|lat|long or -singleFile|here.osm.pbf //allPlaces = PbfFileParser.ProcessSkipDatabase(); } Log.WriteLog("Loaded all intersecting geometry at " + DateTime.Now); string minCode = new OpenLocationCode(buffered.SouthLatitude, buffered.WestLongitude).CodeDigits; string maxCode = new OpenLocationCode(buffered.NorthLatitude, buffered.EastLongitude).CodeDigits; int removableLetters = 0; for (int i = 0; i < 10; i++) { if (minCode[i] == maxCode[i]) { removableLetters++; } else { i += 10; } } string commonStart = minCode.Substring(0, removableLetters); var wikiList = allPlaces.Where(a => a.Tags.Any(t => t.Key == "wikipedia") && TagParser.GetPlaceName(a.Tags) != "").Select(a => TagParser.GetPlaceName(a.Tags)).Distinct().ToList(); //Leaving this nearly wide open, since it's not the main driver of DB size. var basePlaces = allPlaces.Where(a => TagParser.GetPlaceName(a.Tags) != "" || a.GameElementName != "unmatched").ToList(); //.Where(a => a.name != "").ToList();// && (a.IsGameElement || wikiList.Contains(a.name))).ToList(); var distinctNames = basePlaces.Select(p => TagParser.GetPlaceName(p.Tags)).Distinct().ToList(); //This distinct might be causing things in multiple pieces to only detect one of them, not all of them? var placeInfo = PraxisCore.Standalone.Standalone.GetPlaceInfo(basePlaces); //Remove trails later. //SHORTCUT: for roads that are a straight-enough line (under 1 Cell10 in width or height) //just treat them as being 1 Cell10 in that axis, and skip tracking them by each Cell10 they cover. HashSet <long> skipEntries = new HashSet <long>(); foreach (var pi in placeInfo.Where(p => p.areaType == "road" || p.areaType == "trail")) { //If a road is nearly a straight line, treat it as though it was 1 cell10 wide, and don't index its coverage per-cell later. if (pi.height <= ConstantValues.resolutionCell10 && pi.width >= ConstantValues.resolutionCell10) { pi.height = ConstantValues.resolutionCell10; skipEntries.Add(pi.PlaceId); } else if (pi.height >= ConstantValues.resolutionCell10 && pi.width <= ConstantValues.resolutionCell10) { pi.width = ConstantValues.resolutionCell10; skipEntries.Add(pi.PlaceId); } } sqliteDb.PlaceInfo2s.AddRange(placeInfo); sqliteDb.SaveChanges(); Log.WriteLog("Processed geometry at " + DateTime.Now); var placeDictionary = placeInfo.ToDictionary(k => k.PlaceId, v => v); //to save time, i need to index which areas are in which Cell6. //So i know which entries I can skip when running. var indexCell6 = PraxisCore.Standalone.Standalone.IndexAreasPerCell6(buffered, basePlaces); var indexes = indexCell6.SelectMany(i => i.Value.Select(v => new PlaceIndex() { PlusCode = i.Key, placeInfoId = placeDictionary[v.SourceItemID].id })).ToList(); sqliteDb.PlaceIndexs.AddRange(indexes); sqliteDb.SaveChanges(); Log.WriteLog("Processed Cell6 index table at " + DateTime.Now); //trails need processed the old way, per Cell10, when they're not simply a straight-line. //Roads too. var tdSmalls = new Dictionary <string, TerrainDataSmall>(); //Possible issue: a trail and a road with the same name would only show up as whichever one got in the DB first. var toRemove = new List <PlaceInfo2>(); foreach (var trail in basePlaces.Where(p => (p.GameElementName == "trail" || p.GameElementName == "road"))) //TODO: add rivers here? { if (skipEntries.Contains(trail.SourceItemID)) { continue; //Don't per-cell index this one, we shifted it's envelope to handle it instead. } if (TagParser.GetPlaceName(trail.Tags) == "") { continue; //So sorry, but there's too damn many roads without names inflating DB size without being useful as-is. } var p = placeDictionary[trail.SourceItemID]; toRemove.Add(p); GeoArea thisPath = Converters.GeometryToGeoArea(trail.ElementGeometry); List <DbTables.Place> oneEntry = new List <DbTables.Place>(); oneEntry.Add(trail); var overlapped = AreaTypeInfo.SearchArea(ref thisPath, ref oneEntry); if (overlapped.Count() > 0) { tdSmalls.TryAdd(TagParser.GetPlaceName(trail.Tags), new TerrainDataSmall() { Name = TagParser.GetPlaceName(trail.Tags), areaType = trail.GameElementName }); } foreach (var o in overlapped) { var ti = new TerrainInfo(); ti.PlusCode = o.Key.Substring(removableLetters, 10 - removableLetters); ti.TerrainDataSmall = new List <TerrainDataSmall>(); ti.TerrainDataSmall.Add(tdSmalls[o.Value.Name]); sqliteDb.TerrainInfo.Add(ti); } sqliteDb.SaveChanges(); } foreach (var r in toRemove.Distinct()) { sqliteDb.PlaceInfo2s.Remove(r); } sqliteDb.SaveChanges(); Log.WriteLog("Trails processed at " + DateTime.Now); //make scavenger hunts var sh = PraxisCore.Standalone.Standalone.GetScavengerHunts(allPlaces); sqliteDb.ScavengerHunts.AddRange(sh); sqliteDb.SaveChanges(); Log.WriteLog("Auto-created scavenger hunt entries at " + DateTime.Now); var swCorner = new OpenLocationCode(intersectCheck.EnvelopeInternal.MinY, intersectCheck.EnvelopeInternal.MinX); var neCorner = new OpenLocationCode(intersectCheck.EnvelopeInternal.MaxY, intersectCheck.EnvelopeInternal.MaxX); //insert default entries for a new player. sqliteDb.PlayerStats.Add(new PlayerStats() { timePlayed = 0, distanceWalked = 0, score = 0 }); sqliteDb.Bounds.Add(new Bounds() { EastBound = neCorner.Decode().EastLongitude, NorthBound = neCorner.Decode().NorthLatitude, SouthBound = swCorner.Decode().SouthLatitude, WestBound = swCorner.Decode().WestLongitude, commonCodeLetters = commonStart, BestIdleCompletionTime = 0, LastPlayedOn = 0, StartedCurrentIdleRun = 0 }); sqliteDb.IdleStats.Add(new IdleStats() { emptySpacePerSecond = 0, emptySpaceTotal = 0, graveyardSpacePerSecond = 0, graveyardSpaceTotal = 0, natureReserveSpacePerSecond = 0, natureReserveSpaceTotal = 0, parkSpacePerSecond = 0, parkSpaceTotal = 0, touristSpacePerSecond = 0, touristSpaceTotal = 0, trailSpacePerSecond = 0, trailSpaceTotal = 0 }); sqliteDb.SaveChanges(); //now we have the list of places we need to be concerned with. System.IO.Directory.CreateDirectory(relationID + "Tiles"); PraxisCore.Standalone.Standalone.DrawMapTilesStandalone(relationID, buffered, allPlaces, saveToFolder); sqliteDb.SaveChanges(); Log.WriteLog("Maptiles drawn at " + DateTime.Now); //Copy the files as necessary to their correct location. //if (saveToFolder) //Directory.Move(relationID + "Tiles", config["Solar2dExportFolder"] + "Tiles"); //File.Copy(relationID + ".sqlite", config["Solar2dExportFolder"] + "database.sqlite"); Log.WriteLog("Standalone gameplay DB done."); }
private float GetVisualWorldHeight(TerrainInfo terInfo, float x, float z) { int ix = terInfo.PosToVertexX(x); int iz = terInfo.PosToVertexZ(z); if (ix >= terInfo.Width - 1) ix = (int)terInfo.Width - 2; if (iz >= terInfo.Height - 1) iz = (int)terInfo.Height - 2; Vector3 p11 = new Vector3(terInfo.VertexToPosX(ix), terInfo.VertexToPosZ(iz), terInfo.At((uint)ix, (uint)iz)); Vector3 p21 = new Vector3(terInfo.VertexToPosX(ix + 1), terInfo.VertexToPosZ(iz), terInfo.At((uint)ix + 1, (uint)iz)); Vector3 p22 = new Vector3(terInfo.VertexToPosX(ix + 1), terInfo.VertexToPosZ(iz + 1), terInfo.At((uint)ix + 1, (uint)iz + 1)); Vector3 p12 = new Vector3(terInfo.VertexToPosX(ix), terInfo.VertexToPosZ(iz + 1), terInfo.At((uint)ix, (uint)iz + 1)); float t, s, ret; if (x - p11.x < p12.y - z) { t = p21.z - p11.z; s = p12.z - p11.z; ret = p11.z + (x - p11.x) / terInfo.Scaling.x * t + (z - p11.y) / terInfo.Scaling.z * s; } else { t = p22.z - p12.z; s = p22.z - p21.z; ret = p22.z + (x - p22.x) / terInfo.Scaling.x * t + (z - p22.y) / terInfo.Scaling.z * s; } ret = ret * terInfo.Scaling.y + terInfo.Offset.y; //float ret2 = terInfo.GetHeightAt(x, z); if (float.IsNaN(ret)) ret = 0; return ret; }
void GenerateLevelFromString(string levelString, bool edit) { Debug.Log("Generating level from levelString: " + levelString); LevelDataRead levelData = new LevelDataRead(levelString); //TODO: Generate level from levelData // 1) Read version string version = levelData.ReadString(); Debug.Log("Version is: " + version); // 2) Read how many terrains there are int numTerrains = levelData.ReadInt(); for (int t = 0; t < numTerrains; t++) { // Read type TerrainBlueprintType type = (TerrainBlueprintType)levelData.ReadInt(); // Read style TerrainGroundStyle style = (TerrainGroundStyle)levelData.ReadInt(); // Read segment length float segmentLength = levelData.ReadFloat(); TerrainInfo terrainInfo = new TerrainInfo(type, style, segmentLength); TerrainObjectMaker terrainObjectMaker = new TerrainObjectMaker(terrainInfo); for (int i = 0; i < terrainObjectMaker.GetNodeAmount(); i++) { terrainObjectMaker.AddNode((Vector3)levelData.ReadVector2()); } terrainObjectMaker.SetIsEditable(edit); terrainObjectMaker.CreateTerrain(); } // 3) Read how many rollers there are int numRollers = levelData.ReadInt(); for (int t = 0; t < numRollers; t++) { // Read type TerrainBlueprintType type = (TerrainBlueprintType)levelData.ReadInt(); // Read style TerrainRollerStyle style = (TerrainRollerStyle)levelData.ReadInt(); float spacing = levelData.ReadFloat(); bool isFixed = levelData.ReadBool(); float speed = levelData.ReadFloat(); TerrainInfo terrainInfo = new TerrainInfo(type, style, spacing, isFixed, speed); TerrainObjectMaker terrainObjectMaker = new TerrainObjectMaker(terrainInfo); for (int i = 0; i < terrainObjectMaker.GetNodeAmount(); i++) { terrainObjectMaker.AddNode((Vector3)levelData.ReadVector2()); } terrainObjectMaker.SetIsEditable(edit); terrainObjectMaker.CreateTerrain(); } }
private void CreateTerrain() { mTMgr = new MET.TerrainManager(OgreEngine.mMgr, "MET"); mTMgr.SetLodErrorMargin(2, OgreEngine.mWin.Height); mTMgr.SetUseLodMorphing(true, 0.2f, "morphFactor"); mTInfo = new MET.TerrainInfo(); Mogre.Image image = new Mogre.Image(); image.Load("heightmap.png", ResourceGroupManager.DEFAULT_RESOURCE_GROUP_NAME); MET.TerrainInfo.LoadHeightmapFromImage(mTInfo, image); //mTInfo.Extents = new Mogre.AxisAlignedBox(0, 0, 0, land.SizeX + stepWidth, land.SizeZ, land.SizeY + stepHeight); mTInfo.Extents = new Mogre.AxisAlignedBox(Vector3.ZERO, Size); //lightmap Mogre.Image lmImage = new Mogre.Image(); MET.TerrainInfo.CreateTerraingLightmap(mTInfo, lmImage, Constants.Land.LightmapSize, Constants.Land.LightmapSize, new Vector3(-1, -1, -1), new ColourValue(1, 1, 1), new ColourValue(0.2f, 0.2f, 0.2f), true); //lmImage.Save("lightmapa" + land.Id + ".png"); TexturePtr lightmapTex = TextureManager.Singleton.CreateManual( "ETLightmap", ResourceGroupManager.DEFAULT_RESOURCE_GROUP_NAME, Mogre.TextureType.TEX_TYPE_2D, Constants.Land.LightmapSize, Constants.Land.LightmapSize, 1, Mogre.PixelFormat.PF_BYTE_RGB); TexturePtr tex = TextureManager.Singleton.GetByName("ETLightmap"); tex.GetBuffer(0, 0).BlitFromMemory(lmImage.GetPixelBox(0, 0)); mTMgr.CreateTerrain(mTInfo); mTInfo.Dispose(); mTInfo = mTMgr.TerrainInfo; image = new Image(); image.Load("textureMap0.png", ResourceGroupManager.DEFAULT_RESOURCE_GROUP_NAME); TextureSize = image.Width; mSMgr = new MET.SplattingManager("ETSplatting", ResourceGroupManager.DEFAULT_RESOURCE_GROUP_NAME, image.Width, image.Width, 3); mSMgr.NumTextures = 6; mSMgr.LoadMapFromImage(0, image); image = new Image(); image.Load("textureMap1.png", ResourceGroupManager.DEFAULT_RESOURCE_GROUP_NAME); mSMgr.LoadMapFromImage(1, image); mTMgr.Material = MaterialManager.Singleton.GetByName("ETTerrainMaterial"); // lightmapa Pass pass = mTMgr.Material.GetTechnique(0).CreatePass(); pass.LightingEnabled = false; pass.SetSceneBlending(SceneBlendType.SBT_MODULATE); pass.SetVertexProgram("ET/Programs/VSLodMorph2"); pass.SetFragmentProgram("ET/Programs/PSLighting"); pass.CreateTextureUnitState("ETLightmap"); pass = mTMgr.Material.GetTechnique(1).CreatePass(); pass.LightingEnabled = false; pass.SetSceneBlending(SceneBlendType.SBT_MODULATE); pass.SetVertexProgram("ET/Programs/VSLodMorph2"); pass.SetFragmentProgram("ET/Programs/PSLighting"); pass.CreateTextureUnitState("ETLightmap"); //base texture for non shader graphics lmImage = new Mogre.Image(); //TODO: replace by real bic texture lmImage.Load("baseTexture.jpg", ResourceGroupManager.DEFAULT_RESOURCE_GROUP_NAME); //lmImage.Save("lightmapa" + land.Id + ".png"); lightmapTex = TextureManager.Singleton.CreateManual( "ETBasemap", ResourceGroupManager.DEFAULT_RESOURCE_GROUP_NAME, Mogre.TextureType.TEX_TYPE_2D, Constants.Land.LightmapSize, Constants.Land.LightmapSize, 1, Mogre.PixelFormat.PF_BYTE_RGB); tex = TextureManager.Singleton.GetByName("ETBasemap"); tex.GetBuffer(0, 0).BlitFromMemory(lmImage.GetPixelBox(0, 0)); Technique tech = mTMgr.Material.CreateTechnique(); pass = tech.CreatePass(); pass.CreateTextureUnitState("ETBasemap"); }
public void makeMap() { terrain_manager = terrain_manager_game_object.GetComponent <TerrainManager>(); print(terrain_manager); terrainInfo = terrain_manager.myInfo; print(terrainInfo); float[, ] traversability = terrainInfo.traversability; terrainInfo = terrain_manager.myInfo; float tileXSize = (terrainInfo.x_high - terrainInfo.x_low) / terrainInfo.x_N; float tileZSize = (terrainInfo.z_high - terrainInfo.z_low) / terrainInfo.z_N; float factor = 4.5f; float[, ] newTerrain = new float[(int)Mathf.Floor(tileXSize * tileXSize / factor), (int)Mathf.Floor(tileZSize * tileZSize / factor)]; stepx = (terrainInfo.x_high - terrainInfo.x_low) / newTerrain.GetLength(0); stepz = (terrainInfo.z_high - terrainInfo.z_low) / newTerrain.GetLength(1); for (int i = 0; i < newTerrain.GetLength(0); i++) { float posx = terrainInfo.x_low + stepx / 2 + stepx * i; for (int j = 0; j < newTerrain.GetLength(1); j++) { float posz = terrainInfo.z_low + stepz / 2 + stepz * j; newTerrain[i, j] = terrainInfo.traversability[terrainInfo.get_i_index(posx), terrainInfo.get_j_index(posz)]; } } int xLen = newTerrain.GetLength(0); int zLen = newTerrain.GetLength(1); nodeIdMatrix = new int[xLen, zLen]; mapGraph = new Graph(); int nodeId; float wallMargin = 2.0f; for (int i = 0; i < xLen; i++) { float posx = terrainInfo.x_low + stepx / 2 + stepx * i; for (int j = 0; j < zLen; j++) { float posz = terrainInfo.z_low + stepz / 2 + stepz * j; if (newTerrain[i, j] == 0.0f && 0.0f == checkTrav(posx, posz + wallMargin) && 0.0f == checkTrav(posx, posz - wallMargin) && 0.0f == checkTrav(posx + wallMargin, posz) && 0.0f == checkTrav(posx - wallMargin, posz)) { /*GameObject cube = GameObject.CreatePrimitive (PrimitiveType.Cube); * Collider c = cube.GetComponent<Collider> (); * c.enabled = false; * cube.transform.localScale = new Vector3 (0.5f, 0.5f, 0.5f); * cube.transform.position = new Vector3 (posx, 0, posz);*/ nodeIdMatrix[i, j] = mapGraph.addNode(new Node(posx, posz)); mapGraph.getNode(nodeIdMatrix[i, j]).setIndex(i, j); } else { nodeIdMatrix[i, j] = -1; } } } float timeDraw = 1; LayerMask mask = LayerMask.GetMask("Wall"); RaycastHit hit; for (int i = 0; i < xLen; i++) { for (int j = 0; j < zLen; j++) { if (nodeIdMatrix[i, j] != -1) { nodeId = nodeIdMatrix[i, j]; if (nodeIdMatrix[i, j + 1] != -1) { Debug.DrawLine(mapGraph.getNode(nodeId).getPosition(), mapGraph.getNode(nodeIdMatrix[i, j + 1]).getPosition(), Color.cyan, timeDraw); mapGraph.addEdge(nodeId, nodeIdMatrix[i, j + 1]); } if (nodeIdMatrix[i, j - 1] != -1) { Debug.DrawLine(mapGraph.getNode(nodeId).getPosition(), mapGraph.getNode(nodeIdMatrix[i, j - 1]).getPosition(), Color.cyan, timeDraw); mapGraph.addEdge(nodeId, nodeIdMatrix[i, j - 1]); } if (nodeIdMatrix[i + 1, j] != -1) { Debug.DrawLine(mapGraph.getNode(nodeId).getPosition(), mapGraph.getNode(nodeIdMatrix[i + 1, j]).getPosition(), Color.cyan, timeDraw); mapGraph.addEdge(nodeId, nodeIdMatrix[i + 1, j]); } if (nodeIdMatrix[i - 1, j] != -1) { Debug.DrawLine(mapGraph.getNode(nodeId).getPosition(), mapGraph.getNode(nodeIdMatrix[i - 1, j]).getPosition(), Color.cyan, timeDraw); mapGraph.addEdge(nodeId, nodeIdMatrix[i - 1, j]); } Vector3 from = mapGraph.getNode(nodeId).getPosition(); /* * if(nodeIdMatrix[i-1,j-1] != -1 && !Physics.Raycast(from , mapGraph.getNode(nodeIdMatrix[i-1,j-1]).getPosition()-from, out hit,Vector3.Distance(mapGraph.getNode(nodeIdMatrix[i-1,j-1]).getPosition(),from) , mask)){ * Debug.DrawLine(from,mapGraph.getNode(nodeIdMatrix[i-1,j-1]).getPosition(),Color.cyan,timeDraw); * mapGraph.addEdge(nodeId,nodeIdMatrix[i-1,j-1]);} * * * if(nodeIdMatrix[i-1,j+1] != -1 && !Physics.Raycast(from , mapGraph.getNode(nodeIdMatrix[i-1,j+1]).getPosition()-from, out hit,Vector3.Distance(mapGraph.getNode(nodeIdMatrix[i-1,j+1]).getPosition(),from) , mask)){ * Debug.DrawLine(from,mapGraph.getNode(nodeIdMatrix[i-1,j+1]).getPosition(),Color.cyan,timeDraw); * mapGraph.addEdge(nodeId,nodeIdMatrix[i-1,j+1]);} * * * if(nodeIdMatrix[i+1,j-1] != -1 && !Physics.Raycast(from , mapGraph.getNode(nodeIdMatrix[i+1,j-1]).getPosition()-from, out hit,Vector3.Distance(mapGraph.getNode(nodeIdMatrix[i+1,j-1]).getPosition(),from) , mask)){ * Debug.DrawLine(from,mapGraph.getNode(nodeIdMatrix[i+1,j-1]).getPosition(),Color.cyan,timeDraw); * mapGraph.addEdge(nodeId,nodeIdMatrix[i+1,j-1]);} * * * if(nodeIdMatrix[i+1,j+1] != -1 && !Physics.Raycast(from , mapGraph.getNode(nodeIdMatrix[i+1,j+1]).getPosition()-from, out hit,Vector3.Distance(mapGraph.getNode(nodeIdMatrix[i+1,j+1]).getPosition(),from) , mask)){ * Debug.DrawLine(from,mapGraph.getNode(nodeIdMatrix[i+1,j+1]).getPosition(),Color.cyan,timeDraw); * mapGraph.addEdge(nodeId,nodeIdMatrix[i+1,j+1]);}*/ } } } }
public override void Init(TerrainInfo terrainInfo, int v_count, int h_count, int itemEx_x, int itemEx_y, float offset_x, float offset_y) { base.Init(terrainInfo, v_count, h_count, itemEx_x, itemEx_y, offset_x, offset_y); }
public void DrawNoiseParameterGUI(TerrainInfo info, Dictionary <string, bool> EditorWidgetFoldouts) { EditorWidgetFoldouts["TerrainGenerationWidget"] = EditorGUILayout.Foldout(EditorWidgetFoldouts["TerrainGenerationWidget"], "TerrainGenerationWidget"); if (EditorWidgetFoldouts["TerrainGenerationWidget"]) { GUILayout.BeginHorizontal(); GUILayout.Label("DebugPlane coloring"); SerializedNoiseParameter.TerrainTextureType = (TextureType)EditorGUI.EnumPopup(EditorGUILayout.GetControlRect(), SerializedNoiseParameter.TerrainTextureType); GUILayout.EndHorizontal(); var noiseScale = EditorGUI.FloatField(EditorGUILayout.GetControlRect(), "Noise Scale", SerializedNoiseParameter.NoiseScale); SerializedNoiseParameter.NoiseScale = noiseScale <= 0 ? 0.0001f : noiseScale; var baseFrequency = EditorGUI.FloatField(EditorGUILayout.GetControlRect(), "Base Frequecny", SerializedNoiseParameter.BaseFrequency); SerializedNoiseParameter.BaseFrequency = baseFrequency <= 0 ? 0.0001f : baseFrequency; var persistance = EditorGUI.FloatField(EditorGUILayout.GetControlRect(), "Persistance", SerializedNoiseParameter.Persistance); SerializedNoiseParameter.Persistance = persistance <= 0 ? 0.0001f : persistance; var lacunarity = EditorGUI.FloatField(EditorGUILayout.GetControlRect(), "Lacunarity", SerializedNoiseParameter.Lacunarity); SerializedNoiseParameter.Lacunarity = lacunarity <= 0 ? 0.0001f : lacunarity; var octaves = EditorGUI.IntField(EditorGUILayout.GetControlRect(), "Number of octaves", SerializedNoiseParameter.NumberOfOctaves); SerializedNoiseParameter.NumberOfOctaves = octaves <= 0 ? 1 : octaves; SerializedNoiseParameter.Seed = EditorGUI.TextField(EditorGUILayout.GetControlRect(), "Seed", SerializedNoiseParameter.Seed); SerializedNoiseParameter.UserOffset = EditorGUI.Vector2Field(EditorGUILayout.GetControlRect(), "User Offset", SerializedNoiseParameter.UserOffset); SerializedNoiseParameter.GlobalNoiseAddition = EditorGUI.FloatField(EditorGUILayout.GetControlRect(), "Global noise add", SerializedNoiseParameter.GlobalNoiseAddition); SerializedNoiseParameter.CustomFunction = (CustomFunctionType)EditorGUI.EnumPopup(EditorGUILayout.GetControlRect(), SerializedNoiseParameter.CustomFunction); if (SerializedNoiseParameter.CustomFunction == CustomFunctionType.kCustom) { var customExponent = EditorGUI.FloatField(EditorGUILayout.GetControlRect(), "Custom Exponent", SerializedNoiseParameter.CustomExponent); SerializedNoiseParameter.CustomExponent = customExponent <= 0 ? 0.0001f : customExponent; } GUILayout.BeginHorizontal(); GUILayout.Label("Pick a generation type"); info.GenerationType = (GenerationType)EditorGUI.EnumPopup(EditorGUILayout.GetControlRect(), info.GenerationType); GUILayout.EndHorizontal(); if (GUI.Button(EditorGUILayout.GetControlRect(), "Paint the terrain!")) { if (info.GenerationType != GenerationType.kSingleRun) { Debug.LogWarningFormat("WARNING: Parameter _GenerationType is {0}, needs to be kSingleRun (can't paint terrain in runtime), changing to single run.", info.GenerationType.ToString()); info.GenerationType = GenerationType.kSingleRun; } AssignSplatMap.DoSplat(info); } GUILayout.Label("Saved noise presets"); GUILayout.BeginHorizontal(GUILayout.Width(250)); var lastIndex = CurrentSelectedIndexNoise; CurrentSelectedIndexNoise = EditorGUILayout.Popup(CurrentSelectedIndexNoise, AllNoiseParameterNames, GUILayout.Width(250)); DeleteFailsafe = lastIndex != CurrentSelectedIndexNoise ? 0 : DeleteFailsafe; if (GUILayout.Button(string.Format("Delete selected preset ({0})", DeleteFailsafe), GUILayout.MaxWidth(200))) { if (DeleteFailsafe == 2) { DeleteFailsafe = 0; SerializationManager.DeleteNoiseParameter(AllNoiseParameterNames[CurrentSelectedIndexNoise]); SerializedNoiseParameters.RemoveAt(CurrentSelectedIndexNoise); TryGeneratingSavedNoiseParameters(info, false); } else { DeleteFailsafe++; } } GUILayout.EndHorizontal(); if (GUI.Button(EditorGUILayout.GetControlRect(), "Load preset")) { TryGeneratingSavedNoiseParameters(info, true); } EditorGUI.LabelField(EditorGUILayout.GetControlRect(), "Terrain parameter serializer, saves the current terrain preset configuration."); NoisePresetName = EditorGUI.TextField(EditorGUILayout.GetControlRect(), "Terrain preset name: ", NoisePresetName); if (GUI.Button(EditorGUILayout.GetControlRect(), "Save preset")) { SerializedNoiseParameter.NoiseParameterName = NoisePresetName; SerializationManager.SaveNoiseParameters(NoisePresetName, SerializedNoiseParameter); TryGeneratingSavedNoiseParameters(info, false); } } EditorGUILayout.Space(); EditorGUILayout.Space(); SetCorrectNoiseParams(SerializedNoiseParameter, ref info); EditorPrefs.SetInt("ParameterPresetNoiseIdx", CurrentSelectedIndexNoise); }
void Start() { if (!isServer) return; if (terrainParent != null) terrainParentInfo = terrainParent.GetComponent<TerrainInfo>(); //Random.seed = randomSeedValue;//Sets the seed value of the Random class. if (placementState == Placement.Random) RandomPlacement(this.maxNumberOfAssets, this.assets); if (placementState == Placement.Area) AreaPlacement(this.areaRadius, this.maxNumberOfAssets, this.assetID, true); if (placementState == Placement.Fill) FillPlacement(this.heightMin, this.heightMax, this.isBetween, this.maxNumberOfAssets); }