public void FinalizeLoad() { foreach (WorldPosition position in CellPositions) { TerrainCell cell = World.GetCell(position); if (cell == null) { throw new System.Exception("Cell missing at position " + position.Longitude + "," + position.Latitude); } _cells.Add(cell); cell.EncompassingTerritory = this; } foreach (TerrainCell cell in _cells) { foreach (TerrainCell nCell in cell.Neighbors.Values) { if (!_cells.Contains(nCell)) { _borderCells.Add(cell); break; } } } }
private void AddCellDataToInfoPanel_UpdateSpan(TerrainCell cell) { InfoText.text += "\n"; InfoText.text += "\n -- Group Update Span Data -- "; InfoText.text += "\n"; if (cell.Group == null) { InfoText.text += "\n\tNo population at location"; return; } int population = cell.Group.Population; if (population <= 0) { InfoText.text += "\n\tNo population at location"; return; } long lastUpdateDate = cell.Group.LastUpdateDate; long nextUpdateDate = cell.Group.NextUpdateDate; InfoText.text += "\nLast Update Date: " + Manager.GetDateString(lastUpdateDate); InfoText.text += "\nNext Update Date: " + Manager.GetDateString(nextUpdateDate); InfoText.text += "\nTime between updates: " + Manager.GetTimeSpanString(nextUpdateDate - lastUpdateDate); }
public TerrainCellData UnrenderCell(int id) { if (cellsData.ContainsKey(id)) { return(cellsData[id]); } if (!cells.ContainsKey(id)) { return(null); } TerrainCell cell = cells[id]; TerrainCellData cellData = cell.GetData(); foreach (Actor actor in ActorsAtCoords(cell.coords)) { UnrenderActor(actor.id); } foreach (Item item in ItemsAtCoords(cell.coords)) { UnrenderItem(item.id); } cells.Remove(id); cell.QueueFree(); cellsData.Add(id, cellData); return(cellData); }
public void FindAdjacentCellsLeftSideTest() { var map = new TerrainMap(new ShortestPath()); map.InitializeBoard(7, 6); // build a wall of mountains for (int i = 0; i < 4; i++) { map[3, i + 1] = new TerrainCell(3, i + 1, 30); } var surroundingCells = map.FindAdjacentCells(0, 3, 2, 1) .OrderBy(u => u.Col) .ThenBy(u => u.Row) .ToList(); Assert.Equal(4, surroundingCells.Count); Assert.Equal(0, surroundingCells[0].Col); Assert.Equal(2, surroundingCells[0].Row); Assert.Equal(0, surroundingCells[1].Col); Assert.Equal(4, surroundingCells[1].Row); Assert.Equal(1, surroundingCells[2].Col); Assert.Equal(2, surroundingCells[2].Row); Assert.Equal(1, surroundingCells[3].Col); Assert.Equal(3, surroundingCells[3].Row); }
/// <summary> /// Converts terrain node data to a 2D TerrainCell array /// </summary> internal static TerrainCell[,] NodeDataTo2DArray(byte[] data) { var cells = new TerrainCell[8, 8]; using (var memStream = new MemoryStream(data)) { var array = new byte[8]; GCHandle pin = GCHandle.Alloc(array, GCHandleType.Pinned); for (var i = 0; i < 64; i++) { // Source: http://geekswithblogs.net/taylorrich/archive/2006/08/21/88665.aspx if (memStream.Read(array, 0, 8) < 8) { throw new Exception("Unexpected end of byte array"); } TerrainCell cell = (TerrainCell)Marshal.PtrToStructure(pin.AddrOfPinnedObject(), typeof(TerrainCell)); int x = i % 8; int z = (i - x) / 8; cells[x, z] = cell; } pin.Free(); } return(cells); }
public void FindShortestPath() { var shortest = new ShortestPath(); var map = new TerrainMap(shortest); map.InitializeBoard(10, 10); //mountains 4,1 - 4,8 for (var i = 1; i < 9; i++) { var cube = HexGridMath.OffsetToCube(4, i); map[4, i] = new TerrainCell(cube.X, cube.Y, cube.Z, 30); } // 1,3 to 8,4 shortest.ComputeShortestPath(map, 1, 3, 8, 4, 0); Assert.Equal(new Offset(2, 3), shortest.WayPoint[0]); Assert.Equal(new Offset(3, 2), shortest.WayPoint[1]); Assert.Equal(new Offset(3, 1), shortest.WayPoint[2]); Assert.Equal(new Offset(3, 0), shortest.WayPoint[3]); Assert.Equal(new Offset(4, 0), shortest.WayPoint[4]); Assert.Equal(new Offset(5, 0), shortest.WayPoint[5]); Assert.Equal(new Offset(6, 1), shortest.WayPoint[6]); Assert.Equal(new Offset(7, 1), shortest.WayPoint[7]); Assert.Equal(new Offset(8, 2), shortest.WayPoint[8]); Assert.Equal(new Offset(8, 3), shortest.WayPoint[9]); Assert.Equal(new Offset(8, 4), shortest.WayPoint[10]); }
void LoadCellsIntoWaterTerrain(TerrainCell[] cells) { Terrain t = waterTerrain; TerrainData td = t.terrainData; float[,] heights = td.GetHeights(0, 0, td.heightmapWidth, td.heightmapHeight); for (int x = 0; x < heights.GetLength(0); x++) { for (int z = 0; z < heights.GetLength(1); z++) { TerrainCell c = cells[x + z * td.heightmapWidth]; if (c.waterDepth < erosionSettings.minWaterDepthDisplay) { heights[x, z] = Mathf.Max(0.01f, c.height - 0.01f); } else { heights[x, z] = c.height + c.waterDepth / 10; } } } td.SetHeights(0, 0, heights); }
public Agent(CellGroup birthGroup, long birthDate, long idOffset) { World = birthGroup.World; BirthCell = birthGroup.Cell; BirthCellPosition = BirthCell.Position; BirthRegionInfo = BirthCell.Region.Info; BirthRegionInfoId = BirthRegionInfo.Id; Language = birthGroup.Culture.Language; LanguageId = Language.Id; BirthDate = birthDate; idOffset += birthGroup.Id; Profiler.BeginSample("new Agent - GenerateUniqueIdentifier"); Id = birthGroup.GenerateUniqueIdentifier(birthDate, 1000L, idOffset); Profiler.EndSample(); Profiler.BeginSample("new Agent - GenerateBio"); GenerateBio(birthGroup); Profiler.EndSample(); }
private void AddCellDataToInfoPanel_FarmlandDistribution(TerrainCell cell) { float cellArea = cell.Area; float farmlandPercentage = cell.FarmlandPercentage; InfoText.text += "\n"; InfoText.text += "\n -- Cell Farmland Distribution Data -- "; InfoText.text += "\n"; InfoText.text += "\nFarmland Percentage: " + farmlandPercentage.ToString("P"); InfoText.text += "\n"; if (cell.Group == null) { InfoText.text += "\n\tNo population at location"; return; } int population = cell.Group.Population; if (population <= 0) { InfoText.text += "\n\tNo population at location"; return; } if (farmlandPercentage > 0) { float farmlandArea = farmlandPercentage * cellArea; InfoText.text += "\nFarmland Area per Pop: " + (farmlandArea / (float)population).ToString("0.000") + " Km^2 / Pop"; } }
public float CalculateDistance(TerrainCell cell, Direction direction) { float distance = TerrainCell.MaxWidth; if ((direction == Direction.Northeast) || (direction == Direction.Northwest) || (direction == Direction.Southeast) || (direction == Direction.Southwest)) { float sqMaxWidth = TerrainCell.MaxWidth * TerrainCell.MaxWidth; float widthSum = (Width + cell.Width) / 2f; float sqCellWidth = widthSum * widthSum; distance = Mathf.Sqrt(sqMaxWidth + sqCellWidth); } else if ((direction == Direction.East) || (direction == Direction.West)) { distance = cell.Width; } float altitudeDiff = Altitude - cell.Altitude; float sqAltDif = altitudeDiff * altitudeDiff; float sqDistance = distance * distance; distance = Mathf.Sqrt(sqAltDif + sqDistance); return(distance); }
private void CalculateMostCenteredCell() { int centerLongitude = 0, centerLatitude = 0; foreach (TerrainCell cell in _cells) { centerLongitude += cell.Longitude; centerLatitude += cell.Latitude; } centerLongitude /= _cells.Count; centerLatitude /= _cells.Count; TerrainCell closestCell = null; int closestDistCenter = int.MaxValue; foreach (TerrainCell cell in _cells) { int distCenter = Mathf.Abs(cell.Longitude - centerLongitude) + Mathf.Abs(cell.Latitude - centerLatitude); if ((closestCell == null) || (distCenter < closestDistCenter)) { closestDistCenter = distCenter; closestCell = cell; } } _mostCenteredCell = closestCell; }
public void Update(long timeSpan) { TerrainCell groupCell = Group.Cell; float randomModifier = groupCell.GetNextLocalRandomFloat(RngOffsets.ACTIVITY_UPDATE + RngOffset); randomModifier = 1f - (randomModifier * 2f); float randomFactor = MaxChangeDelta * randomModifier; float maxTargetValue = 1f; float minTargetValue = 0f; float targetValue = 0; if (randomFactor > 0) { targetValue = Value + (maxTargetValue - Value) * randomFactor; } else { targetValue = Value - (minTargetValue - Value) * randomFactor; } float timeEffect = timeSpan / (timeSpan + TimeEffectConstant); _newValue = (Value * (1 - timeEffect)) + (targetValue * timeEffect); }
private static async System.Threading.Tasks.Task <GlobeRegion> CreateRegionAsync(Globe globe, TerrainCell startCell, IWorldGenerator globeGenerator, ProgressStorageService progressStorageService) { return(await globeGenerator.GenerateRegionAsync(globe, startCell)); }
/// <summary> /// Converts terrain node data to a 2D TerrainCell array /// </summary> public static TerrainCell[,] TerrainNodeData(byte[] data) { var cells = new TerrainCell[8,8]; using (var memStream = new MemoryStream(data)) { var array = new byte[8]; for (var i = 0; i < 64; i++) { // Source: http://geekswithblogs.net/taylorrich/archive/2006/08/21/88665.aspx if (memStream.Read(array, 0, 8) < 8) throw new Exception("Unexpected end of byte array"); GCHandle pin = GCHandle.Alloc(array, GCHandleType.Pinned); TerrainCell cell = (TerrainCell) Marshal.PtrToStructure(pin.AddrOfPinnedObject(), typeof(TerrainCell)); pin.Free(); int row = i % 8; int col = (i - row) / 8; cells[col, row] = cell; } } return cells; }
private void TryGenerateEventMessage() { DiscoveryEventMessage eventMessage = null; World world = Group.World; TerrainCell cell = Group.Cell; if (!world.HasEventMessage(_discovery.UId)) { eventMessage = new DiscoveryEventMessage(_discovery, cell, _discovery.UId, TriggerDate); world.AddEventMessage(eventMessage); } if (cell.EncompassingTerritory != null) { Polity encompassingPolity = cell.EncompassingTerritory.Polity; if (!encompassingPolity.HasEventMessage(_discovery.UId)) { if (eventMessage == null) { eventMessage = new DiscoveryEventMessage(_discovery, cell, _discovery.UId, TriggerDate); } encompassingPolity.AddEventMessage(eventMessage); } } }
private void AddCellDataToInfoPanel_Language(TerrainCell cell) { InfoText.text += "\n"; InfoText.text += "\n -- Group Language Data -- "; InfoText.text += "\n"; if (cell.Group == null) { InfoText.text += "\n\tNo population at location"; return; } int population = cell.Group.Population; if (population <= 0) { InfoText.text += "\n\tNo population at location"; return; } Language groupLanguage = cell.Group.Culture.Language; if (groupLanguage == null) { InfoText.text += "\n\tNo major language spoken at location"; return; } InfoText.text += "\n\tPredominant language at location: " + groupLanguage.Id; }
public static float CalculateNeighborhoodWaterPresenceIn(CellGroup group) { float neighborhoodPresence; int groupCellBonus = 1; int cellCount = groupCellBonus; TerrainCell groupCell = group.Cell; float totalPresence = groupCell.WaterBiomePresence * groupCellBonus; foreach (TerrainCell c in groupCell.Neighbors.Values) { totalPresence += c.WaterBiomePresence; cellCount++; } neighborhoodPresence = totalPresence / cellCount; if ((neighborhoodPresence < 0) || (neighborhoodPresence > 1)) { throw new System.Exception("Neighborhood sea presence outside range: " + neighborhoodPresence); } return(neighborhoodPresence); }
void ConstructCell(Vector3 offset, Vector3[] blockPoints, int modulus, int cellNumber) { TerrainCell cell = cells[cellNumber]; Vector3[] triVerts = new Vector3[3]; int index; for (int i = 0; i < cell.triCount; i += 3) { for (int j = 0; j < 3; j++) { index = cell.tris[i + j]; triVerts[j] = cell.vertices[modulus, index]; triVerts[j].y = 0; for (int k = 0; k < 4; k++) { triVerts[j].y += blockPoints[(k + modulus) % 4].y * cell.heightWeights[index][k]; } triVerts[j].x += blockPoints[0].x * cell.wallWeights[index][(3 + 4 - modulus) % 4] + blockPoints[1].x * cell.wallWeights[index][(1 + 4 - modulus) % 4]; triVerts[j].z += blockPoints[0].z * cell.wallWeights[index][(4 - modulus) % 4] + blockPoints[3].z * cell.wallWeights[index][(2 + 4 - modulus) % 4]; triVerts[j] += offset; } MakeTri(triVerts); } }
private void OnValidate() { terrainSystem = gameObject.GetComponent <TerrainSystem>(); cells = new TerrainCell[21]; cells[0] = new TerrainCell(M0000); cells[1] = new TerrainCell(M000A); cells[2] = new TerrainCell(M000A, true, 3);// 000B cells[3] = new TerrainCell(M00AB); cells[4] = new TerrainCell(M00BA); cells[5] = new TerrainCell(M0A0B); cells[6] = new TerrainCell(M0AAB); cells[7] = new TerrainCell(M0AAB, true, 1); // 0ABB cells[8] = new TerrainCell(M0BBA); cells[9] = new TerrainCell(M0BBA, true, 1); // 0BAA cells[10] = new TerrainCell(M0ABA); cells[11] = new TerrainCell(M0ABA, true, 1); // 0BAB cells[12] = new TerrainCell(MAAAB); cells[13] = new TerrainCell(MAAAB, true, 0);// ABBB cells[14] = new TerrainCell(MAABB0); cells[15] = new TerrainCell(MAABB1); cells[16] = new TerrainCell(MAABB1, true, 0);// AABB2 cells[17] = new TerrainCell(MABAB0); cells[18] = new TerrainCell(MABAB1); cells[19] = new TerrainCell(MABAB2); cells[20] = new TerrainCell(MABAB3); }
public TerrainCellAlteration(TerrainCell cell, bool addLayerData = true) { Longitude = cell.Longitude; Latitude = cell.Latitude; Position = cell.Position; BaseAltitudeValue = cell.BaseAltitudeValue; BaseTemperatureValue = cell.BaseTemperatureValue; BaseRainfallValue = cell.BaseRainfallValue; BaseTemperatureOffset = cell.BaseTemperatureOffset; BaseRainfallOffset = cell.BaseRainfallOffset; FarmlandPercentage = cell.FarmlandPercentage; Accessibility = cell.Accessibility; Arability = cell.Arability; if (addLayerData) { foreach (CellLayerData data in cell.LayerData) { if (data.Offset == 0) { continue; } LayerData.Add(new CellLayerData(data)); } } Modified = cell.Modified; }
public TerrainCell[,] CalculateWatershed(TerrainCell[,] input, float cellWidth, int iterations) { var start = EditorApplication.timeSinceStartup; int width = input.GetLength(0); int length = input.GetLength(1); Debug.Log($"{width} {length}"); TerrainCell[,] output = new TerrainCell[width, length]; int cellSize = System.Runtime.InteropServices.Marshal.SizeOf(typeof(TerrainCell)); ComputeBuffer inputBuffer = new ComputeBuffer(input.Length, cellSize); inputBuffer.SetData(input); ComputeBuffer outputBuffer = new ComputeBuffer(output.Length, cellSize); int kernel = shader.FindKernel("CalculateWatershed"); LoadShaderSettings(); shader.SetInt("width", width); shader.SetFloat("cellWidth", cellWidth); for (int i = 0; i < iterations; i++) { if (i % 2 == 0) { shader.SetBuffer(kernel, "working1", inputBuffer); shader.SetBuffer(kernel, "working2", outputBuffer); } else { shader.SetBuffer(kernel, "working1", outputBuffer); shader.SetBuffer(kernel, "working2", inputBuffer); } var startDispatch = EditorApplication.timeSinceStartup; shader.Dispatch(kernel, input.Length, 1, 1); Debug.Log($"dispatch time: {EditorApplication.timeSinceStartup - startDispatch}"); } if (iterations % 2 == 1) { outputBuffer.GetData(output); } else { inputBuffer.GetData(output); } inputBuffer.Release(); outputBuffer.Release(); Debug.Log(EditorApplication.timeSinceStartup - start); return(output); }
public void TerrainDoubledOnRoad() { var terrainCell = new TerrainCell(0, 0, 0, 0); terrainCell.Roads = RoadType.Road1; Assert.Equal(0.5, terrainCell.GroundUnitTerrainModifier); }
public bool ChangeTerrainTall(Vector2Int position, TerrainTall tall) { TerrainCell cell = getCell(position); cell.Tall = tall; return(true); }
public void IndexerTest() { var terrainMap = new TerrainMap(new ShortestPath()); terrainMap[2, 2] = new TerrainCell(0, 0, 0, 2); Assert.Equal(2, terrainMap[2, 2].BackgroundType); }
private void AddCell(Vector2 position) { GameObject newObject = Instantiate(new GameObject("Cell"), new Vector3(position.x, 0f, position.y), Quaternion.identity, transform); TerrainCell tc = newObject.AddComponent <TerrainCell>(); tc.PrepareTerrainCell(this); cells.Add(tc); }
public Vector3[,] CalculateNormals(float[,] heights, float cellWidth) { var start = EditorApplication.timeSinceStartup; int width = heights.GetLength(0); int length = heights.GetLength(1); TerrainCell[] input = new TerrainCell[width * length]; TerrainCell[] output = new TerrainCell[width * length]; int cellSize = System.Runtime.InteropServices.Marshal.SizeOf(typeof(TerrainCell)); Debug.Log($"{width} {length} cellSize: {cellSize}"); for (int i = 0; i < width; i++) { for (int j = 0; j < length; j++) { input[i + j * width].height = heights[i, j]; } } ComputeBuffer inputBuffer = new ComputeBuffer(input.Length, cellSize); inputBuffer.SetData(input); ComputeBuffer outputBuffer = new ComputeBuffer(output.Length, cellSize); int kernel = shader.FindKernel("CalculateNormals"); LoadShaderSettings(); shader.SetInt("width", width); shader.SetBuffer(kernel, "working1", inputBuffer); shader.SetBuffer(kernel, "working2", outputBuffer); shader.SetFloat("cellWidth", cellWidth); var startDispatch = EditorApplication.timeSinceStartup; shader.Dispatch(kernel, input.Length, 1, 1); Debug.Log($"dispatch time: {EditorApplication.timeSinceStartup - startDispatch}"); outputBuffer.GetData(output); inputBuffer.Release(); outputBuffer.Release(); Vector3[,] result = new Vector3[width, length]; for (int i = 0; i < width; i++) { for (int j = 0; j < length; j++) { result[i, j] = output[i + j * width].normal; } } Debug.Log(EditorApplication.timeSinceStartup - start); return(result); }
public bool ChangeTerrainType(Vector2Int position, TerrainType type) { TerrainCell cell = getCell(position); cell.Type = type; // TODO return(true); }
public static GlobeRegionStorageData Create(GlobeRegion globeRegion, TerrainCell terrainCell) { var storageData = new GlobeRegionStorageData(); storageData.Id = terrainCell.Coords.ToString(); storageData.Nodes = globeRegion.RegionNodes.Select(x => GlobeRegionNodeStorageData.Create(x)).ToArray(); return(storageData); }
public void CreateRiverNode(TerrainCell nodeCell) { Vector3 riverPosition = new Vector3(); riverPosition = new Vector3((nodeCell.position.x / terData.heightmapResolution) * terData.size.x, nodeCell.heightAtCell * terData.size.y, (nodeCell.position.y / terData.heightmapResolution) * terData.size.z); AddNode(riverPosition, riverWidth); CreateMesh(riverSmooth, true); }
protected void AddPolityProminenceEffectInternal(CulturalSkill politySkill, PolityProminence polityProminence, long timeSpan, float timeEffectFactor) { float targetValue = politySkill.Value; float prominenceEffect = polityProminence.Value; TerrainCell groupCell = Group.Cell; float randomEffect = groupCell.GetNextLocalRandomFloat(RngOffsets.SKILL_POLITY_PROMINENCE + RngOffset + unchecked ((int)polityProminence.PolityId)); float timeEffect = timeSpan / (timeSpan + timeEffectFactor); // _newvalue should have been set correctly either by the constructor or by the Update function float change = (targetValue - _newValue) * prominenceEffect * timeEffect * randomEffect; //#if DEBUG // if (Manager.RegisterDebugEvent != null) // { // if (Manager.TracingData.Priority <= 0) // { // if (Group.Id == Manager.TracingData.GroupId) // { // string groupId = "Id:" + Group.Id + "|Long:" + Group.Longitude + "|Lat:" + Group.Latitude; // SaveLoadTest.DebugMessage debugMessage = new SaveLoadTest.DebugMessage( // "PolityCulturalProminenceInternal - Group:" + groupId, // "CurrentDate: " + Group.World.CurrentDate + // ", Name: " + Name + // ", timeSpan: " + timeSpan + // ", timeEffectFactor: " + timeEffectFactor + // ", randomEffect: " + randomEffect + // ", polity Id: " + polityProminence.PolityId + // ", polityProminence.Value: " + prominenceEffect + // ", politySkill.Value: " + targetValue + // ", Value: " + Value + // ", change: " + change + // "", Group.World.CurrentDate); // Manager.RegisterDebugEvent("DebugMessage", debugMessage); // } // } // else if (Manager.TracingData.Priority <= 1) // { // string groupId = "Id:" + Group.Id + "|Long:" + Group.Longitude + "|Lat:" + Group.Latitude; // SaveLoadTest.DebugMessage debugMessage = new SaveLoadTest.DebugMessage( // "PolityCulturalProminenceInternal - Group:" + groupId, // "CurrentDate: " + Group.World.CurrentDate + // "", Group.World.CurrentDate); // Manager.RegisterDebugEvent("DebugMessage", debugMessage); // } // } //#endif _newValue = _newValue + change; }
public override void FinalizeLoad() { MigrationDirection = (Direction)MigrationDirectionInt; base.FinalizeLoad(); TargetCell = World.TerrainCells[TargetCellLongitude][TargetCellLatitude]; SourceGroup = World.GetGroup(SourceGroupId); }
public void CreateRiverNode(TerrainCell nodeCell) { Vector3 riverPosition = new Vector3(); riverPosition = new Vector3((nodeCell.position.x/terData.heightmapResolution) * terData.size.x, nodeCell.heightAtCell * terData.size.y , (nodeCell.position.y/terData.heightmapResolution) * terData.size.z); AddNode(riverPosition, riverWidth); CreateMesh(riverSmooth, true); }
void OnSceneGUI() { Event currentEvent = Event.current; if (riverScript.nodeObjects != null && riverScript.nodeObjects.Length != 0 && !riverScript.finalized) { int n = riverScript.nodeObjects.Length; for (int i = 0; i < n; i++) { RiverNodeObject node = riverScript.nodeObjects[i]; node.position = Handles.PositionHandle(node.position, Quaternion.identity); } } if(riverScript.riverNodeMode == true) { if(currentEvent.isKey && currentEvent.character == 'r') { Vector3 riverNode = GetTerrainCollisionInEditor(currentEvent, KeyCode.R); TerrainCell riverNodeCell = new TerrainCell(); riverNodeCell.position.x = riverNode.x; riverNodeCell.position.y = riverNode.z; riverNodeCell.heightAtCell = riverNode.y; riverScript.CreateRiverNode(riverNodeCell); riverScript.riverNodeMode = false; } } if (GUI.changed) { if(!riverScript.finalized) { EditorUtility.SetDirty(riverScript); riverScript.CreateMesh(riverScript.riverSmooth, false); } } }