//public FovShapeType FovShape //{ // get { return fovProfile.FovShape; } // set { fovProfile.FovShape = value; } //} #endregion #region IFovAlgorithm Members public FovResultset CalculateFov(TerrainMap terrain, Point origin, IFovProfile fovProfile) { visibleLocations = new FovResultset(); // fovProfile.FovShape = shapeType; if (terrain != null) { visibleLocations.Add(new FovObject() { Location = { Coordinate = origin }, DistanceFromOrigin = 0 }); if (fovProfile.FovRadius > 0) { ScanNorthwestToNorth(terrain, origin, fovProfile); ScanNorthToNortheast(terrain, origin, fovProfile); ScanNortheastToEast(terrain, origin, fovProfile); ScanEastToSoutheast(terrain, origin, fovProfile); ScanSoutheastToSouth(terrain, origin, fovProfile); ScanSouthToSouthwest(terrain, origin, fovProfile); ScanSouthwestToWest(terrain, origin, fovProfile); ScanWestToNorthwest(terrain, origin, fovProfile); } } return(visibleLocations); }
void BuildTerrain(TerrainMap map, ref int totalTriangles) { TileDrawInfo drawInfo = new TileDrawInfo(); int lengthX = map.Width; int lengthY = map.Length; int index = 0; GL.Begin(BeginMode.Quads); for (int x = 0; x < 6; x++) { for (int y = 0; y < 6; y++) { Tile tile = map[x, y]; drawInfo.CurrentTile = tile; drawInfo.MapX = x; drawInfo.MapY = y; RenderTile(drawInfo); index += 4; } } // end for GL.End(); totalTriangles = drawInfo.TotalTriangles; }
VertexPos3Col4[] BuildTerrainBorders(TerrainMap map, ref int totalTriangles) { TileDrawInfo drawInfo = new TileDrawInfo(); int lengthX = map.Width; int lengthY = map.Length; VertexPos3Col4[] vertices = new VertexPos3Col4[lengthX * lengthY * 4]; int index = 0; for (int x = 0; x < lengthX; x++) { for (int y = 0; y < lengthY; y++) { Tile tile = map[x, y]; drawInfo.CurrentTile = tile; drawInfo.MapX = x; drawInfo.MapY = y; RenderTileBorders(drawInfo, vertices, index); index += 4; } } // end for totalTriangles += drawInfo.TotalTriangles; return(vertices); }
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]); }
private TerrainMap CreateMap() { var terraMap = new TerrainMap(10, 10); var map = terraMap.Map; // TODO load map from file map[2, 9] = new WaterTerrain(2, 9); map[2, 8] = new WaterTerrain(2, 8); map[2, 7] = new WaterTerrain(2, 7); map[2, 6] = new WaterTerrain(2, 6); map[3, 5] = new WaterTerrain(3, 5); map[4, 5] = new WaterTerrain(4, 5); map[5, 4] = new WaterTerrain(5, 4); map[5, 3] = new WaterTerrain(5, 3); map[5, 2] = new WaterTerrain(5, 2); map[6, 1] = new WaterTerrain(6, 1); map[4, 0] = new WaterTerrain(4, 0); map[5, 0] = new WaterTerrain(5, 0); map[6, 0] = new WaterTerrain(6, 0); for (var x = 3; x < 10; x++) { for (var y = 6; y < 10; y++) { map[x, y] = new CityTerrain(x, y); } } return(terraMap); }
internal static TerrainGroups CollectTerrains(bool onlyAutoConnectedTerrains = true) { if (!HasValidTerrains()) { return(null); } // Collect by groups TerrainGroups TerrainGroups = new TerrainGroups(); foreach (Terrain t in Terrain.activeTerrains) { if (onlyAutoConnectedTerrains && !t.allowAutoConnect) { continue; } if (!TerrainGroups.ContainsKey(t.groupingID)) { TerrainMap map = TerrainMap.CreateFromPlacement(t, (x => (x.groupingID == t.groupingID) && !(onlyAutoConnectedTerrains && !x.allowAutoConnect))); if (map != null) { TerrainGroups.Add(t.groupingID, map); } } } return((TerrainGroups.Count != 0) ? TerrainGroups : null); }
public void StartUp(VoxelMap map, WorldScriptableObject worldObject) { voxelMesh = FindObjectOfType <VoxelMesh>(); terrainNoise = FindObjectOfType <TerrainNoise>(); terrainMap = FindObjectOfType <TerrainMap>(); chunkCollider = FindObjectOfType <ChunkCollider>(); recycleableChunks = map.recycleableChunks; regionResolution = map.regionResolution; chunkResolution = map.chunkResolution; voxelResolution = map.voxelResolution; viewDistance = map.viewDistance; chunks = map.chunks; existingChunks = map.existingChunks; useVoxelReferences = map.useVoxelReferences; colliderRadius = map.colliderRadius; useColliders = map.useColliders; player = map.player; chunkSaveLoadManager = map.chunkSaveLoadManager; worldScriptableObject = worldObject; playerRb = player.GetComponent <Rigidbody2D>(); terrainNoise.seed = worldScriptableObject.seed; terrainNoise.Startup(voxelResolution, chunkResolution); voxelMesh.Startup(voxelResolution, chunkResolution, viewDistance, useColliders, colliderRadius); InvokeRepeating(nameof(UpdateMap), 0.0f, terrainMap.updateInterval); }
public void Startup(VoxelMap map) { var blockTypeNames = System.Enum.GetNames(typeof(BlockType)); foreach (var blockType in blockTypeNames) { FillTypeNames.Add(blockType); } voxelResolution = map.voxelResolution; chunkResolution = map.chunkResolution; viewDistance = map.viewDistance; existingChunks = map.existingChunks; voxelMap = map; mainCamera = Camera.main; terrainMap = FindObjectOfType <TerrainMap>(); voxelMesh = FindObjectOfType <VoxelMesh>(); chunkCollider = FindObjectOfType <ChunkCollider>(); box = gameObject.GetComponent <BoxCollider>(); if (box != null) { DestroyImmediate(box); } box = gameObject.AddComponent <BoxCollider>(); box.center = Vector3.one * (voxelResolution / 2f); box.size = new Vector3((chunkResolution - viewDistance) * voxelResolution, (chunkResolution - viewDistance) * voxelResolution); }
public static void Fill(TerrainMap terrainMap, VisibilityMap visibilityMap, IMovementProfile movementProfile, Point location) { if (!terrainMap.Bounds.Contains(location)) { return; } if (!visibilityMap.Bounds.Contains(location)) { return; } if (visibilityMap[location].WasSeen) { return; } if (!movementProfile.TerrainIsTraversable(terrainMap[location])) { return; } visibilityMap[location].WasSeen = true; Fill(terrainMap, visibilityMap, movementProfile, Direction.North.ApplyTransform(location)); Fill(terrainMap, visibilityMap, movementProfile, Direction.Northeast.ApplyTransform(location)); Fill(terrainMap, visibilityMap, movementProfile, Direction.East.ApplyTransform(location)); Fill(terrainMap, visibilityMap, movementProfile, Direction.Southeast.ApplyTransform(location)); Fill(terrainMap, visibilityMap, movementProfile, Direction.South.ApplyTransform(location)); Fill(terrainMap, visibilityMap, movementProfile, Direction.Southwest.ApplyTransform(location)); Fill(terrainMap, visibilityMap, movementProfile, Direction.West.ApplyTransform(location)); Fill(terrainMap, visibilityMap, movementProfile, Direction.Northwest.ApplyTransform(location)); }
public MovementPath FindPath(TerrainMap terrain, IList <IActor> actors, IMovementProfile movementProfile, Point locationFrom, Point locationTo) { var closed = new HashSet <PathFindingNode>(); var queue = new PriorityQueue <decimal, Path <PathFindingNode> >(); queue.Enqueue(0, new Path <PathFindingNode>(new PathFindingNode { Location = locationFrom })); while (!queue.IsEmpty) { KeyValuePair <decimal, Path <PathFindingNode> > path = queue.Dequeue(); if (closed.Contains(path.Value.LastStep)) { continue; } if (path.Value.LastStep.Location == locationTo) { return(GetDirections(path.Value)); } closed.Add(path.Value.LastStep); foreach (PathFindingNode n in GetNodeNeighbours(terrain, actors, movementProfile, path.Value.LastStep, locationTo)) { Path <PathFindingNode> newPath = path.Value.AddStep(n, n.MovementCost); queue.Enqueue(newPath.TotalCost + GetEstimatedDistance(n, locationFrom, locationTo), newPath); } } return(new MovementPath()); }
/// <summary> /// Create a pathfinder graph by either /// reading it from a file or generating it from scratch. /// </summary> /// <param name="map"> /// A sampling of the terrain topology, /// used if generating from scratch. /// </param> public PathfinderData( TerrainMap map, List <MobilityData> mobilityTypes, int sceneBuildId) { _map = map; _graphFastMove = new List <PathNode>(); _graphRegularMove = new List <PathNode>(); _mobilityTypes = mobilityTypes; string scenePathWithFilename = SceneUtility.GetScenePathByBuildIndex( sceneBuildId); string sceneName = Path.GetFileNameWithoutExtension( scenePathWithFilename); string sceneDirectory = Path.GetDirectoryName(scenePathWithFilename); _graphFile = Path.Combine(sceneDirectory, sceneName + GRAPH_FILE_SUFFIX); // maybe turn this into a multithreaded worker later //if (!ReadGraph(_graphFile)) //{ GenerateGraphRunner(); //} }
public void saveTopologyLayer() { if (topology == null) { topology = GameObject.FindGameObjectWithTag("Topology").GetComponent <TopologyMesh>(); } LandData topologyData = GameObject.FindGameObjectWithTag("Land").transform.Find("Topology").GetComponent <LandData>(); TerrainMap <int> topologyMap = new TerrainMap <int>(topology.top, 1); float[,,] splatMap = TypeConverter.singleToMulti(topologyData.splatMap, 2); for (int i = 0; i < topologyMap.res; i++) { for (int j = 0; j < topologyMap.res; j++) { if (splatMap[i, j, 0] > 0) { topologyMap[i, j] = topologyMap[i, j] | (int)oldTopologyLayer; } if (splatMap[i, j, 1] > 0) { topologyMap[i, j] = topologyMap[i, j] & ~(int)oldTopologyLayer; } } } topology.top = topologyMap.ToByteArray(); }
private decimal CalculateLocationMovementCost(TerrainMap terrainMap, IList <IActor> actors, IMovementProfile movementProfile, Point targetLocation, Point locationTo) { decimal movementCost = 0M; if (movementProfile.TerrainIsTraversable(terrainMap[targetLocation])) { movementCost += movementProfile.CalculateTerrainMovementCost(terrainMap[targetLocation]); } // We exclude actor movement cost if the target location is the end location // This way we will always find a path to an actor if (targetLocation == locationTo) { return(movementCost); } foreach (var actor in actors.Where(x => x.IsAlive && (x.Location.Coordinate == targetLocation))) { if (movementProfile.MaterialIsTraversable(actor.Race.Material)) { movementCost += movementProfile.CalculateMaterialMovementCost(actor.Race.Material); } } return(movementCost); }
public static Data WorldToTerrain(WorldSerialization blob) { Data worldData = new Data(); Vector3 terrainSize = new Vector3(blob.world.size, 1000, blob.world.size); worldData.terrainMap = new TerrainMap <short>(blob.GetMap("terrain").data, 1); TerrainMap <short> heightMap = new TerrainMap <short>(blob.GetMap("height").data, 1); worldData.splatMap = new TerrainMap <byte>(blob.GetMap("splat").data, 8); worldData.alphaMap = new TerrainMap <byte>(blob.GetMap("alpha").data, 1); worldData.biomeMap = new TerrainMap <byte>(blob.GetMap("biome").data, 4); worldData.topologyMap = new TerrainMap <int>(blob.GetMap("topology").data, 1); worldData.waterMap = new TerrainMap <short>(blob.GetMap("water").data, 1); worldData.pathData = new List <ProtoBuf.PathData>(blob.world.paths); worldData.prefabData = new List <ProtoBuf.PrefabData>(blob.world.prefabs); worldData.resolution = heightMap.res; worldData.size = terrainSize; Debug.Log($"Load : World Size {terrainSize.x} Heightmap Res {heightMap.res} Texture Res {worldData.splatMap.res}"); worldData.landHeightMap = ArrayUtils.ShortToFloatArray(worldData.terrainMap); blob.Clear(); return(worldData); }
// This needs to be separate from Initialize because it is also needed by the ghost platoon public void InitializeGhost(TerrainMap map) { Data = gameObject.GetComponent <DataComponent>(); Mobility = Data.MobilityData; _moveStrategy = new VehicleMovementStrategy( Data, map, transform, Mobility); }
protected void PlaceRoom(Point location, DungeonPrefab room, TerrainMap terrainMap) { // Create a copy of the room var roomToPlace = (DungeonPrefab)room.Clone(); // Offset the room origin to the new location roomToPlace.SetLocation(location); // Loop for each cell in the room foreach (var roomLocation in room.Locations) { // Translate the room cell location to its location in the dungeon var dungeonLocation = new Point(location.X + roomLocation.X, location.Y + roomLocation.Y); if (room[roomLocation] != null) { // Copy the tiles from the room to the dungeon terrainMap[dungeonLocation] = room[roomLocation]; } } // Add the lightsources to the dungeon foreach (var lightSource in room.LightSources) { var lightSourceToPlace = (LightSource)lightSource.Clone(); lightSourceToPlace.Location.Coordinate = new Point(lightSourceToPlace.Location.Coordinate.X + location.X, lightSourceToPlace.Location.Coordinate.Y + location.Y); terrainMap.LightSources.Add(lightSourceToPlace); } terrainMap.Prefabs.Add(roomToPlace); }
public void FindAdjacentCellsRange1() { var map = new TerrainMap(new ShortestPath()); map.InitializeBoard(10, 10); var result = map.FindAdjacentCells(3, 3, 0, 1); Assert.Equal(6, result.Count); Assert.Equal(2, result[0].Col); Assert.Equal(4, result[0].Row); Assert.Equal(2, result[1].Col); Assert.Equal(3, result[1].Row); Assert.Equal(3, result[2].Col); Assert.Equal(4, result[2].Row); Assert.Equal(3, result[3].Col); Assert.Equal(2, result[3].Row); Assert.Equal(4, result[4].Col); Assert.Equal(4, result[4].Row); Assert.Equal(4, result[5].Col); Assert.Equal(3, result[5].Row); }
protected virtual IEnumerable <PathFindingNode> GetNodeNeighbours(TerrainMap terrain, IList <IActor> actors, IMovementProfile movementProfile, PathFindingNode node, Point locationTo) { var picker = new DirectionPicker(Direction.Northwest, 100, movementProfile.AvailableDirections); while (picker.HasDirectionToPick) { Direction direction = picker.PickRandomDirection(); if (terrain.HasAdjacentLocation(node.Location, direction)) { Point targetLocation = terrain.GetTargetLocation(node.Location, direction).Value; if (LocationIsTraversable(terrain, actors, movementProfile, targetLocation, locationTo)) { yield return new PathFindingNode { Location = direction.ApplyTransform(node.Location), Direction = direction, MovementCost = CalculateLocationMovementCost(terrain, actors, movementProfile, targetLocation, locationTo) } } ; } } }
public TemperatureMap(int xSize, int ySize, float[,] grid, TerrainMap terrainmap) { this.terrainmap = terrainmap; this.xSize = xSize; this.ySize = ySize; this.grid = grid; }
static public void AutoConnect() { if (!HasValidTerrains()) { return; } ClearConnectivity(); TerrainGroups TerrainGroups = CollectTerrains(); if (TerrainGroups == null) { return; } foreach (var group in TerrainGroups) { TerrainMap terrains = group.Value; foreach (var tile in terrains.m_terrainTiles) { TerrainMap.TileCoord coords = tile.Key; Terrain center = terrains.GetTerrain(coords.tileX, coords.tileZ); Terrain left = terrains.GetTerrain(coords.tileX - 1, coords.tileZ); Terrain right = terrains.GetTerrain(coords.tileX + 1, coords.tileZ); Terrain top = terrains.GetTerrain(coords.tileX, coords.tileZ + 1); Terrain bottom = terrains.GetTerrain(coords.tileX, coords.tileZ - 1); center.SetNeighbors(left, top, right, bottom); } } }
public StrategyGameData() { Rules = new StrategyGameRules(); TerrainHeight = 300; TerrainWidth = 300; terrain = new TerrainMap(TerrainWidth, TerrainHeight); Fog = new WrappingFogMap(new FogMap(TerrainWidth, TerrainHeight), GridNavigation.CreateNavigator(RenderType.Grid).Wrap(TerrainWidth, TerrainHeight)); Settlements = new SettlementManager(); Players = new List <Player> { new Player("Barbarian", PlayerColor.Red, Culture.Celtic), new Player("Player A", PlayerColor.Green, Culture.Classical), new Player("Player B", PlayerColor.Blue, Culture.Celtic) }; var r = new MapReader(Rules); r.Map = terrain; r.ReadTerrain(new StringReader(MapData.TerrainData), 0, 0, TerrainWidth, TerrainHeight); r.ReadRoads(new StringReader(MapData.RoadData), 0, 0, TerrainWidth, TerrainHeight); r.ReadRivers(new StringReader(MapData.RiverData), 0, 0, TerrainWidth, TerrainHeight); r.ReadImprovement(new StringReader(MapData.ImprovementData), 0, 0, TerrainWidth, TerrainHeight); r.ReadResources(new StringReader(MapData.ResourceData), 0, 0, TerrainWidth, TerrainHeight); AddSettlement(new Settlement("Capital City", new MapCoordinate(7, 13), 1, 4000, true)); AddSettlement(new Settlement("Satellite Settlement", new MapCoordinate(20, 14), 2, 2000, false)); // Explicitly set the initial visible tracker to the location of one of the cities // here so that the visibility marking works correctly. Fog.MarkRangeVisible(0, 0, 2); MousePosition = new MapCoordinate(7, 13); }
// Gives the relative speed of a unit with the given MobilityType at the given location // Relative speed is 0 if the terrain is impassible and 1 for road, otherwise between 0 and 1 // If radius > 0, check for units in the way, otherwise just look at terrain public float GetUnitSpeed(Terrain terrain, TerrainMap map, Vector3 location, float unitRadius, Vector3 direction) { // This is a slow way to do it, and we will probably need a fast, generic method to find units within a given distance of a location if (unitRadius > 0f) { // TODO use unit list from game/match session // TODO maybe move this logic into its own method? GameObject[] units = GameObject.FindGameObjectsWithTag(UnitBehaviour.UNIT_TAG); foreach (GameObject unit in units) { float dist = Vector3.Distance(location, unit.transform.position); if (dist < unitRadius + unit.GetComponent <UnitBehaviour>().Data.radius) { return(0f); } } } // Find unit speed on terrain int terrainType = map.GetTerrainType(location); float speed = 0f; if (terrainType == TerrainMap.BRIDGE) { speed = 1.0f; } else if (terrainType == TerrainMap.BUILDING) { speed = 0.0f; } else if (terrainType == TerrainMap.ROAD) { speed = 1.0f; } else if (terrainType == TerrainMap.FOREST) { speed = ForestSpeed; } else if (terrainType == TerrainMap.PLAIN) { speed = PlainSpeed; } else if (terrainType == TerrainMap.WATER) { speed = WaterSpeed; } if (speed <= 0) { return(0f); } if (terrainType == TerrainMap.BRIDGE || terrainType == TerrainMap.WATER) { return(speed); } return(speed * GetSlopeFactor(terrain, location, direction)); }
public SatelliteRenderer(TerrainMap terrainmap, TemperatureMap temperaturemap, bool snow = false) { this.terrainmap = terrainmap; this.temperaturemap = temperaturemap; snowFunction = new LineFunction(-10, 0.75f, -30, 1); snow = false; }
public virtual void GenerateRooms(TerrainMap terrainMap) { var noOfRoomsToGenerate = Rng.Next(MinNoOfRooms, MaxNoOfRooms); for (var roomCounter = 0; roomCounter < noOfRoomsToGenerate; roomCounter++) { var room = CreateRandomRoom(MinRoomSize, MaxRoomSize); var bestRoomPlacementScore = int.MinValue; Point?bestRoomPlacementLocation = null; foreach (Point currentRoomPlacementLocation in terrainMap.Locations) { int currentRoomPlacementScore = CalculateRoomPlacementScore(currentRoomPlacementLocation, room, terrainMap); if (currentRoomPlacementScore > bestRoomPlacementScore) { bestRoomPlacementScore = currentRoomPlacementScore; bestRoomPlacementLocation = currentRoomPlacementLocation; } } // Create room at best room placement cell if ((bestRoomPlacementLocation != null) && (bestRoomPlacementScore != int.MinValue)) { PlaceRoom(bestRoomPlacementLocation.Value, room, terrainMap); } } }
public MoveCommand(IActor actor, Direction direction, TerrainMap terrain, IList <IActor> actors) { this.direction = direction; this.actor = actor; this.actors = actors; this.terrain = terrain; }
public void UpdateVisibilityMap(TerrainMap terrain, LightMap lightmap, Point origin) { // Reset the visible flag of the previous visible points if (visiblePoints != null) { foreach (var visiblePoint in visiblePoints) { this[visiblePoint.Location.Coordinate].IsVisible = false; } } // Calculate new visible Fov visiblePoints = fovAlgorithm.CalculateFov(terrain, origin, fovProfile); // Evaluate each visible point against the lightmap // Only lit tiles are visible foreach (var visiblePoint in visiblePoints) { if (!fovProfile.IsVisible(lightmap[visiblePoint.Location.Coordinate].Colour)) { continue; } this[visiblePoint.Location.Coordinate].IsVisible = true; this[visiblePoint.Location.Coordinate].WasSeen = true; } }
public override void OnSceneGUI(Terrain terrain, IOnSceneGUI editContext) { if ((Event.current.type == EventType.MouseUp || Event.current.type == EventType.MouseDown) && (Event.current.button == 2 || Event.current.alt) || terrain.terrainData == null) { return; } Quaternion rot = new Quaternion(); rot.eulerAngles = new Vector3(90, 00, 0); Handles.color = new Color(0.9f, 1.0f, 0.8f, 1.0f); Vector3 size = terrain.terrainData.size; TerrainMap mapGroup = TerrainMap.CreateFromPlacement(terrain); if (mapGroup == null) { return; } foreach (TerrainTileCoord coord in mapGroup.terrainTiles.Keys) { int x = coord.tileX; int y = coord.tileZ; Terrain t = mapGroup.GetTerrain(x, y); if (t == null) { continue; } Terrain left = mapGroup.GetTerrain(x - 1, y); Terrain right = mapGroup.GetTerrain(x + 1, y); Terrain top = mapGroup.GetTerrain(x, y + 1); Terrain bottom = mapGroup.GetTerrain(x, y - 1); Vector3 pos = t.transform.position + 0.5f * new Vector3(size.x, 0, size.z); if ((bottom == null) && Handles.Button(pos + new Vector3(0, 0, -size.z), rot, 0.5f * size.x, 0.5f * size.x, Handles.RectangleHandleCapWorldSpace)) { CreateNeighbor(terrain, t.transform.position + Vector3.back * size.z); } if ((top == null) && Handles.Button(pos + new Vector3(0, 0, size.z), rot, 0.5f * size.x, 0.5f * size.x, Handles.RectangleHandleCapWorldSpace)) { CreateNeighbor(terrain, t.transform.position + Vector3.forward * size.z); } if ((right == null) && Handles.Button(pos + new Vector3(size.x, 0, 0), rot, 0.5f * size.x, 0.5f * size.x, Handles.RectangleHandleCapWorldSpace)) { CreateNeighbor(terrain, t.transform.position + Vector3.right * size.x); } if ((left == null) && Handles.Button(pos + new Vector3(-size.x, 0, 0), rot, 0.5f * size.x, 0.5f * size.x, Handles.RectangleHandleCapWorldSpace)) { CreateNeighbor(terrain, t.transform.position + Vector3.left * size.x); } } }
public override void RenderTiles(TerrainMap map, ref int totalTriangles) { if (fullVboId == -1) { Console.WriteLine("Generating with textures!"); fullVboId = GLUtils.GenBuffer(); var sw = Stopwatch.StartNew(); VertexPos3Tex2[] vertices = BuildTerrain(map, ref triangles); long elapsed = sw.ElapsedMilliseconds; sw.Stop(); Console.WriteLine("Took " + elapsed + " ms to generate the map."); int size = vertices.Length * VertexPos3Tex2.Stride; GL.Arb.BindBuffer(BufferTargetArb.ArrayBuffer, fullVboId); GL.Arb.BufferData(BufferTargetArb.ArrayBuffer, new IntPtr(size), vertices, BufferUsageArb.StaticDraw); fullVerticesCount = vertices.Length; } GL.EnableClientState(ArrayCap.VertexArray); GL.EnableClientState(ArrayCap.TextureCoordArray); GL.Arb.BindBuffer(BufferTargetArb.ArrayBuffer, fullVboId); GL.VertexPointer(3, VertexPointerType.Float, VertexPos3Tex2.Stride, new IntPtr(0)); GL.TexCoordPointer(2, TexCoordPointerType.Float, VertexPos3Tex2.Stride, new IntPtr(12)); GL.DrawArrays(BeginMode.Quads, 0, fullVerticesCount); GL.DisableClientState(ArrayCap.TextureCoordArray); GL.DisableClientState(ArrayCap.VertexArray); totalTriangles = triangles; }
public void UseRoads() { //https://www.redblobgames.com/pathfinding/a-star/introduction.html var shortest = new ShortestPath(); var map = new TerrainMap(shortest); map.InitializeBoard(6, 6); map[1, 2].Roads = RoadType.Road2 | RoadType.Road5; map[2, 3].Roads = RoadType.Road2 | RoadType.Road5; map[3, 3].Roads = RoadType.Road3 | RoadType.Road5; map[4, 3].Roads = RoadType.Road2 | RoadType.Road6; map[5, 3].Roads = RoadType.Road5 | RoadType.Road1; map[5, 4].Roads = RoadType.Road1 | RoadType.Road4; map[5, 5].Roads = RoadType.Road4; shortest.ComputeShortestPath(map, 1, 2, 5, 5, 0); Assert.Equal(new Offset(2, 3), shortest.WayPoint[0]); Assert.Equal(new Offset(3, 3), shortest.WayPoint[1]); Assert.Equal(new Offset(4, 3), shortest.WayPoint[2]); Assert.Equal(new Offset(5, 3), shortest.WayPoint[3]); Assert.Equal(new Offset(5, 4), shortest.WayPoint[4]); Assert.Equal(new Offset(5, 5), shortest.WayPoint[5]); }
/// <summary>Parses World Serialization and converts into MapInfo struct.</summary> /// <param name="world">Serialization of the map file to parse.</param> public static MapInfo WorldToTerrain(WorldSerialization world) { MapInfo terrains = new MapInfo(); var terrainSize = new Vector3(world.world.size, 1000, world.world.size); var terrainMap = new TerrainMap <short>(world.GetMap("terrain").data, 1); var heightMap = new TerrainMap <short>(world.GetMap("height").data, 1); var waterMap = new TerrainMap <short>(world.GetMap("water").data, 1); var splatMap = new TerrainMap <byte>(world.GetMap("splat").data, 8); var topologyMap = new TerrainMap <int>(world.GetMap("topology").data, 1); var biomeMap = new TerrainMap <byte>(world.GetMap("biome").data, 4); var alphaMap = new TerrainMap <byte>(world.GetMap("alpha").data, 1); terrains.topology = topologyMap; terrains.pathData = world.world.paths.ToArray(); terrains.prefabData = world.world.prefabs.ToArray(); terrains.terrainRes = heightMap.res; terrains.splatRes = Mathf.Clamp(Mathf.NextPowerOfTwo((int)(world.world.size * 0.5f)), 16, 2048); terrains.size = terrainSize; var heightTask = Task.Run(() => ShortMapToFloatArray(heightMap)); var waterTask = Task.Run(() => ShortMapToFloatArray(waterMap)); terrains = ConvertMaps(terrains, splatMap, biomeMap, alphaMap); Task.WaitAll(heightTask, waterTask); terrains.land.heights = heightTask.Result; terrains.water.heights = waterTask.Result; return(terrains); }
public MainForm(String lp = "") { InitializeComponent(); this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.MainForm_FormClosing); this.LocationChanged += new System.EventHandler(this.MainForm_LocationChanged); this.Resize += new System.EventHandler(this.MainForm_Resize); this.StartPosition = FormStartPosition.Manual; this.Location = Properties.Settings.Default.Location; this.WindowState = Properties.Settings.Default.State; if (this.WindowState == FormWindowState.Normal) this.Size = Properties.Settings.Default.Size; TerrainMap.DefineBoard(@"Terrain\map.txt"); tm = new TerrainMap(); LoadMap(); //Main panel hexgridPanel1.Scales = new List<float>() { 1.000F }.AsReadOnly(); hexgridPanel1.ScaleIndex = hexgridPanel1.Scales .Select((f, i) => new { value = f, index = i }) .Where(s => s.value == 1.0F) .Select(s => s.index).FirstOrDefault(); hexgridPanel1.Host = tm; hexgridPanel1.Size = hexgridPanel1.MapSizePixels; //Minimap minimapScale = Math.Min((float)pbMinimap.Height / (float)hexgridPanel1.Height, (float)pbMinimap.Width / (float)hexgridPanel1.Width); pbMinimap.Width = (int)(hexgridPanel1.Width * minimapScale); pbMinimap.Height = (int)(hexgridPanel1.Height * minimapScale); clickCoords = HexCoords.NewUserCoords(-1, -1); loggedPlayerName = lp; isPlayerTurn = (turn.CurrentPlayer.Name == loggedPlayerName || loggedPlayerName == ""); btnEndTurn.Enabled = isPlayerTurn; if (loggedPlayerName != "") btnResolve.Enabled = false; btnUndo.Enabled = false; UpdateLos(); UpdateSummary(); UpdateResources(); //this.MouseWheel += new MouseEventHandler(hexgridPanel1_MouseWheel); }
public override void Paint(Graphics g, TerrainMap tm) { if (tm.IsOnboard(Coords) && tm.Los[Coords]) { var container = g.BeginContainer(); tm.TranslateGraphicsToHex(g, Coords); g.DrawImage(_bmp, tm.BoardHexes[Coords].Board.HexgridPath.GetBounds()); if (tm.ShowHexgrid) g.DrawPath(Pens.Black, tm.HexgridPath); g.EndContainer(container); } }
public abstract void Paint(Graphics g, TerrainMap tm);
private void OnEnable() { t = (TerrainMap)target; }
public bool CanBuildRoad(TerrainMap tm) { for (int i = 0; i <= 5; i++) { Hexside hs = (Hexside)i; TerrainGridHex nhex = (TerrainGridHex)tm.BoardHexes[Coords].Neighbour(hs); Town t = tm.GetTown(nhex.Coords); Castle c = tm.GetCastle(nhex.Coords); if (nhex.SpecialType == "Road" || t != null || c != null) return true; } return false; }
private Texture GetTextureFor(BlockType block, ComputeBuffer heightMap, TerrainMap normals, Vector2i chunkPos) { var settings = _blockSettings[block]; Texture flat = settings.FlatTexture.Texture; Texture steep = settings.SteepTexture.Texture; var shader = _meshSettings.BlockShader; var kernelName = "Bare"; if (!settings.FlatTexture.BypassMix) kernelName = "Mix"; if (!settings.BypassTriplanar) kernelName += "Tri"; if (!settings.BypassTint) kernelName += "Tint"; var kernelId = shader.FindKernel(kernelName); shader.SetTexture(kernelId, "Texture", flat); if (!settings.FlatTexture.BypassMix) { shader.SetTexture(kernelId, "Noise", _meshSettings.NoiseTexture); //mixShader.SetTexture(kernelId, "MixTexture", settings.MixTexture); shader.SetFloat("MixNoiseScale", settings.FlatTexture.MixNoiseScale); shader.SetFloat("MixTextureScale", settings.FlatTexture.MixTextureScale); shader.SetFloat("MixTextureAngle", settings.FlatTexture.MixTextureAngle); shader.SetInts("ChunkPos", chunkPos.X, chunkPos.Z); } if (!settings.BypassTriplanar) { shader.SetTexture(kernelId, "SteepTexture", steep); shader.SetBuffer(kernelId, "HeightMap", heightMap); shader.SetTexture(kernelId, "Normals", normals.Map); shader.SetInt("Border", normals.Border); shader.SetFloat("SteepAngleFrom", settings.SteepAngles.x); shader.SetFloat("SteepAngleTo", settings.SteepAngles.y); } if (!settings.BypassTint) { shader.SetFloat("TintNoiseScale", settings.TintNoiseScale); shader.SetVector("FromColor", settings.TintFrom); shader.SetVector("ToColor", settings.TintTo); } var result = GetRenderTexture(); shader.SetTexture(kernelId, "Result", result); //mixShader.SetTexture(kernelId, "ResultNormals", resultNrm); shader.Dispatch(kernelId, result.width / 8, result.height / 8, 1); return result; }
public List<TerrainGridHex> ResourceHexes(TerrainMap tm) { int range = _level; List<TerrainGridHex> retVal = new List<TerrainGridHex>(); List<TerrainGridHex> hexes; retVal.Add((TerrainGridHex)tm.BoardHexes[Coords]); for (int i = 1; i <= range; i++) { hexes = new List<TerrainGridHex>(); hexes.AddRange(retVal); foreach (TerrainGridHex hex in hexes) { for (int j = 0; j <= 5; j++) { Hexside hs = (Hexside)j; TerrainGridHex nhex = (TerrainGridHex)hex.Neighbour(hs); if (!retVal.Contains(nhex) && nhex.IsOnboard()) retVal.Add(nhex); } } } return retVal; }
public void Move(HexCoords toCoords, TerrainMap tm) { Landmark lm = new Landmark(Coords, tm); double distance = lm.HexDistance(toCoords); Coords = toCoords; _moveLeft -= distance; Save(); }
public Map() { terrain = new TerrainMap[320, 240]; TerrainBounds = new RectangleF(Vector.Zero, new Vector(320, 240)); }
private void RefreshTerrainMapVars() { heightMap = GetHeightMap(); alphaMap = GetAlphaMap(); detailMap = GetDetailMap(); }