internal GridSystem(int width, int height, int id, City parentCity, TickManager tickMan, Vector3 worldGridPosition) { Id = id; ParentCity = parentCity; Width = width; Height = height; _tickManager = tickMan; Tiles = new GridTile[Width][]; //Initialize Tiles array with empty tiles: for (int x = 0; x < Width; x++) { Tiles[x] = new GridTile[Height]; for (int y = 0; y < Height; y++) { Tiles[x][y] = new GridTile(new Vector2Int(x, y), this); } } Residents = new List <Resident>(); _gridResources = new Dictionary <Type, List <ResourceData> >(); WorldGrid = CreateWorldGrid(worldGridPosition); }
List <Character> FindCharacters() { //Get the grid the character is currently in GridIndex index = WorldGrid.GetGridIndex(character.transform.position); GridCell cell = WorldGrid.GetTheWorldGridCell(index); //check if the cell position is within the search radius //bool xSearch = true, ySearch = true; //add all characters to a list List <Character> proximityCharacters = new List <Character>(); //TODO: add more intuitive and wider search logic depending on character behavior if (character.gridCell != null) { if (character.gridCell.character.Count > 0) { //Add the list of characters. This info is withing grid cell proximityCharacters.AddRange(character.gridCell.character); //Debug.Log("count : " + proximityCharacters.Count); //Debug.Log("names: " + proximityCharacters[0].name + " " + character.name); //Remove yourself from the characters list for (int i = 0; i < proximityCharacters.Count; i++) { if (proximityCharacters[i].gameObject == character.gameObject) { proximityCharacters.RemoveAt(i); //Debug.Log("Removed"); } } } } //TODO: Filter the characters to find the ones that are withing this character's FOV return(proximityCharacters); }
void handleInteract() { if (Input.GetKeyDown(KeyCode.E)) { WorldGrid.DestroyCellAt(whereAmIFacing); } }
public override void HandleMovement(Character c) { if (c.Movement == new Vector3Int(0, 0, 0)) { ToState(c, new StateIdle()); } if (!Input.GetKey(KeyCode.LeftShift)) { ToState(c, new StateWalk()); } c.Animator.ChangeFacingDirection(c.CurrentFacing); _whereAmI = WorldGrid.GetGridPositionFromWorld(c.transform.position); DataTile dt = WorldGrid.GetCellAt(_whereAmI + c.Movement); if (!dt.walkable) { Debug.LogError("Sorry buddy, you cant move there!"); return; } _oldPos = c.transform.position; _nextPos = WorldGrid.GetWorldPositionFromGrid(_whereAmI + c.Movement); _difference = _nextPos - _oldPos; _timer = 0; }
public static void CreateWorldGrid() { WorldGrid grid = ScriptableObjectAssetCreator.GenerateAndRetrieveScriptableObjectAssetAtSelectedFolder <WorldGrid>("WorldGrid"); WorldGridBaseEditor editor = new WorldGridBaseEditor(new SerializedObject(grid)); editor.InitializeWorldGrid(); }
private void SetBiomeToAllTiles() { if (selectedBiome == null) { Messages.Message($"First choose a biome", MessageTypeDefOf.NeutralEvent, false); return; } WorldGrid grid = Find.WorldGrid; if (!setOceanToo) { grid.tiles.Where(tile => tile.biome != BiomeDefOf.Ocean && tile.biome != BiomeDefOf.Lake).ForEach(tile => { tile.biome = selectedBiome; }); } else { grid.tiles.ForEach(tile => { tile.biome = selectedBiome; }); } LongEventHandler.QueueLongEvent(delegate { LayersSubMeshes["WorldLayer_Terrain"].Clear(); WorldUpdater.UpdateLayer(Layers["WorldLayer_Terrain"]); }, "Set biome on the whole map ...", doAsynchronously: false, null); }
public static void DrawTileTangentialToPlanetWithRodation(WorldGrid grid, LayerSubMesh subMesh, int tileID, int atlasX, int atlasZ, IntVec2 texturesInAtlas, int rotDir) { int totalVertCount = subMesh.verts.Count; grid.GetTileVertices(tileID, tmpVerts); int tileVertCount = tmpVerts.Count; //if (tileVertCount != 6) { Log.Error("id: " + tileID + ", tileVertCount: " + tileVertCount); } //if (rotDir < 0) { Log.Error("id: " + tileID + ", dir: " + rotDir); } if (rotDir < 0) { rotDir += tileVertCount; } for (int i = 0; i < tileVertCount; i++) { int vertIndex = (i + rotDir) % tileVertCount; subMesh.verts.Add(tmpVerts[vertIndex] + tmpVerts[vertIndex].normalized * 0.012f); Vector2 posAtlasUV = (GenGeo.RegularPolygonVertexPosition(tileVertCount, i) + Vector2.one) / 2f; posAtlasUV.x = (posAtlasUV.x + atlasX) / texturesInAtlas.x; posAtlasUV.y = (posAtlasUV.y + atlasZ) / texturesInAtlas.z; subMesh.uvs.Add(posAtlasUV); if (i < tileVertCount - 2) { subMesh.tris.Add(totalVertCount + i + 2); subMesh.tris.Add(totalVertCount + i + 1); subMesh.tris.Add(totalVertCount); } } }
private void DeleteFeature() { if (selectedFeature == null) { Messages.Message($"Select feature to delete", MessageTypeDefOf.NeutralEvent, false); return; } WorldGrid grid = Find.WorldGrid; foreach (var t in selectedFeature.Tiles) { if (grid[t].feature == selectedFeature) { grid[t].feature = null; } } Find.WorldFeatures.features.Remove(selectedFeature); Find.WorldFeatures.textsCreated = false; Find.WorldFeatures.UpdateFeatures(); selectedFeature = null; }
private void Awake() { functions = GetComponent <Functions>(); placement = GetComponent <Placement>(); grid = GetComponent <WorldGrid>(); currentTimer = initialTimer; }
void Start() { _myModules = new ModuleContainer(); // will be used in the future _myAgentFactory = _myModules.AgentFactory; _myWorldGrid = _myModules.WorldGrid; for (int i = 0; i < 20; i++) { _myAgentFactory.CreateAgent(_myWorldGrid); } _myWorldGrid.Started = true; /* * float actualTestX = (float)3.3; * float actualTestY = (float)6.7; * * Debug.Log(_myWorldGrid.GetClosestDistance(3, 6, actualTestX, actualTestY, 2, 5)); * Debug.Log(_myWorldGrid.GetClosestDistance(3, 6, actualTestX, actualTestY, 2, 6)); * Debug.Log(_myWorldGrid.GetClosestDistance(3, 6, actualTestX, actualTestY, 2, 7)); * Debug.Log(_myWorldGrid.GetClosestDistance(3, 6, actualTestX, actualTestY, 3, 5)); * Debug.Log(_myWorldGrid.GetClosestDistance(3, 6, actualTestX, actualTestY, 3, 7)); * Debug.Log(_myWorldGrid.GetClosestDistance(3, 6, actualTestX, actualTestY, 4, 5)); * Debug.Log(_myWorldGrid.GetClosestDistance(3, 6, actualTestX, actualTestY, 4, 6)); * Debug.Log(_myWorldGrid.GetClosestDistance(3, 6, actualTestX, actualTestY, 4, 7)); */ }
private RiverMaker GenerateRiver(Map map) { Tile tile = Find.WorldGrid[map.Tile]; List <Tile.RiverLink> visibleRivers = tile.VisibleRivers; if (visibleRivers != null && visibleRivers.Count != 0) { WorldGrid worldGrid = Find.WorldGrid; int tile2 = map.Tile; Tile.RiverLink riverLink = (from rl in visibleRivers orderby - rl.river.degradeThreshold select rl).First(); float headingFromTo = worldGrid.GetHeadingFromTo(tile2, riverLink.neighbor); float num = Rand.Range(0.3f, 0.7f); IntVec3 size = map.Size; float x = num * (float)size.x; float num2 = Rand.Range(0.3f, 0.7f); IntVec3 size2 = map.Size; Vector3 vector = new Vector3(x, 0f, num2 * (float)size2.z); Vector3 center = vector; float angle = headingFromTo; Tile.RiverLink riverLink2 = (from rl in visibleRivers orderby - rl.river.degradeThreshold select rl).FirstOrDefault(); RiverMaker riverMaker = new RiverMaker(center, angle, riverLink2.river); this.GenerateRiverLookupTexture(map, riverMaker); return(riverMaker); } return(null); }
internal static void Postfix(int tile, ref IEnumerable <ThingDef> __result, ref World __instance) { var world = Traverse.Create(__instance); WorldGrid worldGrid = world.Field("grid").GetValue <WorldGrid>(); if (worldGrid[tile].biome.defName == "BiomesPreview_Atoll") { List <ThingDef> rocks = new List <ThingDef>() { BiomesPreviewDefOf.BiomesIslands_CoralRock }; __result = rocks; } else if (__result.Contains(BiomesPreviewDefOf.BiomesIslands_CoralRock)) { Rand.PushState(); Rand.Seed = tile; List <ThingDef> rocks = __result.ToList(); rocks.Remove(BiomesPreviewDefOf.BiomesIslands_CoralRock); List <ThingDef> list = (from d in DefDatabase <ThingDef> .AllDefs where d.category == ThingCategory.Building && d.building.isNaturalRock && !d.building.isResourceRock && !d.IsSmoothed && !rocks.Contains(d) && d.defName != "BiomesIslands_CoralRock" select d).ToList <ThingDef>(); if (!list.NullOrEmpty()) { rocks.Add(list.RandomElement <ThingDef>()); } __result = rocks; Rand.PopState(); } }
private float getSeasonMoveCost(int currentPlace) { WorldGrid grid = Find.WorldGrid; Tile currentTile = grid.tiles[currentPlace]; Season season = GenDate.Season(Find.TickManager.TicksGame, grid.LongLatOf(currentPlace)); switch (season) { case Season.Spring: return(currentTile.biome.pathCost_spring); case Season.Summer: case Season.PermanentSummer: return(currentTile.biome.pathCost_summer); case Season.Fall: return(currentTile.biome.pathCost_fall); case Season.Winter: case Season.PermanentWinter: return(currentTile.biome.pathCost_winter); } Log.Error("unable to know seasonal move cost"); return(0); }
public static bool SeasonalShiftAmplitudeAt(ref float __result, int tile) { WorldGrid newWorldGrid = Find.WorldGrid; if (worldGrid != newWorldGrid) { worldGrid = newWorldGrid; SeasonalShiftAmplitudeCache.Clear(); tileAbsTickTemperature.Clear(); tileTemperature.Clear(); #if DEBUG Log.Message("RimThreaded is rebuilding WorldGrid Temperature Cache"); #endif } if (SeasonalShiftAmplitudeCache.TryGetValue(tile, out __result)) { return(false); } __result = Find.WorldGrid.LongLatOf(tile).y >= 0.0 ? TemperatureTuning.SeasonalTempVariationCurve.Evaluate(newWorldGrid.DistanceFromEquatorNormalized(tile)) : -TemperatureTuning.SeasonalTempVariationCurve.Evaluate(newWorldGrid.DistanceFromEquatorNormalized(tile)); SeasonalShiftAmplitudeCache[tile] = __result; return(false); }
public void Populate(WorldGrid grid) { FindCoord(grid, Direction.North); FindCoord(grid, Direction.South); FindCoord(grid, Direction.East); FindCoord(grid, Direction.West); }
public SimulationGame() { Graphics = new GraphicsDeviceManager(this); Graphics.PreparingDeviceSettings += new EventHandler <PreparingDeviceSettingsEventArgs>((object sender, PreparingDeviceSettingsEventArgs eventargs) => { eventargs.GraphicsDeviceInformation.PresentationParameters.RenderTargetUsage = RenderTargetUsage.PreserveContents; }); Graphics.PreferredBackBufferWidth = Resolution.Width; // set this value to the desired width of your window Graphics.PreferredBackBufferHeight = Resolution.Height; // set this value to the desired height of your window Graphics.ApplyChanges(); Content.RootDirectory = "Content"; ContentManager = Content; VisibleArea = Rect.Empty; IsDebug = false; Thread.CurrentThread.Priority = ThreadPriority.AboveNormal; World = new WorldGrid(); I = this; }
private void GenerateLake() { WorldGrid grid = Find.WorldGrid; bool[] touched = new bool[grid.TilesCount]; List <int> oceanChunk = new List <int>(); for (int i = 0; i < grid.TilesCount; i++) { if (touched[i] || grid[i].biome != BiomeDefOf.Ocean) { continue; } Find.WorldFloodFiller.FloodFill(i, (int tid) => grid[tid].biome == BiomeDefOf.Ocean, delegate(int tid) { oceanChunk.Add(tid); touched[tid] = true; }); if (oceanChunk.Count <= 15) { for (int j = 0; j < oceanChunk.Count; j++) { grid[oceanChunk[j]].biome = BiomeDefOf.Lake; } } oceanChunk.Clear(); } }
static bool Prefix(WorldGrid __instance, int ___cachedTraversalDistance, int ___cachedTraversalDistanceForStart, int ___cachedTraversalDistanceForEnd) { if (copyFrom == null) { return(true); } WorldGrid grid = __instance; grid.viewAngle = copyFrom.viewAngle; grid.viewCenter = copyFrom.viewCenter; grid.verts = copyFrom.verts; grid.tileIDToNeighbors_offsets = copyFrom.tileIDToNeighbors_offsets; grid.tileIDToNeighbors_values = copyFrom.tileIDToNeighbors_values; grid.tileIDToVerts_offsets = copyFrom.tileIDToVerts_offsets; grid.averageTileSize = copyFrom.averageTileSize; grid.tiles = new List <Tile>(); ___cachedTraversalDistance = -1; ___cachedTraversalDistanceForStart = -1; ___cachedTraversalDistanceForEnd = -1; copyFrom = null; return(false); }
float GetHeight(WorldGridTile tile) { float height = 0f; Vector2Int pos = tile.Position; WorldGrid grid = tile.ParentGrid; for (int i = pos.x - 1; i < pos.x + 2; i++) { for (int j = pos.y - 1; j < pos.y + 2; j++) { WorldGridTile adjTile = grid.GetTile(i, j); if (adjTile == null) { continue; } if (adjTile.Model) { if (adjTile.Model.GetComponent <MeshRenderer>()) { height = (adjTile.Model.GetComponent <MeshRenderer>().bounds.size.y > height) ? adjTile.Model.GetComponent <MeshRenderer>().bounds.size.y : height; } else { height = (adjTile.Model.GetComponentInChildren <MeshRenderer>().bounds.size.y > height) ? adjTile.Model.GetComponentInChildren <MeshRenderer>().bounds.size.y : height; } } } } return(height); }
/// <summary> /// Returns a populated world grid for testing. /// </summary> /// <returns></returns> private WorldGrid GetPopulatedWorldGrid() { WorldGrid grid = new WorldGrid(800, 800, 200, 200); // Populate float[] posX = new float[] { 250, 450, 650, 750, 210, 450, 500, 50, 250, 750 }; float[] posY = new float[] { 50, 50, 50, 150, 300, 300, 500, 700, 700, 700 }; for (int i = 0; i < posX.Length; i++) { WorldComponent comp = new WorldComponent(); comp.Entity = new Entity(i); comp.PositionComponent = new PositionComponent(); comp.PositionComponent.Position = new Vector2(posX[i], posY[i]); grid.Add(comp); } return(grid); }
public List<Point> GetValidMoves(int positionX, int positionY, WorldGrid worldGrid) { List<Point> validMoves = new List<Point>(); Random rand = new Random(); for (int i = -1; i <= 1; i++) { for (int j = -1; j <= 1; j++) { if (i == 0 && j == 0) continue; int neighborX = positionX + i; int neighborY = positionY + j; if (neighborX > 0 && neighborX < worldGrid.WorldHeight && neighborY > 0 && neighborY < worldGrid.WorldWidth) { if (worldGrid.CurrentState[positionX, positionY] == 1 && worldGrid.CurrentState[neighborX, neighborY] == 0) { validMoves.Add(new Point(neighborX, neighborY)); } } } } if (validMoves.Count > 0) { validMoves.Shuffle(); return validMoves; } return validMoves; }
/// <summary> /// Renders all structures of the worldgrid. /// </summary> /// <param name="spriteBatch">The spritebatch to use for drawing.</param> /// <param name="worldGrid">The worldgrid to get all info from.</param> public void RenderStructures(SpriteBatch spriteBatch, WorldGrid worldGrid) { for (byte xIndex = 0; xIndex < worldGrid.Size; xIndex++) { for (byte yIndex = 0; yIndex < worldGrid.Size; yIndex++) { if (!worldGrid.HasStructure(yIndex, xIndex)) { continue; } Structure currentStructure = worldGrid.GetStructure(yIndex, xIndex); if (xIndex != currentStructure.X || yIndex != currentStructure.Y) { continue; } int structureTypeIndex = (int)currentStructure.Type - 1; byte structureHeight = currentStructure.Height; structureTextureAtlas.Draw( structureTypeIndex * STRUCTURE_HEIGHT, 0, STRUCTURE_HEIGHT, STRUCTURE_WIDTH, spriteBatch, new Rectangle(xIndex * CELL_SIZE * DISPLAY_SCALE, (yIndex - STRUCTURE_HEIGHT + structureHeight) * CELL_SIZE * DISPLAY_SCALE, CELL_SIZE * STRUCTURE_WIDTH * DISPLAY_SCALE, CELL_SIZE * STRUCTURE_HEIGHT * DISPLAY_SCALE), Color.White ); } } }
void UpdateWorldGrid() { //clear grid from child cubes for (int y = 0; y < WorldGrid.gridSize.y; ++y) { for (int x = 0; x < WorldGrid.gridSize.x; ++x) { for (int z = 0; z < WorldGrid.gridSize.z; ++z) { if (WorldGrid.Grid[y, x, z] != null) { if (WorldGrid.Grid[y, x, z].parent == transform) { WorldGrid.Grid[y, x, z] = null; } } } } } //save new position in grid foreach (Transform cube in transform) { Vector3 v = WorldGrid.RoundVector(cube.position); WorldGrid.Grid[(int)v.y, (int)v.x, (int)v.z] = cube; } }
/// <summary> /// Renders all crops of the worldgrid. /// </summary> /// <param name="spriteBatch">The spritebatch to use for drawing.</param> /// <param name="worldGrid">The worldgrid to get all info from.</param> public void RenderCrops(SpriteBatch spriteBatch, WorldGrid worldGrid) { float maxYTextureIndex = cropTextureAtlas.YSize - 1; for (byte xIndex = 0; xIndex < worldGrid.Size; xIndex++) { for (byte yIndex = 0; yIndex < worldGrid.Size; yIndex++) { if (!worldGrid.HasCrop(yIndex, xIndex)) { continue; } Crop?currentCrop = worldGrid.GetCrop(yIndex, xIndex); int growthIndex = (int)(currentCrop.Value.Growth * maxYTextureIndex); int cropTypeIndex = ((int)currentCrop.Value.Type) - 1; cropTextureAtlas.Draw( cropTypeIndex, growthIndex, 1, 1, spriteBatch, new Rectangle(xIndex * CELL_SIZE * DISPLAY_SCALE, yIndex * CELL_SIZE * DISPLAY_SCALE, CELL_SIZE * DISPLAY_SCALE, CELL_SIZE * DISPLAY_SCALE), Color.White ); } } }
void drawGizmo() { WorldGrid grid = WorldData.worldGrid; Gizmos.color = Color.green; for (int z = 0; z < grid.cellCount; z++) { for (int x = 0; x < grid.cellCount; x++) { if (!grid.getCell(x, debugRenderLevel, z).blocked) { Gizmos.color = Color.green; } else { Gizmos.color = Color.red; } Vector3 cubeCenter = new Vector3( x * grid.cellSize + grid.cellSize / 2, grid.yOffsets[debugRenderLevel], z * grid.cellSize + grid.cellSize / 2 ); cubeCenter += new Vector3(grid.xzOffsets.x, 0, grid.xzOffsets.y); Gizmos.DrawCube(cubeCenter, new Vector3(grid.cellSize, 0, grid.cellSize)); } } }
public void PopulateCoords(WorldGrid grid) { for (int i = 0; i < m_Coordinates.Count; ++i) { m_Coordinates[i].Populate(grid); } }
public static void Postfix(ref bool __result, int tile, StringBuilder reason) { if (!__result) { return; } WorldGrid worldGrid = Find.WorldGrid; var listWO = Find.WorldObjects.AllWorldObjects; for (int i = 0; i < listWO.Count; i++) { if (!(listWO[i] is BaseOnline)) { continue; } var wot = listWO[i].Tile; if (wot == tile || worldGrid.IsNeighborOrSame(wot, tile)) { if (reason != null) { reason.Append("OCity_Starter_CityNotBuild".Translate()); } __result = false; return; } } }
private void MainWindow_KeyDown(object sender, KeyEventArgs e) { WorldGrid.Focus(); if (e.Key == Key.Right) { Constants.CameraX += Constants.TILE_WIDTH; } if (e.Key == Key.Left) { Constants.CameraX -= Constants.TILE_WIDTH; } if (e.Key == Key.Up) { Constants.CameraY -= Constants.TILE_HEIGHT; } if (e.Key == Key.Down) { Constants.CameraY += Constants.TILE_HEIGHT; } WorldGrid.Children.Clear(); DrawGrid(); DrawWorld(); //throw new NotImplementedException(); }
public static int GetDirection6WayIntFromTo(this WorldGrid grid, int fromTileID, int toTileID) { float headingFromTo = grid.GetHeadingFromTo(fromTileID, toTileID); if (headingFromTo >= 330f || headingFromTo < 30f) { return(0); } if (headingFromTo < 90f) { return(1); } if (headingFromTo < 150f) { return(2); } if (headingFromTo < 210f) { return(3); } if (headingFromTo < 270f) { return(4); } return(5); }
/// <summary> /// Builds 1 segment of road. Returns if a segment was built /// </summary> /// <returns> this.IsCompleted </returns> /// <param name="roadDef">Road def.</param> public bool BuildSegment(RoadDef roadDef) { start: if (!this.Path.Found || this.IsCompleted) { return(false); } int tile = this.Path.ConsumeNextNode(); int lastTile = this.Path.Peek(-1); WorldGrid grid = Find.WorldGrid; RoadDef existingRoad = grid.GetRoadDef(lastTile, tile); if (IsNewRoadBetter(existingRoad, roadDef)) { // Replaces the road if this.Road.priority > the existing road's priority grid.OverlayRoad(lastTile, tile, roadDef); Find.WorldPathGrid.RecalculatePerceivedMovementDifficultyAt(lastTile); Find.WorldPathGrid.RecalculatePerceivedMovementDifficultyAt(tile); } else { goto start; } return(true); }
public Globule(WorldGrid grid, Vector2 cell) { worldGrid = grid; movement = new GlobuleMovement(); movement.cursor = 1; movement.speed = 0; movement.jitterPhase = Random.Range(0, Mathf.PI); movement.jitterPeriod = 1; movement.curCell = cell; movement.nextCell = cell; }
public Heart(WorldGrid _world) { worldGrid = _world; heartLevel = 0; globuleToSpawn = 10; globuleSpawnNextTime = Time.time + Random.Range(globuleSpawnMinDelay, globuleSpawnMaxDelay); SetupLevel1(); }
public Tree(WorldGrid _world, Cell _cell, Vector2 _position) { position = _position; worldGrid = _world; cell = _cell; ressourceConsumer = new RessourceConsumer(); ressourceConsumer.createTypes = RessourceType.None; ressourceConsumer.consumTypes = RessourceType.Blue | RessourceType.Green; ressourceConsumer.OnRessourceConsumed += new RessourceConsumer.RessourceEvent(ressourceConsumer_OnRessourceConsumed); ressourceConsumer.OnRessourceCreated += new RessourceConsumer.RessourceEvent(ressourceConsumer_OnRessourceCreated); cell.ressourceConsumer = ressourceConsumer; type = _world.lifeLayer.treeTypes[ Random.Range(0, _world.lifeLayer.treeTypes.Length) ]; maxLevel = type.growthCount - 1; animOffset = Random.value; worldGrid.trees.Add(this); }