public NavMesh(TerrainTile tile, NavMeshPolygon[] polys, Vector3[] vertices, int[] indices) { Tile = tile; Polygons = polys; Vertices = vertices; Indices = indices; }
public void Render(TerrainTile tile, TerrainGlobal terrainGlobal, Matrix4 projection, Matrix4 view, Vector3 eyePos) { var boxparam = tile.GetBoxParam(); Vector3 eyePosTileCoords = Vector4.Transform(new Vector4(eyePos, 0.0f), tile.InverseModelMatrix).Xyz; GL.Enable(EnableCap.CullFace); GL.CullFace(CullFaceMode.Front); // we only want to render back-faces tile.HeightTexture.Bind(TextureUnit.Texture0); tile.ParamTexture.Bind(TextureUnit.Texture1); tile.NormalTexture.Bind(TextureUnit.Texture2); this.boundingBoxProgram .UseProgram() .SetUniform("projection_matrix", projection) .SetUniform("model_matrix", tile.ModelMatrix) .SetUniform("view_matrix", view) .SetUniform("heightTex", 0) .SetUniform("paramTex", 1) .SetUniform("normalTex", 2) .SetUniform("eyePos", eyePos) .SetUniform("nEyePos", eyePosTileCoords) .SetUniform("boxparam", boxparam); this.vertexVBO.Bind(this.boundingBoxProgram.VariableLocation("vertex")); this.boxcoordVBO.Bind(this.boundingBoxProgram.VariableLocation("in_boxcoord")); this.indexVBO.Bind(); GL.DrawElements(BeginMode.Triangles, this.indexVBO.Length, DrawElementsType.UnsignedInt, 0); Sampler.Unbind(TextureUnit.Texture0); }
public override void Draw() { if (template == null) return; var grid = Game.ModData.Manifest.Get<MapGrid>(); var ts = grid.TileSize; var gridType = grid.Type; var scale = GetScale(); var sb = new Rectangle((int)(scale * bounds.X), (int)(scale * bounds.Y), (int)(scale * bounds.Width), (int)(scale * bounds.Height)); var origin = RenderOrigin + new int2((RenderBounds.Size.Width - sb.Width) / 2 - sb.X, (RenderBounds.Size.Height - sb.Height) / 2 - sb.Y); var i = 0; for (var y = 0; y < Template.Size.Y; y++) { for (var x = 0; x < Template.Size.X; x++) { var tile = new TerrainTile(Template.Id, (byte)(i++)); var tileInfo = tileset.GetTileInfo(tile); // Empty tile if (tileInfo == null) continue; var sprite = worldRenderer.Theater.TileSprite(tile, 0); var size = new float2(sprite.Size.X * scale, sprite.Size.Y * scale); var u = gridType == MapGridType.Rectangular ? x : (x - y) / 2f; var v = gridType == MapGridType.Rectangular ? y : (x + y) / 2f; var pos = origin + scale * (new float2(u * ts.Width, (v - 0.5f * tileInfo.Height) * ts.Height) - 0.5f * sprite.Size); Game.Renderer.SpriteRenderer.DrawSprite(sprite, pos, worldRenderer.Palette(Palette), size); } } }
//private Vector3 MinVertex; //private Vector3 MaxVertex; public QuadTreeNode(QuadTreeNode parent, TerrainTile tile, int tileSize, int depth, bool checkFrustum, Vector2 offset, params Vector4[] v) { this.tile = tile; this.checkFrustum = checkFrustum; this.depth = depth; this.tileSize = tileSize; this.Offset = offset; //if (parent != null) //{ // //TileOffset = parent.TileOffset; //} //else //{ // // get tile offset in world space // TileOffset = Vector4.Transform(new Vector4(0f,0f,0f,1f), tile.InverseModelMatrix); //} for (int i = 0; i < 8; i++) { vertex[i] = v[i]; } BottomCentre = (vertex[(int)Corner.BottomNearLeft] + vertex[(int)Corner.BottomFarRight]) * 0.5f; TopCentre = (vertex[(int)Corner.TopNearLeft] + vertex[(int)Corner.TopFarRight]) * 0.5f; }
List<GameObject> TileArray = new List<GameObject>(); //used for storing the gameobjects themselves. Whenever updating the tile, be sure to call tile.updateObject() to avoid a desync. #endregion Fields #region Methods // //Other Methods public static bool CheckPassable(TerrainTile tile) { var top = tile.topper; //check for toppers or inpassable terrain type. var type = tile.terrainType; switch (top) { case TerrainTileParent.Topper.Tree: { return false; } default: { switch (type) { case TerrainTileParent.TerrainType.Empty: { return true; } default: { return false; } } } } }
public Map(int Width, int Height, string TerrainName) { width = Width; height = Height; terrainName = TerrainName; System.Random rnd = new System.Random(); // Create map m_Tiles = new TerrainTile[width * height]; for (int j = 0; j < height; ++j) { for (int i = 0; i < width; ++i) { // For first and last row and first and last collumn set // to non-walkable TerrainTile.Type tile_type = (i > 0 && j % 2 == 0) || (j % 2 == 1 && i < width - 1) ? TerrainTile.Type.REGULAR : TerrainTile.Type.NONE; TerrainTile tile = new TerrainTile(i, j, tile_type); // Set random variant // tile.variant = (byte)rnd.Next(0, 7); tile.variant = 0; m_Tiles[i + j * width] = tile; } } // Set some debug tile SetTileTerrainType(GetTile(2, 3), 1); SetTileTerrainType(GetTile(13, 6), 1); SetTileTerrainType(GetTile(width - 1, height - 1), 1); }
public IEnumerable<PatchDescriptor> GetPatches(TerrainTile tile, Frustum f, Vector3 eyeWorld) { // create root node var root = new QuadTreeNode(tile); return root.GetPatches(eyeWorld,f); }
public static byte[] Convert(string json) { var obj = JsonConvert.DeserializeObject<json_dat>(json); var dat = ZlibStream.UncompressBuffer(obj.data); Dictionary<short, TerrainTile> tileDict = new Dictionary<short, TerrainTile>(); for (int i = 0; i < obj.dict.Length; i++) { var o = obj.dict[i]; tileDict[(short)i] = new TerrainTile() { TileId = o.ground == null ? (short)0xff : XmlDatas.IdToType[o.ground], TileObj = o.objs == null ? null : o.objs[0].id, Name = o.objs == null ? "" : o.objs[0].name ?? "", Terrain = TerrainType.None, Region = o.regions == null ? TileRegion.None : (TileRegion)Enum.Parse(typeof(TileRegion), o.regions[0].id.Replace(' ', '_')) }; } var tiles = new TerrainTile[obj.width, obj.height]; using (NReader rdr = new NReader(new MemoryStream(dat))) for (int y = 0; y < obj.height; y++) for (int x = 0; x < obj.width; x++) { tiles[x, y] = tileDict[rdr.ReadInt16()]; } return Export(tiles); }
public int CostToTile(TerrainTile tile) { var idx = TileToIndex(tile); if (idx < _distance.Length) { return _distance[idx]; } return int.MaxValue; }
public void AddTile(CPos cell, TerrainTile tile) { map.CustomTerrain[cell] = map.Rules.TileSet.GetTerrainIndex(tile); // Terrain tiles define their origin at the topleft var s = theater.TileSprite(tile); dirty[cell] = new Sprite(s.Sheet, s.Bounds, float2.Zero, s.Channel, s.BlendMode); }
private TerrainTile pickNeighbor(TerrainTile[,] tiles, int row, int col) { int neighborRow = (row == 0) ? (row + 1) : (row - 1); int neighborCol = (col == 0) ? (col + 1) : (col - 1); var neighbor = tiles[neighborRow, neighborCol]; // TODO: this isn't perfect. maybe use breadth-first search return (neighbor.WasTerrainApplied) ? neighbor : pickNeighbor(tiles, neighborRow, neighborCol); }
// Use this for initialization void Start() { health = maxHealth; curTile = null; engine = (EnvironmentEngine) FindObjectOfType(typeof(EnvironmentEngine)); terrain = (PrettyTerrain) FindObjectOfType(typeof(PrettyTerrain)); }
public void HandleTileClick(TerrainTile tile) { var nextstate = _state.HandleTileClick(tile); if (nextstate != null) { // state transition requested _state.OnExit(); _state = nextstate; } }
private void AddInitalTile(int index) { var tileGameObject = (GameObject)Instantiate(trackPrefab); var newTileCoordinates = LocationToCoordinates(0, index); tileGameObject.transform.Translate(newTileCoordinates); var newTile = new TerrainTile(tileGameObject, 0, index, Direction.Up, index, TerrainTileType.Direct); _terrainTiles.Add(newTile); }
void Update() { Vector2 tileInd = terrain.tileFromPos(transform.localPosition); try{ curTile = engine.mapgen.tiles[(int)tileInd.x,(int)tileInd.y]; }catch{ curTile = null; } }
static CPos FindEdge(Surface s, CPos p, CVec d, TerrainTile replace) { for (;;) { var q = p + d; if (!s.Map.Contains(q)) return p; if (s.Map.MapTiles.Value[q].Type != replace.Type) return p; p = q; } }
public void ExportRecastInputMesh(TerrainTile tile, string filename) { if (File.Exists(filename)) return; // skip existing files var verts = tile.TerrainVertices; var indices = tile.TerrainIndices; var start = DateTime.Now; Console.Write("Writing input file {0}...", filename); using (var file = new StreamWriter(filename)) { foreach (var vertex in verts) { var v = vertex; RecastUtil.TransformWoWCoordsToRecastCoords(ref v); file.WriteLine("v {0} {1} {2}", v.X, v.Y, v.Z); } // write faces var terrain = tile.Terrain; for (var i = 0; i < indices.Length; i += 3) { // ignore triangles that are completely submerged in a liquid var v1 = verts[indices[i]]; var v2 = verts[indices[i+1]]; var v3 = verts[indices[i+2]]; if (terrain.GetLiquidType(v1) != LiquidType.None && terrain.GetLiquidType(v2) != LiquidType.None && terrain.GetLiquidType(v3) != LiquidType.None) { var triBottom = float.MaxValue; var triTop = float.MinValue; triBottom = Math.Min(triBottom, v1.Z); triBottom = Math.Min(triBottom, v2.Z); triBottom = Math.Min(triBottom, v3.Z); triTop = Math.Max(triTop, v1.Z); triTop = Math.Max(triTop, v2.Z); triTop = Math.Max(triTop, v3.Z); var triHeightAvg = (triTop - triBottom)*0.5f; var liqHeight = terrain.GetLiquidHeight(v1); var avgTriLiqDepth = liqHeight - triHeightAvg; if (avgTriLiqDepth > 1.0f) continue; } //file.WriteLine("f {0} {1} {2}", indices[i] + 1, indices[i + 1] + 1, indices[i + 2] + 1); file.WriteLine("f {0} {1} {2}", indices[i + 2] + 1, indices[i + 1] + 1, indices[i] + 1); } } Console.WriteLine("Done. - Exported {0} triangles in: {1:0.000}s", indices.Length / 3, (DateTime.Now - start).TotalSeconds); }
public Sprite TileSprite(TerrainTile r) { Sprite[] template; if (!templates.TryGetValue(r.Type, out template)) return missingTile; if (r.Index >= template.Length) return missingTile; return template[r.Index]; }
public static byte[] ConvertMakeWalls(RealmManager manager, string json) { json_dat obj = JsonConvert.DeserializeObject<json_dat>(json); byte[] dat = ZlibStream.UncompressBuffer(obj.data); Dictionary<ushort, TerrainTile> tileDict = new Dictionary<ushort, TerrainTile>(); for (int i = 0; i < obj.dict.Length; i++) { loc o = obj.dict[i]; tileDict[(ushort)i] = new TerrainTile { TileId = o.ground == null ? (ushort)0xff : manager.GameData.IdToObjectType[o.ground], TileObj = o.objs == null ? null : o.objs[0].id, Name = o.objs == null ? "" : o.objs[0].name ?? "", Terrain = TerrainType.None, Region = o.regions == null ? TileRegion.None : (TileRegion)Enum.Parse(typeof(TileRegion), o.regions[0].id.Replace(' ', '_')) }; } TerrainTile[,] tiles = new TerrainTile[obj.width, obj.height]; using (NReader rdr = new NReader(new MemoryStream(dat))) for (int y = 0; y < obj.height; y++) for (int x = 0; x < obj.width; x++) { tiles[x, y] = tileDict[(ushort)rdr.ReadInt16()]; tiles[x, y].X = x; tiles[x, y].Y = y; } foreach (TerrainTile i in tiles) { if (i.TileId == 0xff && i.TileObj == null) { bool createWall = false; for (int ty = -1; ty <= 1; ty++) for (int tx = -1; tx <= 1; tx++) try { if (tiles[i.X + tx, i.Y + ty].TileId != 0xff) createWall = true; } catch { } if (createWall) tiles[i.X, i.Y].TileObj = "Grey Wall"; } } return WorldMapExporter.Export(tiles); }
private static Bitmap RenderColorBmp(TerrainTile[,] tiles) { int w = tiles.GetLength(0); int h = tiles.GetLength(1); Bitmap bmp = new Bitmap(w, h); BitmapBuffer buff = new BitmapBuffer(bmp); buff.Lock(); for (int y = 0; y < w; y++) for (int x = 0; x < h; x++) buff[x, y] = TileTypes.color[tiles[x, y].TileId]; buff.Unlock(); return bmp; }
public override void Apply(TerrainTile[,] tiles) { for (int row = 0; row < tiles.GetLength(0); row++) { for (int col = 0; col < tiles.GetLength(1); col++) { var tile = tiles[row, col]; if (!tile.WasTerrainApplied) { var neighbor = pickNeighbor(tiles, row, col); var mat = neighbor.renderer.sharedMaterial; var cost = neighbor.MoveCost; tile.SetTerrain(cost, mat); } } } }
private void AddCoin(TerrainTile tile) { var coin = (GameObject)Instantiate(coinPrefab); coin.transform.Translate(tile.GameObject.transform.position); //NOTE: assume obstacle has sime size in all directions var halfObstacleSize = coin.collider.bounds.size.x / 2.0f; var possibleMoveRange = GlobalConstants.TerrainTileSize / 2.0f - halfObstacleSize; var shiftX = Random.Range(-possibleMoveRange, possibleMoveRange); var shiftY = Random.Range(-possibleMoveRange, possibleMoveRange); coin.transform.Translate(shiftX, 0, shiftY); //add as child to tile coin.transform.parent = tile.GameObject.transform; }
public override void Apply(TerrainTile[,] tiles) { _tiles = tiles; _numRows = tiles.GetLength(0); _numCols = tiles.GetLength(1); int minRow = Mathf.Max(0, Row - Range); int maxRow = Mathf.Min(_numRows, Row + Range); int minCol = Mathf.Max(0, Col - Range); int maxCol = Mathf.Min(_numCols, Col + Range); int nSplotches = (int)(Density * Range * Range); for (int i = 0; i < nSplotches; i++) { int row = Random.Range(minRow, maxRow); int col = Random.Range(minCol, maxCol); PlaceBuilding(row, col, BuildingSize, WallPrefab, Direction.North); } }
public Stack<TerrainTile> PathToTile(TerrainTile endTile) { int idx = TileToIndex(endTile); if (_distance[idx] == int.MaxValue) { return null; } else { var route = new Stack<TerrainTile>(); var startIdx = CoordsToIndex(_sourceRow, _sourceCol); while (idx != startIdx) { route.Push(IndexToTile(idx)); idx = _parent[idx]; } return route; } }
public static void SetHeights(TerrainTile tile, Texture2D tex) { //Color[] colormap = tex.GetPixels(0,0,tex.width, tex.width); float[,] heightmap = new float[tex.width, tex.height]; for (int y = 0; y < tex.height; y++) { for (int x = 0; x < tex.width; x++) { heightmap[y, x] = DecodeFloatRGBA(tex.GetPixel(x, y)); } } //TerrainData tData = GetComponent<Terrain>().terrainData; //GetComponent<TerrainCollider>().terrainData = tData; tile.TData.SetHeights(0, 0, heightmap); tile.Terrain.gameObject.name = "x:" + tile.Index.x + " z:" + tile.Index.z; }
public override void Apply(TerrainTile[,] tiles) { _tiles = tiles; _numRows = tiles.GetLength(0); _numCols = tiles.GetLength(1); int minRow = Mathf.Max(0, Row - Range); int maxRow = Mathf.Min(_numRows, Row + Range); int minCol = Mathf.Max(0, Col - Range); int maxCol = Mathf.Min(_numRows, Col + Range); int nSplotches = (int)(Density * Range * Range); for (int i = 0; i < nSplotches; i++) { int row = Random.Range(minRow, maxRow); int col = Random.Range(minCol, maxCol); ApplyMaterialSplotch(row, col, 5); } }
public static byte[] Export(TerrainTile[,] tiles) { List<TerrainTile> dict = new List<TerrainTile>(); int w = tiles.GetLength(0); int h = tiles.GetLength(1); byte[] dat = new byte[w * h * 3]; int idx = 0; for (int y = 0; y < h; y++) for (int x = 0; x < w; x++) { TerrainTile tile = tiles[x, y]; short i = (short)dict.IndexOf(tile); if (i == -1) { i = (short)dict.Count; dict.Add(tile); } dat[idx] = (byte)(i & 0xff); dat[idx + 1] = (byte)(i >> 8); dat[idx + 2] = tile.Elevation; idx += 3; } MemoryStream ms = new MemoryStream(); using (BinaryWriter wtr = new BinaryWriter(ms)) { wtr.Write((ushort)dict.Count); foreach (TerrainTile i in dict) { wtr.Write(i.TileId); wtr.Write(i.TileObj ?? ""); wtr.Write(i.Name ?? ""); wtr.Write((byte)i.Terrain); wtr.Write((byte)i.Region); //wtr.Write((byte)i.Elevation); } wtr.Write(w); wtr.Write(h); wtr.Write(dat); } byte[] buff = ZlibStream.CompressBuffer(ms.ToArray()); byte[] ret = new byte[buff.Length + 1]; Buffer.BlockCopy(buff, 0, ret, 1, buff.Length); ret[0] = 2; return ret; }
public TileRenderer(Game game, TerrainTile tile) : base(game) { environs = new EnvironmentRenderer(game, tile); normals = new WireframeNormalRenderer(game, environs); liquids = new LiquidRenderer(game, tile); solidNavMesh = new SolidNavMeshRenderer(game, tile); wiredNavMesh = new WireframeNavMeshRenderer(game, tile); Game.Components.Add(environs); Game.Components.Add(normals); Game.Components.Add(liquids); Game.Components.Add(solidNavMesh); Game.Components.Add(wiredNavMesh); Disposed += (sender, args) => Cleanup(); EnabledChanged += (sender, args) => EnabledToggled(); }
public static byte[] Export(TerrainTile[,] tiles) { List<TerrainTile> dict = new List<TerrainTile>(); int w = tiles.GetLength(0); int h = tiles.GetLength(1); byte[] dat = new byte[w * h * 2]; int idx = 0; for (int y = 0; y < h; y++) for (int x = 0; x < w; x++) { TerrainTile tile = tiles[x, y]; short i = (short)dict.IndexOf(tile); if (i == -1) { i = (short)dict.Count; dict.Add(tile); } dat[idx] = (byte)(i & 0xff); dat[idx + 1] = (byte)(i >> 8); idx += 2; } MemoryStream ms = new MemoryStream(); using (BinaryWriter wtr = new BinaryWriter(ms)) { wtr.Write((short)dict.Count); foreach (var i in dict) { wtr.Write(i.TileId); wtr.Write(i.TileObj ?? ""); wtr.Write(i.Name ?? ""); wtr.Write((byte)i.Terrain); wtr.Write((byte)i.Region); } wtr.Write(w); wtr.Write(h); wtr.Write(dat); } return ZlibStream.CompressBuffer(ms.ToArray()); }
public TerrainDisplay(TerrainTile[,] tiles) { mode = Mode.Erase; this.tilesBak = (TerrainTile[,])tiles.Clone(); this.tiles = tiles; ClientSize = new Size(800, 800); BackColor = Color.Blue; WindowState = FormWindowState.Maximized; panel = new Panel() { Dock = DockStyle.Fill, AutoScroll = true, Controls = { (pic = new PictureBox() { Image = bmp = RenderColorBmp(tiles), SizeMode = PictureBoxSizeMode.AutoSize, }) } }; panel.HorizontalScroll.Enabled = true; panel.VerticalScroll.Enabled = true; panel.HorizontalScroll.Visible = true; panel.VerticalScroll.Visible = true; Controls.Add(panel); pic2 = new PictureBox() { Image = bmp, Width = 250, Height = 250, SizeMode = PictureBoxSizeMode.Zoom }; Controls.Add(pic2); pic2.BringToFront(); Text = mode.ToString(); pic.MouseMove += new MouseEventHandler(pic_MouseMove); pic.MouseDoubleClick += new MouseEventHandler(pic_MouseDoubleClick); }
public static void AddTerrainBrush(this List <ImageBrushPair> list, Image image, EntityId id, TerrainTile tile) { list.Add(new ImageBrushPair( brush: new TerrainBrush( metadata: new TerrainMetadata( entityId: id, textureDescriptor: tile ) ), image: image )); }
public SolidNavMeshRenderer(Game game, TerrainTile tile) : base(game, tile) { }
internal NavMeshRenderer(Game game, TerrainTile tile) : base(game) { this.tile = tile; }
void ITickRender.TickRender(WorldRenderer wr, Actor self) { if (wr.World.Type != WorldType.Editor) { return; } if (Type == EditorCursorType.TerrainTemplate || Type == EditorCursorType.Resource) { var cell = wr.Viewport.ViewToWorld(Viewport.LastMousePos); if (terrainOrResourceCell != cell || terrainOrResourceDirty) { terrainOrResourceCell = cell; terrainOrResourceDirty = false; terrainOrResourcePreview.Clear(); var pos = world.Map.CenterOfCell(cell); if (Type == EditorCursorType.TerrainTemplate) { var i = 0; for (var y = 0; y < TerrainTemplate.Size.Y; y++) { for (var x = 0; x < TerrainTemplate.Size.X; x++) { var tile = new TerrainTile(TerrainTemplate.Id, (byte)i++); var tileInfo = world.Map.Rules.TileSet.GetTileInfo(tile); // Empty tile if (tileInfo == null) { continue; } var sprite = wr.Theater.TileSprite(tile, 0); var offset = world.Map.Offset(new CVec(x, y), tileInfo.Height); var palette = wr.Palette(TerrainTemplate.Palette ?? TileSet.TerrainPaletteInternalName); terrainOrResourcePreview.Add(new SpriteRenderable(sprite, pos, offset, 0, palette, 1, false, false)); } } } else { var variant = Resource.Sequences.FirstOrDefault(); var sequence = wr.World.Map.Rules.Sequences.GetSequence("resources", variant); var sprite = sequence.GetSprite(Resource.MaxDensity - 1); var palette = wr.Palette(Resource.Palette); terrainOrResourcePreview.Add(new SpriteRenderable(sprite, pos, WVec.Zero, 0, palette, 1, false, sequence.IgnoreWorldTint)); } } } else if (Type == EditorCursorType.Actor) { // Offset mouse position by the center offset (in world pixels) var worldPx = wr.Viewport.ViewToWorldPx(Viewport.LastMousePos) - wr.ScreenPxOffset(actorCenterOffset); var cell = wr.Viewport.ViewToWorld(wr.Viewport.WorldToViewPx(worldPx)); var subCell = actorSharesCell ? editorLayer.FreeSubCellAt(cell) : SubCell.Invalid; var updated = false; if (actorLocation != cell) { actorLocation = cell; Actor.ReplaceInit(new LocationInit(cell)); updated = true; } if (actorSubCell != subCell) { actorSubCell = subCell; if (Actor.RemoveInits <SubCellInit>() > 0) { updated = true; } var subcell = world.Map.Tiles.Contains(cell) ? editorLayer.FreeSubCellAt(cell) : SubCell.Invalid; if (subcell != SubCell.Invalid) { Actor.AddInit(new SubCellInit(subcell)); updated = true; } } if (updated) { Actor = new EditorActorPreview(wr, null, Actor.Export(), Actor.Owner); } } }
public void GatherAlphamap(TerrainLayer inputLayer, bool addLayerIfDoesntExist = true) { if (inputLayer == null) { return; } int terrainLayerIndex = TerrainPaintUtility.FindTerrainLayerIndex(originTerrain, inputLayer); if (terrainLayerIndex == -1 && addLayerIfDoesntExist) { terrainLayerIndex = TerrainPaintUtility.AddTerrainLayer(originTerrain, inputLayer); } RenderTexture.active = sourceRenderTexture; GL.Clear(false, true, new Color(0.0f, 0.0f, 0.0f, 0.0f)); GL.PushMatrix(); GL.LoadPixelMatrix(0, pixelRect.width, 0, pixelRect.height); Vector4[] layerMasks = { new Vector4(1, 0, 0, 0), new Vector4(0, 1, 0, 0), new Vector4(0, 0, 1, 0), new Vector4(0, 0, 0, 1) }; Material copyTerrainLayerMaterial = TerrainPaintUtility.GetCopyTerrainLayerMaterial(); for (int i = 0; i < m_TerrainTiles.Count; i++) { TerrainTile terrainTile = m_TerrainTiles[i]; if (terrainTile.clippedLocalPixels.width == 0 || terrainTile.clippedLocalPixels.height == 0) { continue; } int tileLayerIndex = TerrainPaintUtility.FindTerrainLayerIndex(terrainTile.terrain, inputLayer); if (tileLayerIndex == -1) { if (!addLayerIfDoesntExist) { // setting these to zero will prevent them from being used later terrainTile.clippedLocalPixels.width = 0; terrainTile.clippedLocalPixels.height = 0; terrainTile.clippedPCPixels.width = 0; terrainTile.clippedPCPixels.height = 0; continue; } tileLayerIndex = TerrainPaintUtility.AddTerrainLayer(terrainTile.terrain, inputLayer); } terrainTile.mapIndex = tileLayerIndex >> 2; terrainTile.channelIndex = tileLayerIndex & 0x3; Texture sourceTexture = TerrainPaintUtility.GetTerrainAlphaMapChecked(terrainTile.terrain, terrainTile.mapIndex); if ((sourceTexture.width != targetTextureWidth) || (sourceTexture.height != targetTextureHeight)) { Debug.LogWarning("PaintContext alphamap operations must use the same resolution for all Terrains - mismatched Terrains are ignored. (" + sourceTexture.width + " x " + sourceTexture.height + ") != (" + targetTextureWidth + " x " + targetTextureHeight + ")", terrainTile.terrain); continue; } FilterMode oldFilterMode = sourceTexture.filterMode; sourceTexture.filterMode = FilterMode.Point; copyTerrainLayerMaterial.SetVector("_LayerMask", layerMasks[terrainTile.channelIndex]); copyTerrainLayerMaterial.SetTexture("_MainTex", sourceTexture); copyTerrainLayerMaterial.SetPass(0); TerrainPaintUtility.DrawQuad(terrainTile.clippedPCPixels, terrainTile.clippedLocalPixels, sourceTexture); sourceTexture.filterMode = oldFilterMode; } GL.PopMatrix(); RenderTexture.active = oldRenderTexture; }
private void ScatterInternal( Func <ITerrainInfo, RenderTexture> terrainToRT, string operationName, Material blitMaterial = null, int blitPass = 0, Action <ITerrainInfo> beforeBlit = null, Action <ITerrainInfo> afterBlit = null) { var oldRT = RenderTexture.active; if (blitMaterial == null) { blitMaterial = TerrainPaintUtility.GetBlitMaterial(); } for (int i = 0; i < m_TerrainTiles.Count; i++) { TerrainTile terrainTile = m_TerrainTiles[i]; if (!terrainTile.scatterEnable) { continue; } RenderTexture target = terrainToRT(terrainTile); if ((target == null) || (!terrainTile.scatterEnable)) // double check scatterEnable in case terrainToRT modified it { continue; } if ((target.width != targetTextureWidth) || (target.height != targetTextureHeight)) { Debug.LogWarning(operationName + " requires the same resolution for all Terrains - mismatched Terrains are ignored.", terrainTile.terrain); continue; } beforeBlit?.Invoke(terrainTile); if (!terrainTile.scatterEnable) // check again, beforeBlit may have modified it { continue; } RenderTexture.active = target; GL.PushMatrix(); GL.LoadPixelMatrix(0, target.width, 0, target.height); { FilterMode oldFilterMode = destinationRenderTexture.filterMode; destinationRenderTexture.filterMode = FilterMode.Point; blitMaterial.SetTexture("_MainTex", destinationRenderTexture); blitMaterial.SetPass(blitPass); TerrainPaintUtility.DrawQuad(terrainTile.clippedTerrainPixels, terrainTile.clippedPCPixels, destinationRenderTexture); destinationRenderTexture.filterMode = oldFilterMode; } GL.PopMatrix(); afterBlit?.Invoke(terrainTile); } RenderTexture.active = oldRT; }
private void DeleteTile(TerrainTile tile, Control obj) { tile.Clear(); RefreshTile(obj, tile); ReloadMap(); }
public void GatherAlphamap(Terrain terrain, TerrainLayer inputLayer, bool addLayerIfDoesntExist = true) { if (inputLayer == null) { return; } int terrainLayerIndex = FindTerrainLayerIndex(terrain, inputLayer); if (terrainLayerIndex == -1 && addLayerIfDoesntExist) { terrainLayerIndex = AddTerrainLayer(terrain, inputLayer); } Texture2D inputTexture = GetTerrainAlphaMapChecked(terrain, terrainLayerIndex >> 2); int inputTextureWidth = inputTexture.width; int inputTextureHeight = inputTexture.height; RenderTexture.active = sourceRenderTexture; Vector4[] layerMasks = { new Vector4(1, 0, 0, 0), new Vector4(0, 1, 0, 0), new Vector4(0, 0, 1, 0), new Vector4(0, 0, 0, 1) }; Material copyTerrainLayerMaterial = GetCopyTerrainLayerMaterial(); for (int i = 0; i < terrainTiles.Length; i++) { if (clippedTiles[i].width == 0 || clippedTiles[i].height == 0) { continue; } TerrainTile terrainTile = terrainTiles[i]; Rect readRect = new Rect( (clippedTiles[i].x + terrainTile.readOffset.x) / (float)inputTextureWidth, (clippedTiles[i].y + terrainTile.readOffset.y) / (float)inputTextureHeight, (clippedTiles[i].width) / (float)inputTextureWidth, (clippedTiles[i].height) / (float)inputTextureHeight); int tileLayerIndex = FindTerrainLayerIndex(terrainTile.terrain, inputLayer); if (tileLayerIndex == -1) { if (!addLayerIfDoesntExist) { // setting these to zero will prevent them from being used later clippedTiles[i].width = 0; clippedTiles[i].height = 0; validPaintRects[i].width = 0; validPaintRects[i].height = 0; continue; } tileLayerIndex = AddTerrainLayer(terrainTile.terrain, inputLayer); } terrainTile.mapIndex = tileLayerIndex >> 2; terrainTile.channelIndex = tileLayerIndex & 0x3; Texture sourceTexture = GetTerrainAlphaMapChecked(terrainTile.terrain, terrainTile.mapIndex); FilterMode oldFilterMode = sourceTexture.filterMode; sourceTexture.filterMode = FilterMode.Point; copyTerrainLayerMaterial.SetVector("_LayerMask", layerMasks[terrainTile.channelIndex]); copyTerrainLayerMaterial.SetTexture("_MainTex", sourceTexture); copyTerrainLayerMaterial.SetPass(0); DrawQuad(brushRect.width, brushRect.height, readRect, validPaintRects[i]); sourceTexture.filterMode = oldFilterMode; } RenderTexture.active = oldRenderTexture; }
public TerrainTextureSample(Microsoft.Xna.Framework.Game game) : base(game) { SampleFramework.IsMouseVisible = false; _graphicsScreen = new DeferredGraphicsScreen(Services); _graphicsScreen.DrawReticle = true; GraphicsService.Screens.Insert(0, _graphicsScreen); GameObjectService.Objects.Add(new DeferredGraphicsOptionsObject(Services)); Services.Register(typeof(DebugRenderer), null, _graphicsScreen.DebugRenderer); var scene = _graphicsScreen.Scene; Services.Register(typeof(IScene), null, scene); // Add gravity and damping to the physics simulation. Simulation.ForceEffects.Add(new Gravity()); Simulation.ForceEffects.Add(new Damping()); // Add a custom game object which controls the camera. var cameraGameObject = new CameraObject(Services, 60); cameraGameObject.ResetPose(new Vector3F(0, 1.8f, 0), 0, 0); GameObjectService.Objects.Add(cameraGameObject); _graphicsScreen.ActiveCameraNode = cameraGameObject.CameraNode; for (int i = 0; i < 10; i++) { GameObjectService.Objects.Add(new DynamicObject(Services, 1)); } GameObjectService.Objects.Add(new DynamicSkyObject(Services, true, false, true)); // Create a simple flat terrain. var terrain = new Terrain(); _terrainTile = new TerrainTile(GraphicsService) { OriginX = -100, OriginZ = -100, CellSize = 1, }; terrain.Tiles.Add(_terrainTile); // Create a flat dummy height texture. float[] heights = new float[200 * 200]; Texture2D heightTexture = null; TerrainHelper.CreateHeightTexture( GraphicsService.GraphicsDevice, heights, 200, 200, false, ref heightTexture); _terrainTile.HeightTexture = heightTexture; var shadowMapEffect = ContentManager.Load <Effect>("DigitalRune/Terrain/TerrainShadowMap"); var gBufferEffect = ContentManager.Load <Effect>("DigitalRune/Terrain/TerrainGBuffer"); var materialEffect = ContentManager.Load <Effect>("DigitalRune/Terrain/TerrainMaterial"); var material = new Material { { "ShadowMap", new EffectBinding(GraphicsService, shadowMapEffect, null, EffectParameterHint.Material) }, { "GBuffer", new EffectBinding(GraphicsService, gBufferEffect, null, EffectParameterHint.Material) }, { "Material", new EffectBinding(GraphicsService, materialEffect, null, EffectParameterHint.Material) } }; var terrainNode = new TerrainNode(terrain, material) { DetailClipmap = { CellsPerLevel = 1364, NumberOfLevels = 9, EnableMipMap = true, }, }; scene.Children.Add(terrainNode); // Add 3 detail textures layers: gravel, rock, snow. float detailCellSize = terrainNode.DetailClipmap.CellSizes[0]; var materialGravel = new TerrainMaterialLayer(GraphicsService) { DiffuseTexture = ContentManager.Load <Texture2D>("Terrain/Gravel-Diffuse"), NormalTexture = ContentManager.Load <Texture2D>("Terrain/Gravel-Normal"), SpecularTexture = ContentManager.Load <Texture2D>("Terrain/Gravel-Specular"), TileSize = detailCellSize * 512, BlendRange = 0.1f, }; _terrainTile.Layers.Add(materialGravel); var noiseTexture = NoiseHelper.GetNoiseTexture(GraphicsService, 128, 60); var materialRock = new TerrainMaterialLayer(GraphicsService) { DiffuseTexture = ContentManager.Load <Texture2D>("Terrain/Rock-02-Diffuse"), NormalTexture = ContentManager.Load <Texture2D>("Terrain/Rock-02-Normal"), SpecularTexture = ContentManager.Load <Texture2D>("Terrain/Rock-02-Specular"), HeightTexture = ContentManager.Load <Texture2D>("Terrain/Rock-02-Height"), TileSize = detailCellSize * 1024, DiffuseColor = new Vector3F(1 / 0.702f), BlendTexture = noiseTexture, BlendTextureChannel = 0, BlendRange = 0.1f, TerrainHeightBlendRange = 0.1f, }; _terrainTile.Layers.Add(materialRock); var materialSnow = new TerrainMaterialLayer(GraphicsService) { DiffuseTexture = ContentManager.Load <Texture2D>("Terrain/Snow-Diffuse"), NormalTexture = ContentManager.Load <Texture2D>("Terrain/Snow-Normal"), SpecularTexture = ContentManager.Load <Texture2D>("Terrain/Snow-Specular"), TileSize = detailCellSize * 512, BlendTexture = noiseTexture, BlendTextureChannel = 1, BlendRange = 0.1f, }; _terrainTile.Layers.Add(materialSnow); // Create a flat plane for collision detection. var rigidBody = new RigidBody(new PlaneShape(), new MassFrame(), null) { MotionType = MotionType.Static, }; Simulation.RigidBodies.Add(rigidBody); CreateGuiControls(); }
//-------------------------------------------------------------- #region Methods //-------------------------------------------------------------- protected override void OnLoad() { // Get common services and game objects. _graphicsService = _services.GetInstance <IGraphicsService>(); var content = _services.GetInstance <ContentManager>(); var scene = _services.GetInstance <IScene>(); _simulation = _services.GetInstance <Simulation>(); var gameObjectService = _services.GetInstance <IGameObjectService>(); _cameraObject = gameObjectService.Objects.OfType <CameraObject>().First(); _previousCameraFar = _cameraObject.CameraNode.Camera.Projection.Far; // Create a new terrain. var terrain = new Terrain(); _terrainTile = new TerrainTile(_graphicsService) { CellSize = 2, }; terrain.Tiles.Add(_terrainTile); var shadowMapEffect = content.Load <Effect>("DigitalRune/Terrain/TerrainShadowMap"); var gBufferEffect = content.Load <Effect>("DigitalRune/Terrain/TerrainGBuffer"); var materialEffect = content.Load <Effect>("DigitalRune/Terrain/TerrainMaterial"); var material = new Material { { "ShadowMap", new EffectBinding(_graphicsService, shadowMapEffect, null, EffectParameterHint.Material) }, { "GBuffer", new EffectBinding(_graphicsService, gBufferEffect, null, EffectParameterHint.Material) }, { "Material", new EffectBinding(_graphicsService, materialEffect, null, EffectParameterHint.Material) } }; TerrainNode = new TerrainNode(terrain, material) { BaseClipmap = { CellsPerLevel = 128, NumberOfLevels = 6, }, DetailClipmap = { CellsPerLevel = 1364, NumberOfLevels = 9, }, }; scene.Children.Add(TerrainNode); // Create a rigid body with a height field for collision detection. var heightField = new HeightField { Depth = 1, UseFastCollisionApproximation = false, }; _rigidBody = new RigidBody(heightField, new MassFrame(), null) { MotionType = MotionType.Static, UserData = _terrainTile, }; _simulation.RigidBodies.Add(_rigidBody); InitializeHeightsAndNormals(); InitializeClipmapCellSizes(); InitializeTerrainLayers(content); // Enable mipmaps when using anisotropic filtering on AMD graphics cards: //TerrainNode.DetailClipmap.EnableMipMap = true; CreateGuiControls(); }
internal void AddTreeToTile(TerrainTile tile, TreeInstance tree, int rand) { tree.position = new Vector3(tile.floatPos.x + Random.Range(0, tilePosJitter), 0f, tile.floatPos.y + Random.Range(0, tilePosJitter)); terrain.AddTreeInstance(tree); tile.TreeInstanceIndex = terrainData.treeInstanceCount - 1; }
public UndoTile(CPos cell, TerrainTile mapTile, byte height) { Cell = cell; MapTile = mapTile; Height = height; }
public static void OnTilePrepare_ReadLocks(TerrainTile tile, TileData tileData) { //finding locks intersecting tile List <Lock> intersectingLocks = null; Lock[] allLocks = tile.mapMagic.locks; for (int i = 0; i < allLocks.Length; i++) { if (!allLocks[i].locked) { continue; } if (!allLocks[i].IsIntersecting(tileData.area.active)) { continue; } if (tileData.isDraft && !allLocks[i].rescaleDraft) { continue; } if (intersectingLocks == null) { intersectingLocks = new List <Lock>(); } intersectingLocks.Add(allLocks[i]); } if (intersectingLocks == null) //no locks on this tile { return; } //preparing lock-to-data dict Dictionary <Lock, LockDataSet> lockDatasDict; if (!lockDatas.TryGetValue(tileData, out lockDatasDict)) { lockDatasDict = new Dictionary <Lock, LockDataSet>(); lockDatas.Add(tileData, lockDatasDict); } //writing locks Terrain terrain = tile.GetTerrain(tileData.isDraft); int intersectingCount = intersectingLocks.Count; for (int i = 0; i < intersectingCount; i++) { Lock lk = intersectingLocks[i]; if (lockDatasDict.ContainsKey(lk)) { continue; } //do not read anything if already contains data ? LockDataSet lockData = new LockDataSet(); lockData.Read(terrain, lk); lockDatasDict.Add(lk, lockData); } }
public TerrainTileInfo GetTileInfo(TerrainTile r) { return(Templates[r.Type][r.Index]); }
void Awake() { grass = new TerrainTile(2, false, new Color(0.05f, 1, 0.15f), "Grass"); water = new TerrainTile(4, true, new Color(0.1f, 0.05f, 1), "Water"); dirt = new TerrainTile(2, false, new Color(0.8f, 0.25f, 0.25f), "Dirt"); }
public void ScatterAlphamap(string editorUndoName) { Vector4[] layerMasks = { new Vector4(1, 0, 0, 0), new Vector4(0, 1, 0, 0), new Vector4(0, 0, 1, 0), new Vector4(0, 0, 0, 1) }; Material copyTerrainLayerMaterial = GetCopyTerrainLayerMaterial(); for (int i = 0; i < terrainTiles.Length; i++) { if (clippedTiles[i].width == 0 || clippedTiles[i].height == 0) { continue; } TerrainTile terrainTile = terrainTiles[i]; if (onTerrainTileBeforePaint != null) { onTerrainTileBeforePaint(terrainTile, ToolAction.PaintTexture, editorUndoName); } var rtdesc = new RenderTextureDescriptor(destinationRenderTexture.width, destinationRenderTexture.height, RenderTextureFormat.ARGB32); rtdesc.sRGB = false; rtdesc.useMipMap = false; rtdesc.autoGenerateMips = false; RenderTexture destTarget = RenderTexture.GetTemporary(rtdesc); RenderTexture.active = destTarget; var writeRect = new RectInt( clippedTiles[i].x + terrainTile.rect.x - brushRect.x + terrainTile.writeOffset.x, clippedTiles[i].y + terrainTile.rect.y - brushRect.y + terrainTile.writeOffset.y, clippedTiles[i].width, clippedTiles[i].height); var readRect = new Rect( writeRect.x / (float)brushRect.width, writeRect.y / (float)brushRect.height, writeRect.width / (float)brushRect.width, writeRect.height / (float)brushRect.height); destinationRenderTexture.filterMode = FilterMode.Point; for (int j = 0; j < terrainTile.terrain.terrainData.alphamapTextureCount; j++) { Texture2D sourceTex = terrainTile.terrain.terrainData.alphamapTextures[j]; int mapIndex = terrainTile.mapIndex; int channelIndex = terrainTile.channelIndex; Rect combineRect = new Rect( clippedTiles[i].x / (float)sourceTex.width, clippedTiles[i].y / (float)sourceTex.height, clippedTiles[i].width / (float)sourceTex.width, clippedTiles[i].height / (float)sourceTex.height); copyTerrainLayerMaterial.SetTexture("_MainTex", destinationRenderTexture); copyTerrainLayerMaterial.SetTexture("_OldAlphaMapTexture", sourceRenderTexture); copyTerrainLayerMaterial.SetTexture("_AlphaMapTexture", sourceTex); copyTerrainLayerMaterial.SetVector("_LayerMask", j == mapIndex ? layerMasks[channelIndex] : Vector4.zero); copyTerrainLayerMaterial.SetPass(1); GL.PushMatrix(); GL.LoadOrtho(); GL.LoadPixelMatrix(0, destTarget.width, 0, destTarget.height); GL.Begin(GL.QUADS); GL.Color(new Color(1.0f, 1.0f, 1.0f, 1.0f)); GL.MultiTexCoord2(0, readRect.x, readRect.y); GL.MultiTexCoord2(1, combineRect.x, combineRect.y); GL.Vertex3(writeRect.x, writeRect.y, 0.0f); GL.MultiTexCoord2(0, readRect.x, readRect.yMax); GL.MultiTexCoord2(1, combineRect.x, combineRect.yMax); GL.Vertex3(writeRect.x, writeRect.yMax, 0.0f); GL.MultiTexCoord2(0, readRect.xMax, readRect.yMax); GL.MultiTexCoord2(1, combineRect.xMax, combineRect.yMax); GL.Vertex3(writeRect.xMax, writeRect.yMax, 0.0f); GL.MultiTexCoord2(0, readRect.xMax, readRect.y); GL.MultiTexCoord2(1, combineRect.xMax, combineRect.y); GL.Vertex3(writeRect.xMax, writeRect.y, 0.0f); GL.End(); GL.PopMatrix(); if (paintTextureUsesCopyTexture) { var rtdesc2 = new RenderTextureDescriptor(sourceTex.width, sourceTex.height, RenderTextureFormat.ARGB32); rtdesc2.sRGB = false; rtdesc2.useMipMap = true; rtdesc2.autoGenerateMips = false; var mips = RenderTexture.GetTemporary(rtdesc2); if (!mips.IsCreated()) { mips.Create(); } // Composes mip0 in a RT with full mipchain. Graphics.CopyTexture(sourceTex, 0, 0, mips, 0, 0); Graphics.CopyTexture(destTarget, 0, 0, writeRect.x, writeRect.y, writeRect.width, writeRect.height, mips, 0, 0, clippedTiles[i].x, clippedTiles[i].y); mips.GenerateMips(); // Copy them into sourceTex. Graphics.CopyTexture(mips, sourceTex); RenderTexture.ReleaseTemporary(mips); } else { GraphicsDeviceType deviceType = SystemInfo.graphicsDeviceType; if (deviceType == GraphicsDeviceType.Metal || deviceType == GraphicsDeviceType.OpenGLCore) { sourceTex.ReadPixels(new Rect(writeRect.x, writeRect.y, writeRect.width, writeRect.height), clippedTiles[i].x, clippedTiles[i].y); } else { sourceTex.ReadPixels(new Rect(writeRect.x, destTarget.height - writeRect.y - writeRect.height, writeRect.width, writeRect.height), clippedTiles[i].x, clippedTiles[i].y); } sourceTex.Apply(); } } RenderTexture.active = null; RenderTexture.ReleaseTemporary(destTarget); OnTerrainPainted(terrainTile, ToolAction.PaintTexture); } }
Sprite ITiledTerrainRenderer.TileSprite(TerrainTile r, int?variant) { return(tileCache.TileSprite(r, variant)); }
public static TerrainTile[] FindTerrainTiles(Terrain terrain, int width, int height, RectInt brushRect) { List <TerrainTile> terrainTiles = new List <TerrainTile>(); Terrain left = terrain.leftNeighbor; Terrain right = terrain.rightNeighbor; Terrain top = terrain.topNeighbor; Terrain bottom = terrain.bottomNeighbor; bool wantLeft = (brushRect.x < 0); bool wantRight = (brushRect.xMax > (width - 1)); bool wantTop = (brushRect.yMax > (height - 1)); bool wantBottom = (brushRect.y < 0); if (wantLeft && wantRight) { Debug.Log("FindTerrainTiles query rectangle too large!"); wantRight = false; } if (wantTop && wantBottom) { Debug.Log("FindTerrainTiles query rectangle too large!"); wantBottom = false; } // add center tile TerrainTile tile = new TerrainTile(terrain, new RectInt(0, 0, width, height)); tile.readOffset = Vector2Int.zero; tile.writeOffset = Vector2Int.zero; terrainTiles.Add(tile); // add horizontal and vertical neighbors Terrain horiz = null; Terrain vert = null; Terrain cornerTerrain = null; int xBias = 0; int yBias = 0; int xReadBias = 0; int yReadBias = 0; int xWriteBias = 0; int yWriteBias = 0; if (wantLeft) { xBias = -1; xReadBias = -1; xWriteBias = 1; horiz = left; } else if (wantRight) { xBias = 1; xReadBias = 1; xWriteBias = -1; horiz = right; } if (wantTop) { yBias = 1; yReadBias = 1; yWriteBias = -1; vert = top; } else if (wantBottom) { yBias = -1; yReadBias = -1; yWriteBias = 1; vert = bottom; } if (horiz) { tile = new TerrainTile(horiz, new RectInt(xBias * width, 0, width, height)); tile.readOffset = new Vector2Int(xReadBias, 0); tile.writeOffset = new Vector2Int(xWriteBias, 0); terrainTiles.Add(tile); // add corner, if we have a link if (wantTop && horiz.topNeighbor) { cornerTerrain = horiz.topNeighbor; } else if (wantBottom && horiz.bottomNeighbor) { cornerTerrain = horiz.bottomNeighbor; } } if (vert) { tile = new TerrainTile(vert, new RectInt(0, yBias * height, width, height)); tile.readOffset = new Vector2Int(0, yReadBias); tile.writeOffset = new Vector2Int(0, yWriteBias); terrainTiles.Add(tile); // add corner, if we have a link if (wantLeft && vert.leftNeighbor) { cornerTerrain = vert.leftNeighbor; } else if (wantRight && vert.rightNeighbor) { cornerTerrain = vert.rightNeighbor; } } if (cornerTerrain != null) { tile = new TerrainTile(cornerTerrain, new RectInt(xBias * width, yBias * height, width, height)); tile.readOffset = new Vector2Int(xReadBias, yReadBias); tile.writeOffset = new Vector2Int(xWriteBias, yWriteBias); terrainTiles.Add(tile); } return(terrainTiles.ToArray()); }
public void ScatterAlphamap(string editorUndoName) { Vector4[] layerMasks = { new Vector4(1, 0, 0, 0), new Vector4(0, 1, 0, 0), new Vector4(0, 0, 1, 0), new Vector4(0, 0, 0, 1) }; Material copyTerrainLayerMaterial = TerrainPaintUtility.GetCopyTerrainLayerMaterial(); for (int i = 0; i < m_TerrainTiles.Count; i++) { TerrainTile terrainTile = m_TerrainTiles[i]; if (terrainTile.clippedLocalPixels.width == 0 || terrainTile.clippedLocalPixels.height == 0) { continue; } if (onTerrainTileBeforePaint != null) { onTerrainTileBeforePaint(terrainTile, ToolAction.PaintTexture, editorUndoName); } var rtdesc = new RenderTextureDescriptor(destinationRenderTexture.width, destinationRenderTexture.height, RenderTextureFormat.ARGB32); rtdesc.sRGB = false; rtdesc.useMipMap = false; rtdesc.autoGenerateMips = false; RenderTexture destTarget = RenderTexture.GetTemporary(rtdesc); RenderTexture.active = destTarget; RectInt writeRect = terrainTile.clippedPCPixels; Rect readRect = new Rect( writeRect.x / (float)pixelRect.width, writeRect.y / (float)pixelRect.height, writeRect.width / (float)pixelRect.width, writeRect.height / (float)pixelRect.height); destinationRenderTexture.filterMode = FilterMode.Point; int mapIndex = terrainTile.mapIndex; int channelIndex = terrainTile.channelIndex; Texture2D sourceTexTargetChannel = terrainTile.terrain.terrainData.alphamapTextures[mapIndex]; for (int j = 0; j < terrainTile.terrain.terrainData.alphamapTextureCount; j++) { Texture2D sourceTex = terrainTile.terrain.terrainData.alphamapTextures[j]; if ((sourceTex.width != targetTextureWidth) || (sourceTex.height != targetTextureHeight)) { Debug.LogWarning("PaintContext alphamap operations must use the same resolution for all Terrains - mismatched Terrains are ignored.", terrainTile.terrain); continue; } Rect combineRect = new Rect( terrainTile.clippedLocalPixels.x / (float)sourceTex.width, terrainTile.clippedLocalPixels.y / (float)sourceTex.height, terrainTile.clippedLocalPixels.width / (float)sourceTex.width, terrainTile.clippedLocalPixels.height / (float)sourceTex.height); copyTerrainLayerMaterial.SetTexture("_MainTex", destinationRenderTexture); copyTerrainLayerMaterial.SetTexture("_OldAlphaMapTexture", sourceRenderTexture); copyTerrainLayerMaterial.SetTexture("_OriginalTargetAlphaMap", sourceTexTargetChannel); copyTerrainLayerMaterial.SetTexture("_AlphaMapTexture", sourceTex); copyTerrainLayerMaterial.SetVector("_LayerMask", j == mapIndex ? layerMasks[channelIndex] : Vector4.zero); copyTerrainLayerMaterial.SetVector("_OriginalTargetAlphaMask", layerMasks[channelIndex]); copyTerrainLayerMaterial.SetPass(1); GL.PushMatrix(); GL.LoadPixelMatrix(0, destTarget.width, 0, destTarget.height); GL.Begin(GL.QUADS); GL.Color(new Color(1.0f, 1.0f, 1.0f, 1.0f)); GL.MultiTexCoord2(0, readRect.x, readRect.y); GL.MultiTexCoord2(1, combineRect.x, combineRect.y); GL.Vertex3(writeRect.x, writeRect.y, 0.0f); GL.MultiTexCoord2(0, readRect.x, readRect.yMax); GL.MultiTexCoord2(1, combineRect.x, combineRect.yMax); GL.Vertex3(writeRect.x, writeRect.yMax, 0.0f); GL.MultiTexCoord2(0, readRect.xMax, readRect.yMax); GL.MultiTexCoord2(1, combineRect.xMax, combineRect.yMax); GL.Vertex3(writeRect.xMax, writeRect.yMax, 0.0f); GL.MultiTexCoord2(0, readRect.xMax, readRect.y); GL.MultiTexCoord2(1, combineRect.xMax, combineRect.y); GL.Vertex3(writeRect.xMax, writeRect.y, 0.0f); GL.End(); GL.PopMatrix(); if (TerrainPaintUtility.paintTextureUsesCopyTexture) { var rtdesc2 = new RenderTextureDescriptor(sourceTex.width, sourceTex.height, RenderTextureFormat.ARGB32); rtdesc2.sRGB = false; rtdesc2.useMipMap = true; rtdesc2.autoGenerateMips = false; var mips = RenderTexture.GetTemporary(rtdesc2); if (!mips.IsCreated()) { mips.Create(); } // Composes mip0 in a RT with full mipchain. Graphics.CopyTexture(sourceTex, 0, 0, mips, 0, 0); Graphics.CopyTexture(destTarget, 0, 0, writeRect.x, writeRect.y, writeRect.width, writeRect.height, mips, 0, 0, terrainTile.clippedLocalPixels.x, terrainTile.clippedLocalPixels.y); mips.GenerateMips(); // Copy them into sourceTex. Graphics.CopyTexture(mips, sourceTex); RenderTexture.ReleaseTemporary(mips); } else { GraphicsDeviceType deviceType = SystemInfo.graphicsDeviceType; if (deviceType == GraphicsDeviceType.Metal || deviceType == GraphicsDeviceType.OpenGLCore) { sourceTex.ReadPixels(new Rect(writeRect.x, writeRect.y, writeRect.width, writeRect.height), terrainTile.clippedLocalPixels.x, terrainTile.clippedLocalPixels.y); } else { sourceTex.ReadPixels(new Rect(writeRect.x, destTarget.height - writeRect.y - writeRect.height, writeRect.width, writeRect.height), terrainTile.clippedLocalPixels.x, terrainTile.clippedLocalPixels.y); } sourceTex.Apply(); } } RenderTexture.active = null; RenderTexture.ReleaseTemporary(destTarget); OnTerrainPainted(terrainTile, ToolAction.PaintTexture); } }
public static void DrawSceneGUI(MapMagicObject mapMagic, SelectionMode selectionMode) { Dictionary <Coord, TerrainTile> tilesLut = new Dictionary <Coord, TerrainTile>(mapMagic.tiles.grid); if (selectionMode != SelectionMode.none && !Event.current.alt) { //returning if no scene veiw (right after script compile) SceneView sceneview = UnityEditor.SceneView.lastActiveSceneView; if (sceneview == null || sceneview.camera == null) { return; } //disabling selection HandleUtility.AddDefaultControl(GUIUtility.GetControlID(FocusType.Passive)); //preparing the sets of both custom and tile terrains HashSet <Terrain> pinnedCustomTerrains = new HashSet <Terrain>(); //custom terrains that were already pinned before foreach (TerrainTile tile in mapMagic.tiles.customTiles) { if (tile.main != null) { pinnedCustomTerrains.Add(tile.main.terrain); } if (tile.draft != null) { pinnedCustomTerrains.Add(tile.draft.terrain); } } HashSet <Terrain> pinnedTileTerrains = new HashSet <Terrain>(); foreach (var kvp in tilesLut) { TerrainTile tile = kvp.Value; if (tile.main != null) { pinnedTileTerrains.Add(tile.main.terrain); } if (tile.draft != null) { pinnedTileTerrains.Add(tile.draft.terrain); } } if (selectionMode == SelectionMode.pin) { Handles.color = FrameDraw.pinColor; List <Coord> selectedCoords = SelectTiles((Vector3)mapMagic.tileSize, false, tilesLut, mapMagic.transform); if (selectedCoords != null) { UnityEditor.Undo.RegisterFullObjectHierarchyUndo(mapMagic.gameObject, "MapMagic Pin Terrains"); foreach (Coord coord in selectedCoords) { mapMagic.tiles.Pin(coord, false, mapMagic); } foreach (Coord coord in selectedCoords) { UnityEditor.Undo.RegisterCreatedObjectUndo(mapMagic.tiles[coord].gameObject, "MapMagic Pin Terrains"); } } } if (selectionMode == SelectionMode.pinLowres) { Handles.color = FrameDraw.pinColor; List <Coord> selectedCoords = SelectTiles((Vector3)mapMagic.tileSize, true, tilesLut, mapMagic.transform); if (selectedCoords != null) { UnityEditor.Undo.RegisterFullObjectHierarchyUndo(mapMagic.gameObject, "MapMagic Pin Draft Terrains"); foreach (Coord coord in selectedCoords) { mapMagic.tiles.Pin(coord, true, mapMagic); } foreach (Coord coord in selectedCoords) { UnityEditor.Undo.RegisterCreatedObjectUndo(mapMagic.tiles[coord].gameObject, "MapMagic Pin Terrains"); } } } if (selectionMode == SelectionMode.pinExisting) { //excluding tiles HashSet <Terrain> possibleTerrains = new HashSet <Terrain>(); Terrain[] allTerrains = GameObject.FindObjectsOfType <Terrain>(); foreach (Terrain terrain in allTerrains) { if (!pinnedTileTerrains.Contains(terrain)) { possibleTerrains.Add(terrain); } } HashSet <Terrain> selectedTerrains = SelectTerrains(possibleTerrains, FrameDraw.pinColor, false); if (selectedTerrains != null) { UnityEditor.Undo.RegisterFullObjectHierarchyUndo(mapMagic.gameObject, "MapMagic Pin Terrains"); foreach (Terrain terrain in selectedTerrains) { if (pinnedCustomTerrains.Contains(terrain)) { continue; } terrain.transform.parent = mapMagic.transform; TerrainTile tile = terrain.gameObject.GetComponent <TerrainTile>(); if (tile == null) { tile = terrain.gameObject.AddComponent <TerrainTile>(); } tile.main.terrain = terrain; //tile.main.area = new Terrains.Area(terrain); //tile.main.use = true; //tile.lodData = null; mapMagic.tiles.PinCustom(tile); mapMagic.StartGenerate(tile); } } } if (selectionMode == SelectionMode.selectPreview) { //hash set of all pinned terrains contains main data HashSet <Terrain> pinnedMainTerrains = new HashSet <Terrain>(); foreach (var kvp in tilesLut) { TerrainTile tile = kvp.Value; if (tile.main != null) { pinnedMainTerrains.Add(tile.main.terrain); } } pinnedMainTerrains.UnionWith(pinnedCustomTerrains); HashSet <Terrain> selectedTerrains = SelectTerrains(pinnedMainTerrains, FrameDraw.selectPreviewColor, false); if (selectedTerrains != null && selectedTerrains.Count == 1) { UnityEditor.Undo.RegisterCompleteObjectUndo(mapMagic, "MapMagic Select Preview"); Terrain selectedTerrain = selectedTerrains.Any(); //clearing preview if (selectedTerrain == mapMagic.AssignedPreviewTerrain) { mapMagic.ClearPreviewTile(); TerrainTile.OnPreviewAssigned(mapMagic.PreviewData); } //assigning new else { foreach (var kvp in tilesLut) { TerrainTile tile = kvp.Value; if (tile.main?.terrain == selectedTerrain && mapMagic.AssignedPreviewTerrain != selectedTerrain) { mapMagic.AssignPreviewTile(tile); mapMagic.AssignedPreviewData.isPreview = true; TerrainTile.OnPreviewAssigned(mapMagic.AssignedPreviewData); UI.RepaintAllWindows(); } } } } } if (selectionMode == SelectionMode.unpin) { HashSet <Terrain> possibleTerrains = new HashSet <Terrain>(pinnedTileTerrains); possibleTerrains.UnionWith(pinnedCustomTerrains); HashSet <Terrain> selectedTerrains = SelectTerrains(possibleTerrains, FrameDraw.unpinColor, false); if (selectedTerrains != null) { UnityEditor.Undo.RegisterFullObjectHierarchyUndo(mapMagic.gameObject, "MapMagic Unpin Terrains"); foreach (Terrain terrain in selectedTerrains) { //terrain-to-coord lut (to pick tile terrain coord faster) Dictionary <Terrain, Coord> terrainToCoordLut = new Dictionary <Terrain, Coord>(); foreach (var kvp in tilesLut) { Coord coord = kvp.Key; TerrainTile tile = kvp.Value; if (tile.main != null) { terrainToCoordLut.Add(tile.main.terrain, coord); } if (tile.draft != null) { terrainToCoordLut.Add(tile.draft.terrain, coord); } } //if it's tile if (terrainToCoordLut.ContainsKey(terrain)) { Coord coord = terrainToCoordLut[terrain]; mapMagic.tiles.Unpin(coord); } //if it's custom if (pinnedCustomTerrains.Contains(terrain)) { TerrainTile tileComponent = terrain.gameObject.GetComponent <TerrainTile>(); mapMagic.tiles.UnpinCustom(tileComponent); GameObject.DestroyImmediate(tileComponent); } } } } //redrawing scene SceneView.lastActiveSceneView.Repaint(); } }
private void DeleteTile(TerrainTile tile) { tile.Clear(); ReloadBuildingsTerrain(); }
public void LoadGame(string name, WorldManager manager) { CreateSchema(); TerrainTile[,] world; List <Herbivore> herbivores = new List <Herbivore>(); List <Carnivore> carnivores = new List <Carnivore>(); int size = 0; int game_id = 0; using (var conn = new SqliteConnection(StaticData.dbPath)) { conn.Open(); using (var cmd = conn.CreateCommand()) { cmd.CommandType = CommandType.Text; cmd.CommandText = "SELECT id, size_factor FROM saved_games WHERE name=@Name"; cmd.Parameters.Add(new SqliteParameter() { ParameterName = "Name", Value = name }); using (var reader = cmd.ExecuteReader()) { while (reader.Read()) { game_id = reader.GetInt32(0); size = reader.GetInt32(1); } } int width = (int)System.Math.Pow(2, size + 1); int height = (int)System.Math.Pow(2, size); world = new TerrainTile[width, height]; cmd.CommandText = "SELECT x, y, type, height, temperature, nutrition, growth_rate, regrowth_left FROM terrain_tiles WHERE game_id=@Game"; cmd.Parameters.Clear(); cmd.Parameters.Add(new SqliteParameter() { ParameterName = "Game", Value = game_id }); using (var reader = cmd.ExecuteReader()) { while (reader.Read()) { int x = reader.GetInt32(0); int y = reader.GetInt32(1); TerrainTile.TerrainType type = (TerrainTile.TerrainType)reader.GetInt32(2); float h = reader.GetFloat(3); float t = reader.GetFloat(4); float n = reader.GetFloat(5); float g = reader.GetFloat(6); int r = reader.GetInt32(7); world[x, y] = new TerrainTile() { height = h, temperature = t, nutrition = n, growth_rate = g, regrowth_left = r, type = type, grazers = new List <Herbivore>(), predators = new List <Carnivore>(), location = new Vector2(x, y) }; } } cmd.CommandText = "SELECT x, y, movement, perception, population, starvation_threshold, fertility, food_efficiency, size, max_growth_factor FROM herbivores WHERE game_id=@Game"; cmd.Parameters.Clear(); cmd.Parameters.Add(new SqliteParameter() { ParameterName = "Game", Value = game_id }); using (var reader = cmd.ExecuteReader()) { while (reader.Read()) { int x = reader.GetInt32(0); int y = reader.GetInt32(1); float m = reader.GetFloat(2); float per = reader.GetFloat(3); int pop = reader.GetInt32(4); float s = reader.GetFloat(5); float f = reader.GetFloat(6); float fe = reader.GetFloat(7); float siz = reader.GetFloat(8); float mgf = reader.GetFloat(9); herbivores.Add(new Herbivore() { location = new Vector2(x, y), movement = m, perception = per, population = pop, starvation_threshold = s, fertility = f, food_efficiency = fe, size = siz, max_growth_factor = mgf }); } } cmd.CommandText = "SELECT x, y, movement, perception, population, starvation_threshold, fertility, last_meal_size FROM carnivores WHERE game_id=@Game"; cmd.Parameters.Clear(); cmd.Parameters.Add(new SqliteParameter() { ParameterName = "Game", Value = game_id }); using (var reader = cmd.ExecuteReader()) { while (reader.Read()) { int x = reader.GetInt32(0); int y = reader.GetInt32(1); float m = reader.GetFloat(2); float per = reader.GetFloat(3); int pop = reader.GetInt32(4); float s = reader.GetFloat(5); float f = reader.GetFloat(6); float lms = reader.GetFloat(7); carnivores.Add(new Carnivore() { location = new Vector2(x, y), movement = m, perception = per, population = pop, starvation_threshold = s, fertility = f, last_meal_size = lms }); } } } } manager.LoadWorld(world, herbivores, carnivores); }
public LinesOnTerrain() { _window = Device.CreateWindow(800, 600, "Research: Lines on Terrain"); _window.Resize += OnResize; _window.RenderFrame += OnRenderFrame; _window.Keyboard.KeyDown += OnKeyDown; _sceneState = new SceneState(); _sceneState.Camera.PerspectiveFarPlaneDistance = 4096; _sceneState.Camera.PerspectiveNearPlaneDistance = 10; _instructions = new HeadsUpDisplay(); _instructions.Texture = Device.CreateTexture2D( Device.CreateBitmapFromText( "u - Use silhouette\ns - Show silhouette\n", new Font("Arial", 24)), TextureFormat.RedGreenBlueAlpha8, false); _instructions.Color = Color.LightBlue; /////////////////////////////////////////////////////////////////// TerrainTile terrainTile = TerrainTile.FromBitmap(new Bitmap(@"ps-e.lg.png")); _tile = new TriangleMeshTerrainTile(_window.Context, terrainTile); _tile.HeightExaggeration = 30.0f; /////////////////////////////////////////////////////////////////// double tileRadius = Math.Max(terrainTile.Resolution.X, terrainTile.Resolution.Y) * 0.5; _camera = new CameraLookAtPoint(_sceneState.Camera, _window, Ellipsoid.UnitSphere); _camera.CenterPoint = new Vector3D(terrainTile.Resolution.X * 0.5, terrainTile.Resolution.Y * 0.5, 0.0); _sceneState.Camera.ZoomToTarget(tileRadius); _sceneState.Camera.Eye = new Vector3D(_xPos, 256, 0); // // Positions // IList <Vector3D> positions = new List <Vector3D>(); double temp = 1.2 * _tile.HeightExaggeration; positions.Add(new Vector3D(0.0, 0.0, -temp)); positions.Add(new Vector3D(0.0, 0.0, temp)); positions.Add(new Vector3D(100.0, 100.0, -temp)); positions.Add(new Vector3D(100.0, 100.0, temp)); positions.Add(new Vector3D(200.0, 100.0, -temp)); positions.Add(new Vector3D(200.0, 100.0, temp)); positions.Add(new Vector3D(256.0, 256.0, -temp)); positions.Add(new Vector3D(256.0, 256.0, temp)); positions.Add(new Vector3D(512.0, 512.0, -temp)); positions.Add(new Vector3D(512.0, 512.0, temp)); // // junk _polylineOnTerrain = new PolylineOnTerrain(); _polylineOnTerrain.Set(_window.Context, positions); _clearState = new ClearState(); // junk string fs = @"#version 330 uniform sampler2D og_texture0; in vec2 fsTextureCoordinates; out vec4 fragmentColor; void main() { if (texture(og_texture0, fsTextureCoordinates).r == 0.0) { fragmentColor = vec4(0.0, 0.0, 0.0, 1.0); } else { discard; } }"; _viewportQuad = new ViewportQuad(_window.Context, fs); }
protected override void OnLoad() { // Get common services and game objects. _graphicsService = _services.GetInstance<IGraphicsService>(); _graphicsScreen = _graphicsService.Screens.OfType<DeferredGraphicsScreen>().First(); var content = _services.GetInstance<ContentManager>(); var scene = _services.GetInstance<IScene>(); _simulation = _services.GetInstance<Simulation>(); var gameObjectService = _services.GetInstance<IGameObjectService>(); _cameraObject = gameObjectService.Objects.OfType<CameraObject>().First(); _previousCameraFar = _cameraObject.CameraNode.Camera.Projection.Far; // Create a new terrain. var terrain = new Terrain(); // The terrain is made up of terrain tiles which can be loaded independently. // Each terrain tile consists of height and normal textures which define the terrain // geometry and terrain layers which define the material (detail textures). // In this sample we create 2x2 tiles. _tiles = new Tile[2, 2]; for (int row = 0; row < 2; row++) { for (int column = 0; column < 2; column++) { // Create a tile and add it to the terrain. // (The tile content is loaded later.) var terrainTile = new TerrainTile(_graphicsService) { CellSize = 1, // The terrain has a resolution of 1 height sample per world space unit. }; terrain.Tiles.Add(terrainTile); // Create a rigid body with a height field for collision detection and add // it to the simulation. (The height data is loaded later.) var heightField = new HeightField { Depth = 1, UseFastCollisionApproximation = false, }; var rigidBody = new RigidBody(heightField, new MassFrame(), null) { MotionType = MotionType.Static, UserData = terrainTile, }; _simulation.RigidBodies.Add(rigidBody); // Store the tile for use later in this sample. _tiles[row, column] = new Tile { TerrainTile = terrainTile, RigidBody = rigidBody, }; } } // Create a terrain node which represents the terrain in the scene graph. // The terrain node is rendered by the TerrainRenderer (see DeferredGraphicsScreen). // The material used to render the terrain is customizable. The material must specify // the effects for the different render passes which we use in the DeferredGraphicsScreen // ("ShadowMap", "GBuffer", "Material"). // The prebuilt DigitalRune content contains standard terrain effects. However, you could // change the effects to change how the material is rendered. // We can create the material by loading a .drmat file. Or we can create the material in // code like this: var shadowMapEffect = content.Load<Effect>("DigitalRune/Terrain/TerrainShadowMap"); var gBufferEffect = content.Load<Effect>("DigitalRune/Terrain/TerrainGBuffer"); var materialEffect = content.Load<Effect>("DigitalRune/Terrain/TerrainMaterial"); var material = new Material { { "ShadowMap", new EffectBinding(_graphicsService, shadowMapEffect, null, EffectParameterHint.Material) }, { "GBuffer", new EffectBinding(_graphicsService, gBufferEffect, null, EffectParameterHint.Material) }, { "Material", new EffectBinding(_graphicsService, materialEffect, null, EffectParameterHint.Material) } }; TerrainNode = new TerrainNode(terrain, material) { // The terrain rendering uses clipmaps. // The clipmaps are updated by the TerrainClipmapRenderer (see DeferredGraphicsScreen) // when the camera moves. // The base clipmap contains the basic geometry info (height, normals, hole info). // It also determines the terrain mesh resolution. BaseClipmap = { CellsPerLevel = 128, NumberOfLevels = 6 }, // The detail clipmap contains the splatted detail textures (e.g. grass, rock, ...). // (The max texture size in XNA is 4096x4096. That means we can fit 9 clipmap levels // into a single texture.) DetailClipmap = { CellsPerLevel = 1365, NumberOfLevels = 9, }, }; scene.Children.Add(TerrainNode); // Load the height and normal maps which define the terrain geometry. InitializeHeightsAndNormals(); // Set the clipmap cell sizes. InitializeClipmapCellSizes(); // Create the terrain layers which define the detail textures (e.g. grass, rock, ...) InitializeTerrainLayers(content); // Special note for AMD GPUs: // If we want anisotropic filtering for the terrain, then we need to enable mipmaps for // AMD GPUs. NVIDIA and Intel can do anisotropic filtering without mipmaps. //TerrainNode.DetailClipmap.EnableMipMap = true; CreateGuiControls(); }
public WireframeNavMeshRenderer(Game game, TerrainTile tile) : base(game, tile) { }
private void Update() { // calculate how far the player is in relation to his last position when the terrain generated int generateX = (int)(player.transform.position.x - oldPlayerPosition.x); int generateY = (int)(player.transform.position.z - oldPlayerPosition.z); //if the moves moves a certain distance away... if (Mathf.Abs(generateX) > maxTilesSeen || Mathf.Abs(generateY) > maxTilesSeen) { float newTileIndex = Time.realtimeSinceStartup; // ... then spawn random settlements for (int i = 0; i < 5; i++) { int generateDistanceX = (int)(player.position.x - settlements.transform.position.x); int generateDistanceZ = (int)(player.position.z - settlements.transform.position.z); Vector3 pos = new Vector3(i + Random.Range(-100, 100) + player.transform.position.x, 2, i + Random.Range(-100, 100) + player.transform.position.z); string newName = "Settlement " + ((int)(pos.x)).ToString() + " , " + ((int)(pos.z)).ToString(); // if a settlement does not exists in the hashatble then add it if (!newSettle.ContainsKey(newName)) { GameObject poi = Instantiate(settlements, pos, Quaternion.identity); poi.name = newName; Settlements s = new Settlements(poi, newTileIndex, transform); newSettle.Add(newName, s); } else { // if a settlement already exists in the hashatble then update its index (newSettle[newName] as Settlements).index = newTileIndex; } } // round down the x and z positions to the nearest integer int planeX = (int)Mathf.Floor(player.transform.position.x / planeSize) * planeSize; int planeZ = (int)Mathf.Floor(player.transform.position.z / planeSize) * planeSize; for (int x = -mapLength; x < mapLength; x++) { for (int y = -mapLength; y < mapLength; y++) { // move the piece one plane size in a given direction Vector3 newPosition = new Vector3((x * planeSize + planeX), 0, (y * planeSize + planeZ)); string terrainTileIndex = "Index at (" + ((int)(newPosition.x)).ToString() + " , " + ((int)(newPosition.z)).ToString() + ")"; // if the piece does not exist then spawn it and add it to the hashtable // if it does then keep it where it is and update its index if (!terrain.ContainsKey(terrainTileIndex)) { GameObject newPlane = Instantiate(prefabTerrain, newPosition, Quaternion.identity); newPlane.name = terrainTileIndex; TerrainTile infiniteTileMember = new TerrainTile(newPlane, newTileIndex, transform); terrain.Add(terrainTileIndex, infiniteTileMember); } else { (terrain[terrainTileIndex] as TerrainTile).tileIndex = newTileIndex; } } } // if a piece is too far away the destroy it, if not then add it to the temp hashtable Hashtable infiniteTerrain = new Hashtable(); foreach (TerrainTile tt in terrain.Values) { if (tt.tileIndex != newTileIndex) { Destroy(tt.newTile); } else { infiniteTerrain.Add(tt.newTile.name, tt); } } Hashtable infiniteSettlements = new Hashtable(); foreach (Settlements ss in newSettle.Values) { if (ss.index != newTileIndex) { Destroy(ss.settlements); } else { infiniteSettlements.Add(ss.settlements.name, ss); } } // combine the temp hashtable to the original one newSettle = infiniteSettlements; terrain = infiniteTerrain; oldPlayerPosition = player.transform.position; } }
internal void FindTerrainTiles() { m_TerrainTiles = new List <PaintContext.TerrainTile>(); Terrain left = originTerrain.leftNeighbor; Terrain right = originTerrain.rightNeighbor; Terrain top = originTerrain.topNeighbor; Terrain bottom = originTerrain.bottomNeighbor; bool wantLeft = (pixelRect.x < 0); bool wantRight = (pixelRect.xMax > (targetTextureWidth - 1)); bool wantTop = (pixelRect.yMax > (targetTextureHeight - 1)); bool wantBottom = (pixelRect.y < 0); if (wantLeft && wantRight) { Debug.LogWarning("PaintContext pixelRect is too large! It should touch a maximum of 2 Terrains horizontally."); wantRight = false; } if (wantTop && wantBottom) { Debug.LogWarning("PaintContext pixelRect is too large! It should touch a maximum of 2 Terrains vertically."); wantBottom = false; } // add center tile m_TerrainTiles.Add(TerrainTile.Make(originTerrain, 0, 0, pixelRect, targetTextureWidth, targetTextureHeight)); // add horizontal and vertical neighbors Terrain horiz = null; Terrain vert = null; Terrain cornerTerrain = null; int horizTileDelta = 0; // how many tiles to move horizontally int vertTileDelta = 0; // how many tiles to move vertically if (wantLeft) { horizTileDelta = -1; horiz = left; } else if (wantRight) { horizTileDelta = 1; horiz = right; } if (wantTop) { vertTileDelta = 1; vert = top; } else if (wantBottom) { vertTileDelta = -1; vert = bottom; } if (horiz) { m_TerrainTiles.Add(TerrainTile.Make(horiz, horizTileDelta * (targetTextureWidth - 1), 0, pixelRect, targetTextureWidth, targetTextureHeight)); // add corner, if we have a link if (wantTop && horiz.topNeighbor) { cornerTerrain = horiz.topNeighbor; } else if (wantBottom && horiz.bottomNeighbor) { cornerTerrain = horiz.bottomNeighbor; } } if (vert) { m_TerrainTiles.Add(TerrainTile.Make(vert, 0, vertTileDelta * (targetTextureHeight - 1), pixelRect, targetTextureWidth, targetTextureHeight)); // add corner, if we have a link if (wantLeft && vert.leftNeighbor) { cornerTerrain = vert.leftNeighbor; } else if (wantRight && vert.rightNeighbor) { cornerTerrain = vert.rightNeighbor; } } if (cornerTerrain != null) { m_TerrainTiles.Add(TerrainTile.Make(cornerTerrain, horizTileDelta * (targetTextureWidth - 1), vertTileDelta * (targetTextureHeight - 1), pixelRect, targetTextureWidth, targetTextureHeight)); } }
private static void RefreshTile(Control button, TerrainTile tile) { button.Text = TerrainSprite.GetTileName(tile); button.BackColor = TerrainSprite.GetTileColor(tile); }
bool ITerrainInfo.TryGetTerrainInfo(TerrainTile r, out TerrainTileInfo info) { return(TryGetTileInfo(r, out info)); }
TerrainTileInfo ITerrainInfo.GetTerrainInfo(TerrainTile r) { return(GetTileInfo(r)); }