public static TiledMap Parse(string tiledMapFilename) { var tilemapDoc = new XmlDocument(); tilemapDoc.Load(tiledMapFilename); var mapElt = tilemapDoc.DocumentElement; RequireAttributeValue(mapElt, "orientation", "orthogonal"); // TODO: Support other render orders. (We will always output right-down order, // so the generator just needs to iterate diferently while writing tiles.) RequireAttributeValue(mapElt, "renderorder", "right-down"); int width = GetIntAttribute(mapElt, "width"); int height = GetIntAttribute(mapElt, "height"); int tileWidth = GetIntAttribute(mapElt, "tilewidth"); int tileHeight = GetIntAttribute(mapElt, "tileheight"); var tilesetElements = mapElt.SelectNodes("tileset"); var tilesets = MapElements(tilesetElements, e => TiledTileset.ParseRef(e, tileWidth, tileHeight)); var layerElements = mapElt.SelectNodes("layer"); var layers = MapElements(layerElements, e => TiledLayer.Parse(e, width, height)); var objectGroupElements = mapElt.SelectNodes("objectgroup"); var objectGroups = MapElements(objectGroupElements, e => TiledObjectGroup.Parse(e, tileWidth, tileHeight)); return(new TiledMap() { MapFilename = tiledMapFilename, Width = width, Height = height, TileWidth = tileWidth, TileHeight = tileHeight, Tilesets = tilesets.ToList(), Layers = layers.ToList(), }); }
// Initialize the xServer base map layers public void InsertXMapBaseLayers(LayerCollection layers, string url, string copyrightText, Size maxRequestSize, string user, string password) { var baseLayer = new TiledLayer("Background") { TiledProvider = new XMapTiledProvider(url, XMapMode.Background) { User = user, Password = password, ContextKey = "in case of context key" }, Copyright = copyrightText, Caption = MapLocalizer.GetString(MapStringId.Background), IsBaseMapLayer = true, Icon = ResourceHelper.LoadBitmapFromResource("Ptv.XServer.Controls.Map;component/Resources/Background.png") }; var labelLayer = new UntiledLayer("Labels") { UntiledProvider = new XMapTiledProvider(url, XMapMode.Town) { User = user, Password = password, ContextKey = "in case of context key" }, Copyright = copyrightText, MaxRequestSize = maxRequestSize, Caption = MapLocalizer.GetString(MapStringId.Labels), Icon = ResourceHelper.LoadBitmapFromResource("Ptv.XServer.Controls.Map;component/Resources/Labels.png") }; layers.Add(baseLayer); layers.Add(labelLayer); }
public void InsertXMapBaseLayers(LayerCollection layers, XMapMetaInfo meta, string profile) { var baseLayer = new TiledLayer("Background") { TiledProvider = new ExtendedXMapTiledProvider(meta.Url, meta.User, meta.Password) { ContextKey = "in case of context key", CustomProfile = profile + "-bg", }, Copyright = meta.CopyrightText, Caption = MapLocalizer.GetString(MapStringId.Background), IsBaseMapLayer = true, Icon = ResourceHelper.LoadBitmapFromResource("Ptv.XServer.Controls.Map;component/Resources/Background.png"), }; var labelLayer = new UntiledLayer("Labels") { UntiledProvider = new XMapTiledProvider( meta.Url, XMapMode.Town) { User = meta.User, Password = meta.Password, ContextKey = "in case of context key", CustomProfile = profile + "-fg", }, Copyright = meta.CopyrightText, MaxRequestSize = meta.MaxRequestSize, Caption = MapLocalizer.GetString(MapStringId.Labels), Icon = ResourceHelper.LoadBitmapFromResource("Ptv.XServer.Controls.Map;component/Resources/Labels.png"), }; layers.Add(baseLayer); layers.Add(labelLayer); }
/// <summary> <para>Adds a shape layer with selection logic to the map. The shapes are managed by SharpMap.</para> /// <para>See the <conceptualLink target="427ab62e-f02d-4e92-9c26-31e0f89d49c5"/> topic for an example.</para> </summary> /// <param name="wpfMap">The map to add the layer to.</param> /// <param name="name">The name of the layer.</param> /// <param name="shapeFilePath">The full qualified path to the shape file.</param> /// <param name="idx">The index where to add the layer in the hierarchy.</param> /// <param name="isBaseMapLayer">Specifies if the layer is a base map layer.</param> /// <param name="opacity">The initial opacity.</param> /// <param name="icon">The icon used in the layers control.</param> #region doc:AddShapeLayer method public static void AddShapeLayer(this WpfMap wpfMap, string name, string shapeFilePath, int idx, bool isBaseMapLayer, double opacity, System.Windows.Media.Imaging.BitmapImage icon) { // the collection of selected elements var selectedRegions = new System.Collections.ObjectModel.ObservableCollection <System.Windows.Media.Geometry>(); // add a layer which uses SharpMap (by using SharpMapTiledProvider and ShapeSelectionCanvas) #region doc:create TiledLayer var sharpMapLayer = new TiledLayer(name) { // Create canvas categories. First one for the ordinary tile content. Second one for the selection canvas. CanvasCategories = new[] { CanvasCategory.Content, CanvasCategory.SelectedObjects }, // Create delegates for the content canvas and the selection canvas. CanvasFactories = new BaseLayer.CanvasFactoryDelegate[] { m => new TiledCanvas(m, new SharpMapTiledProvider(shapeFilePath)) { IsTransparentLayer = true }, m => new ShapeSelectionCanvas(m, shapeFilePath, selectedRegions) }, // Set some more initial values... Opacity = opacity, IsBaseMapLayer = isBaseMapLayer, Icon = icon }; #endregion // doc:create TiledLayer wpfMap.Layers.Insert(idx, sharpMapLayer); }
/// <summary> Extension method which adds a Microsoft Bing layer to the map. </summary> /// <param name="wpfMap"> The map to add the layer to. </param> /// <param name="name"> The name of the layer. </param> /// <param name="idx"> The index of the layer in the layer hierarchy. </param> /// <param name="bingKey"> The Microsoft Bing key to use. </param> /// <param name="set"> The imagery set to be used. </param> /// <param name="version"> The Microsoft Bing version. </param> /// <param name="isBaseMapLayer"> Specifies if the added layer should act as a base layer. </param> /// <param name="opacity"> The initial opacity of the layer. </param> /// <param name="icon"> The icon of the layer used within the layer gadget. </param> /// <param name="copyrightImagePanel"> The panel where the bing logo should be added. </param> public static void AddBingLayer(this WpfMap wpfMap, string name, int idx, string bingKey, BingImagerySet set, BingMapVersion version, bool isBaseMapLayer, double opacity, BitmapImage icon, Panel copyrightImagePanel) { var metaInfo = new BingMetaInfo(set, version, bingKey); // add a bing aerial layer var bingLayer = new TiledLayer(name) { TiledProvider = new BingTiledProvider(metaInfo), IsBaseMapLayer = isBaseMapLayer, Opacity = opacity, Icon = icon }; wpfMap.Layers.Insert(idx, bingLayer); try { var bingLogo = new Image { Stretch = Stretch.None, HorizontalAlignment = HorizontalAlignment.Left, Source = new BitmapImage(new Uri(metaInfo.LogoUri)) }; copyrightImagePanel.Children.Add(bingLogo); copyrightImagePanel.Visibility = Visibility.Visible; } catch (Exception) { //Just silently catch exceptions if the image cannot be displayed! } }
public void InsertXMapBaseLayers(LayerCollection layers, XMapMetaInfo meta, string profile) { var baseLayer = new TiledLayer("Background") { TiledProvider = new ExtendedXMapTiledProvider(meta.Url, meta.User, meta.Password) { ContextKey = "in case of context key", CustomProfile = profile + "-bg" }, Copyright = meta.CopyrightText, Caption = MapLocalizer.GetString(MapStringId.Background), IsBaseMapLayer = true, Icon = ResourceHelper.LoadBitmapFromResource("Ptv.XServer.Controls.Map;component/Resources/Background.png") }; var labelLayer = new UntiledLayer("Labels") { UntiledProvider = new XMapTiledProvider( meta.Url, XMapMode.Town) { User = meta.User, Password = meta.Password, ContextKey = "in case of context key", CustomProfile = profile + "-fg" }, Copyright = meta.CopyrightText, MaxRequestSize = meta.MaxRequestSize, Caption = MapLocalizer.GetString(MapStringId.Labels), Icon = ResourceHelper.LoadBitmapFromResource("Ptv.XServer.Controls.Map;component/Resources/Labels.png") }; layers.Add(baseLayer); layers.Add(labelLayer); }
public LayerPropertiesController() { TiledWidth.ValueChanged += (newValue) => { TiledLayer tiled = (_layer as DocTiledLayer).Layer; tiled.TiledWidth = newValue; }; TiledHeight.ValueChanged += (newValue) => { TiledLayer tiled = (_layer as DocTiledLayer).Layer; tiled.TiledHeight = newValue; }; Select.ValueChanged += (val) => { if (val) { new Tools.Select(); } }; Eraser.ValueChanged += (val) => { if (val) { new Tools.EraseTile(); } }; Accelerators.Instance.Register(KeyModifiers.None, Keys.X, () => OnAccelerator("Erase")); Accelerators.Instance.Register(KeyModifiers.None, Keys.Escape, () => OnAccelerator("Escape")); }
private async Task <IEnumerable <Sprite> > _AddLayer(TiledLayer layer, string name, int depth = 0) { TiledMap tileMap = TileMap; int mapX = 0, mapY = 0, width = tileMap.TileWidth, height = tileMap.TileHeight; foreach (var strValue in layer.ToString().Split(',')) { int localId; var tileSet = findTileSet(Int32.Parse(strValue), out localId); int tileX = localId % tileMap.Height, tileY = localId / tileMap.Height; AddSprite(await getTexture(tileSet), new Vector2(mapX, mapY), new Rectangle(tileX, tileY, width, height), depth); if (mapX >= layer.Width) { mapX = 0; mapY += height; } else { mapX += width; } } return(Layers[name] = ConsumeAddedStates()); }
private void ReadLayers(ContentReader reader, TiledMap tiledMap) { var layerCount = reader.ReadInt32(); for (var i = 0; i < layerCount; i++) { var layer = new TiledLayer(); layer.Data = new TiledData(); layer.Name = reader.ReadString(); layer.Width = reader.ReadInt32(); layer.Height = reader.ReadInt32(); var tileDataCount = reader.ReadInt32(); layer.Data.Tiles = new uint[layer.Width, layer.Height]; for (int y = 0; y < layer.Height; ++y) { for (int x = 0; x < layer.Width; ++x) { layer.Data.Tiles[x, y] = reader.ReadUInt32(); } } tiledMap.Layers.Add(layer); } }
/// <summary> /// Sets the value of the TiledLayerFullExtent attached property to a specified TiledLayer. /// </summary> /// <param name="element">The TiledLayer to which the attached property is written.</param> /// <param name="value">The needed TiledLayerFullExtent value.</param> public static void SetTiledLayerFullExtent(TiledLayer element, Envelope value) { if (element == null) { throw new ArgumentNullException("element"); } element.SetValue(TiledLayerFullExtentProperty, value); }
/// <summary> /// Gets the value of the TiledLayerFullExtent attached property for a specified TiledLayer. /// </summary> /// <param name="element">The TiledLayer from which the property value is read.</param> /// <returns>The TiledLayerFullExtent property value for the TiledLayer.</returns> public static Envelope GetTiledLayerFullExtent(TiledLayer element) { if (element == null) { throw new ArgumentNullException("element"); } return(element.GetValue(TiledLayerFullExtentProperty) as Envelope); }
void DrawCurrentLayer(ref UiViewDrawParameters parameters) { if (Document.Current.SelectedLayer is DocTiledLayer) { TiledLayer layer = Document.Current.SelectedLayer.Layer as TiledLayer; DrawTiles(ref parameters, layer); } }
protected override void FillWithData(DocLayer layer) { base.FillWithData(layer); TiledLayer tl = layer.Layer as TiledLayer; tl.Resize(Width, Height); tl.TiledWidth = TiledWidth; tl.TiledHeight = TiledHeight; tl.Tileset = Tileset; }
static void BuildTile(TileMap collection, TiledLayer layer, int index, int gid) { var newTile = new TileMapTile() { Gid = gid, GroupName = layer.Name, Position = new Point( index % collection.Columns, index / collection.Columns) }; collection._tiles.Add(newTile); }
void PaintTiles(Vector2 position) { Document.Current.SetModified(); TiledLayer layer = Document.Current.SelectedLayer.Layer as TiledLayer; if (layer != null) { int startX = (int)position.X; int startY = (int)position.Y; int endX = startX + _tiles.GetLength(0); int endY = startY + _tiles.GetLength(1); endX = Math.Min(1024, endX); endY = Math.Min(1024, endY); //if(endX > layer.Width || endY > layer.Height) //{ // layer.Resize( Math.Max(endX, layer.Width), Math.Max(endY, layer.Height)); // Document.Current.SelectedLayer.InvalidateProperties(); //} Rectangle rect = Rectangle.Empty; rect.X = startX; rect.Y = startY; rect.Width = endX - startX; rect.Height = endY - startY; if (_invalidRect.Intersects(rect)) { return; } _invalidRect = rect; endX = Math.Min(endX, layer.Width); endY = Math.Min(endY, layer.Height); for (int idxX = startX; idxX < endX; ++idxX) { for (int idxY = startY; idxY < endY; ++idxY) { ushort tile = _tiles[idxX - startX, idxY - startY]; layer.Content[idxX, idxY] = tile; } } } }
public override void Draw(AdvancedDrawBatch batch, Point startPosition, Vector2 position, float scale) { int size = UnitToPixels(scale); int unitSize = UnitToPixels(1); Rectangle target = new Rectangle(0, 0, size, size); position = position.TrimToIntValues() * size; SamplerState oldSamplerState = batch.SamplerState; batch.SamplerState = SamplerState.PointClamp; TiledLayer layer = Document.Current.SelectedLayer.Layer as TiledLayer; if (layer != null) { int maxX = _tiles.GetLength(0); int maxY = _tiles.GetLength(1); int targetX = (int)(position.X / size); int targetY = (int)(position.Y / size); maxX = Math.Min(layer.Width - targetX, maxX); maxY = Math.Min(layer.Height - targetY, maxY); position.X -= startPosition.X; position.Y -= startPosition.Y; for (int idxX = 0; idxX < maxX; ++idxX) { target.X = (int)(idxX * size + position.X); for (int idxY = 0; idxY < maxY; ++idxY) { target.Y = (int)(idxY * size + position.Y); ushort tile = _tiles[idxX, idxY]; Point src = new Point(tile & 0xff, (tile >> 8) & 0xff); Rectangle source = new Rectangle(src.X * unitSize, src.Y * unitSize, unitSize - 1, unitSize - 1); batch.DrawImage(_tileset, target, source, Color.White * 0.5f); } } } batch.SamplerState = oldSamplerState; }
private void ProcessLayer(TiledLayer layer, TiledMap map) { var data = layer.Data; foreach (var chunk in data.Chunks) { for (var i = 0; i < chunk.Tiles.Count; i++) { var tile = chunk.Tiles[i]; if (tile.Gid == 0) { continue; } var set = GetTilesetFromGid(tile, map); var x = (i % chunk.Width); var y = (i - x) / chunk.Width; x = (x + chunk.X) * set.TileWidth + layer.OffsetX + set.Offset.XOffset; y = (y + chunk.Y) * set.TileHeight + layer.OffsetY + set.Offset.YOffset; var setPos = (int)tile.Gid - set.FirstGid; var bgx = setPos % set.Columns; var bgy = (setPos - bgx) / set.Columns; bgx = bgx * (set.Spacing + set.TileWidth) + set.Margin; bgy = bgy * (set.Spacing + set.TileHeight) + set.Margin; var name = GetTilesetName(set); Write($"screen.add_tile({name}, {bgx}, {bgy}, {set.TileWidth}, {set.TileHeight}, {x}, {y}, {_depth});"); } } for (var i = 0; i < data.Tiles.Count; i++) { var tile = data.Tiles[i]; if (tile.Gid == 0) { continue; } var set = GetTilesetFromGid(tile, map); var x = (i % map.Width); var y = ((i - x) / map.Width); x = x * set.TileWidth + layer.OffsetX + set.Offset.XOffset; y = y * set.TileHeight + layer.OffsetY + set.Offset.YOffset; var setPos = (int)tile.Gid - set.FirstGid; var bgx = setPos % set.Columns; var bgy = (setPos - bgx) / set.Columns; bgx = bgx * (set.Spacing + set.TileWidth) + set.Margin; bgy = bgy * (set.Spacing + set.TileHeight) + set.Margin; var name = GetTilesetName(set); Write($"screen.add_tile({name}, {bgx}, {bgy}, {set.TileWidth}, {set.TileHeight}, {x}, {y}, {_depth});"); } }
public static TiledLayer ToTiledLayer(this JsonLayer jsonLayer) { var tiledLayer = new TiledLayer(); tiledLayer.Data = jsonLayer.Data; tiledLayer.Height = jsonLayer.Height; tiledLayer.Id = jsonLayer.Id; tiledLayer.Name = jsonLayer.Name; tiledLayer.Type = jsonLayer.Type; tiledLayer.Visible = jsonLayer.Visible; tiledLayer.Width = jsonLayer.Width; tiledLayer.X = jsonLayer.X; tiledLayer.Y = jsonLayer.Y; return(tiledLayer); }
public TiledLayer GetLayer(string layerName) { TiledLayer layer = null; foreach (var tempLayer in layers) { if (tempLayer.name == layerName) { layer = tempLayer; break; } } return(layer); }
public override void OnDown(Vector2 position) { Document.Current.SetModified(); TiledLayer layer = Document.Current.SelectedLayer.Layer as TiledLayer; if (layer != null) { int startX = (int)position.X; int startY = (int)position.Y; if (startX < layer.Width && startY < layer.Height) { layer.Content[startX, startY] = TiledLayer.Empty; } } }
/// <summary> /// Inserts the xMapServer base layers, i.e. the background layers for areas like forests, rivers, population areas, et al, /// and their corresponding labels. /// </summary> /// <param name="layers">The LayerCollection instance, used as an extension. </param> /// <param name="meta">Meta information for xMapServer, further details can be seen in the <see cref="XMapMetaInfo"/> description. </param> public static void InsertXMapBaseLayers(this LayerCollection layers, XMapMetaInfo meta) { var baseLayer = new TiledLayer(BackgroundLayerName) { TiledProvider = new XMapTiledProvider(meta.Url, meta.User, meta.Password, XMapMode.Background), Copyright = meta.CopyrightText, Caption = MapLocalizer.GetString(MapStringId.Background), IsBaseMapLayer = true, Icon = ResourceHelper.LoadBitmapFromResource("Ptv.XServer.Controls.Map;component/Resources/Background.png") }; if (BaseLayerSuccessor != null && layers[BaseLayerSuccessor] != null) { layers.Insert(layers.IndexOf(layers[BaseLayerSuccessor]), baseLayer); } else { // add tile layer layers.Add(baseLayer); BaseLayerSuccessor = null; } // don't add overlay layer for Decarta-powered maps (basemap is completely rendered on tiles) if (XServerUrl.IsDecartaBackend(meta.Url)) { return; } var labelLayer = new UntiledLayer(LabelsLayerName) { UntiledProvider = new XMapTiledProvider(meta.Url, meta.User, meta.Password, XMapMode.Town), MaxRequestSize = meta.MaxRequestSize, Caption = MapLocalizer.GetString(MapStringId.Labels), Icon = ResourceHelper.LoadBitmapFromResource("Ptv.XServer.Controls.Map;component/Resources/Labels.png") }; if (LabelLayerPredecessor != null && layers[LabelLayerPredecessor] != null && layers.IndexOf(layers[LabelLayerPredecessor]) < layers.Count) { layers.Insert(layers.IndexOf(layers[LabelLayerPredecessor]) + 1, labelLayer); } else { // add label layer layers.Add(labelLayer); LabelLayerPredecessor = null; } }
static void BuildLayout( TileMap collection, List <TiledTileSet> tileSets, TiledLayer layer) { var renderer = null as TileMapRenderer; for (int i = 0; i < layer.GidMap.Length; i++) { var gid = layer.GidMap[i]; if (gid == 0) { continue; } var tileSet = tileSets.First(x => x.WithinOffset(gid)); gid -= tileSet.GidOffset; if (tileSet.TileSet == null) { BuildTile(collection, layer, i, gid); } else { if (renderer == null) { renderer = new TileMapRenderer(collection.Size, collection.TileSize); } var position = new Point(i % collection.Columns, i / collection.Columns); var texture = tileSet.TileSet[gid]; renderer.Fill(texture, position, new Point(1, 1)); } } if (renderer != null) { var layout = new TileMapLayout() { GroupName = layer.Name, Renderer = renderer, }; layer.Properties.ToList() .ForEach(x => layout._properties.Add(x.Key, x.Value)); collection._layouts.Add(layout); } }
private void OnDone(TiledLayer layer = null) { var curCount = Interlocked.Decrement(ref _loadCount); if (layer != null) { AssociatedObject.SetCurrentValue(CurrentExtentProperty, layer.FullExtent); } if (curCount != 0) { return; } IsLoading = false; Progress = 0; }
public string OnApplyHeight(string text) { TiledLayer tiled = (_layer as DocTiledLayer).Layer; int value; int.TryParse(text, out value); int newValue = Math.Max(1, Math.Min(1024, value)); if (newValue != value) { text = string.Format("{0}", newValue); } tiled.Resize(tiled.Width, value); Document.Current.SetModified(); return(text); }
private static uint[,] DecodeBase64Data(TiledLayer layer) { var width = layer.Width; var height = layer.Height; var tileList = new uint[width, height]; var data = layer.Data; var encodedData = data.Value.Trim(); var decodedData = Convert.FromBase64String(encodedData); using (var stream = OpenStream(decodedData, data.Compression)) using (var reader = new BinaryReader(stream)) { for (var y = 0; y < height; y++) { for (var x = 0; x < width; x++) { tileList[x, y] = reader.ReadUInt32(); } } } return(tileList); }
void UpdateProperties() { Layer layer = _layer.Layer; LayerName.Format("{0}", _layer.Name); LayerSpeedX.Format("{0}", (int)(layer.ScrollSpeed.X * 100)); LayerSpeedY.Format("{0}", (int)(layer.ScrollSpeed.Y * 100)); if (_layer is DocTiledLayer) { TiledLayer tiled = (_layer as DocTiledLayer).Layer; LayerWidth.Format("{0}", tiled.Width); LayerHeight.Format("{0}", tiled.Height); ShowVector.Value = false; ShowTiled.Value = true; TiledWidth.Value = tiled.TiledWidth; TiledHeight.Value = tiled.TiledHeight; } else { ShowVector.Value = true; ShowTiled.Value = false; } }
/// <summary> /// Tries to create a HERE layer with specified account information. Throws an exception if the key is wrong. /// </summary> protected override void Enable() { #region doc:HereSatelliteView const string hereStatelliteUrl = "http://{0}.aerial.maps.api.here.com/maptile/2.1/maptile/newest/satellite.day/{3}/{1}/{2}/256/png8?app_id={app_id}&app_code={app_code}"; var metaInfo = new HereMetaInfo(Properties.Settings.Default.HereAppId, Properties.Settings.Default.HereAppCode); if (string.IsNullOrEmpty(metaInfo.AppCode) || string.IsNullOrEmpty(metaInfo.AppId)) { // Throws an exception if no valid access information was specified. throw new Exception("Please enter valid HERE access information."); } // Insert on top of xServer background. var idx = wpfMap.Layers.IndexOf(wpfMap.Layers["Background"]) + 1; var hereUrl = hereStatelliteUrl.Replace("{app_id}", metaInfo.AppId).Replace("{app_code}", metaInfo.AppCode); var hereSatelliteLayer = new TiledLayer("HERE_Satellite") { TiledProvider = new RemoteTiledProvider { MinZoom = 0, MaxZoom = 20, RequestBuilderDelegate = (x, y, z) => String.Format(hereUrl, (x + y) % 4 + 1, x, y, z) }, IsBaseMapLayer = true, Opacity = .8, Icon = ResourceHelper.LoadBitmapFromResource("Ptv.XServer.Controls.Map;component/Resources/Aerials.png"), Copyright = "© HERE", Caption = "Here Satellite", }; wpfMap.Layers.Insert(idx, hereSatelliteLayer); #endregion }
public TiledMap(string fileText, string layerName) { XmlDocument doc = new XmlDocument(); doc.LoadXml(fileText); XmlNode map = XmlUtils.FindChild(doc, "map"); XmlAttribute widthAt = XmlUtils.FindAttribute(map, "width"); XmlAttribute heightAt = XmlUtils.FindAttribute(map, "height"); width = int.Parse(widthAt.InnerText); height = int.Parse(heightAt.InnerText); List <XmlNode> layersNodes = XmlUtils.FindChilds(map, "layer"); foreach (XmlNode layerNode in layersNodes) { if (XmlUtils.FindAttribute(layerNode, "name").InnerText == layerName) { layer = new TiledLayer(layerNode); return; } } }
/// <summary> /// Reloads the tmx file and regenerates the 2D map /// </summary> private void ReloadMap(string mapFile) { while (rootTransform.childCount > 0) { for (int i = 0; i < rootTransform.childCount; i++) { GameObject child = rootTransform.GetChild(i).gameObject; DestroyImmediate(child); } } XmlSerializer mapFileReader = new XmlSerializer(typeof(TiledMap)); string mapFolder = mapFile.Substring(0, mapFile.LastIndexOfAny(FILEPATH_SEPARATORS) + 1); TiledMap map = null; using (XmlTextReader reader = new XmlTextReader(mapFile)) { map = (TiledMap)mapFileReader.Deserialize(reader); } if (map == null || map.layers == null || map.layers.Length == 0) { return; } if (map.tileSetEntries != null && map.tileSetEntries.Length > 0) { map.tileSets = new TiledTileSetFile[map.tileSetEntries.Length]; XmlSerializer tileSetFileReader = new XmlSerializer(typeof(TiledTileSetFile)); for (int i = 0; i < map.tileSetEntries.Length; i++) { string tileSetFile = map.tileSetEntries[i].source; List <string> mapFolderParts = new List <string>(mapFolder.Split("/".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)); List <string> tileSetFileParts = new List <string>(tileSetFile.Split("/".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)); string pathStart = tileSetFileParts[0]; while (pathStart == "..") { tileSetFileParts.RemoveAt(0); mapFolderParts.RemoveAt(mapFolderParts.Count - 1); pathStart = tileSetFileParts[0]; } string tileSetPath = string.Join("/", new string[] { string.Join("/", mapFolderParts.ToArray()), string.Join("/", tileSetFileParts.ToArray()) }); using (XmlTextReader reader = new XmlTextReader(tileSetPath)) { map.tileSets[i] = (TiledTileSetFile)tileSetFileReader.Deserialize(reader); } string loc = Application.dataPath.Replace("Assets", "") + tileSetPath; tsxOriginalLocations.Add(loc); } } int z = 0; for (int l = map.layers.Length - 1; l >= 0; l--) { TiledLayer layer = map.layers[l]; spriteCache = new List <Sprite>(); usedTiles = new List <int>(); int w, h; w = layer.width; h = layer.height; GameObject layerObject = new GameObject(layer.name); layerObject.transform.parent = rootTransform; layerObject.isStatic = true; TiledProperty[] layerProperties = layer.customProperties; if (layerProperties != null && layerProperties.Length > 0) { LayerCustomProperties properties = layerObject.AddComponent <LayerCustomProperties>(); for (int i = 0; i < layerProperties.Length; i++) { if (layerProperties[i].name.ToLower().Equals("height")) { float constantHeight; if (float.TryParse(layerProperties[i].value, out constantHeight)) { properties.height = constantHeight; } } } } string[] layerData = layer.data.Value.Trim().Split(ROW_SEPARATOR, System.StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < h; i++) { string[] row = layerData[i].Split(COMMA_SEPARATOR); for (int j = 0; j < w; j++) { uint tid = uint.Parse(row[j]); bool flipX = (tid & FLIPPED_HORIZONTALLY_FLAG) >> 31 == 1; tid &= ~FLIPPED_HORIZONTALLY_FLAG; bool flipY = (tid & FLIPPED_VERTICALLY_FLAG) >> 30 == 1; tid &= ~FLIPPED_VERTICALLY_FLAG; bool flipDiag = (tid & FLIPPED_DIAGONALLY_FLAG) >> 29 == 1; tid &= ~FLIPPED_DIAGONALLY_FLAG; int tileID = (int)tid; if (tileID != 0) { Vector3 tilePosition = new Vector3((w * -0.5f) + j, (h * 0.5f) - i, 0); GameObject tileObject = new GameObject("TILE[" + i + "," + j + "]"); tileObject.isStatic = true; tileObject.transform.position = tilePosition; tileObject.transform.parent = layerObject.transform; //tileObject.transform.localScale = new Vector3(1.01f, 1.01f, 1.0f); SpriteRenderer sr = tileObject.AddComponent <SpriteRenderer>(); sr.sortingOrder = z; if (flipDiag) { tileObject.transform.Rotate(0, 0, 90); tileObject.transform.localScale = new Vector3(1, -1, 1); } sr.flipX = flipX; sr.flipY = flipY; int spriteIndex = usedTiles.IndexOf(tileID); if (spriteIndex < 0) { //new tile Sprite sp = GetTile(tileID, map); spriteCache.Add(sp); usedTiles.Add(tileID); sr.sprite = sp; } else { sr.sprite = spriteCache[spriteIndex]; } AnimationFrame[] frames = GetAnimations(tileID, map); if (frames != null) { AnimatedSprite anim = tileObject.AddComponent <AnimatedSprite>(); anim.frames = frames; } //Add colliders TiledObjectGroup group = GetObjectsGroup(map, tileID); if (group != null && group.objects != null) { float ppu = sr.sprite.pixelsPerUnit; Collider2D col; foreach (TiledTObject obj in group.objects) { if (obj.polygon != null) { Vector2 startPoint = new Vector2(obj.x / ppu - 0.5f, -obj.y / ppu + 0.5f); Vector2[] points = obj.polygon.GetPoints(); for (int k = 0; k < points.Length; k++) { points[k].x /= ppu; points[k].y /= -ppu; points[k].x += startPoint.x; points[k].y += startPoint.y; } col = tileObject.AddComponent <PolygonCollider2D>(); RotatePoints(points, -obj.rotation, points[0]); if (flipY) { RotatePoints(points, 180.0f, Vector3.zero); } ((PolygonCollider2D)col).points = points; } else if (obj.polyline != null) { Vector2 startPoint = new Vector2(obj.x / ppu - 0.5f, -obj.y / ppu + 0.5f); Vector2[] points = obj.polyline.GetPoints(); for (int k = 0; k < points.Length; k++) { points[k].x /= ppu; points[k].y /= -ppu; points[k].x += startPoint.x; points[k].y += startPoint.y; } col = tileObject.AddComponent <EdgeCollider2D>(); RotatePoints(points, -obj.rotation, points[0]); ((EdgeCollider2D)col).points = points; } else if (obj.ellipse != null) { Vector2 center = new Vector2(obj.x / ppu - 0.5f, -obj.y / ppu + 0.5f); float width = obj.width / ppu; float height = obj.height / ppu; center.x += width / 2.0f; center.y -= height / 2.0f; if (Mathf.Abs(width - height) < 0.1f) { col = tileObject.AddComponent <CircleCollider2D>(); float radius = Mathf.Max(height, width) / 2.0f; ((CircleCollider2D)col).radius = radius; } else { int vertices = 24; col = tileObject.AddComponent <PolygonCollider2D>(); Vector2[] points = new Vector2[vertices]; float angStep = 360.0f / vertices; Vector2 rotationCenter = new Vector2(float.MaxValue, float.MinValue); for (int p = 0; p < points.Length; p++) { float ang = angStep * p * Mathf.Deg2Rad; float x = width * Mathf.Cos(ang) * 0.5f; float y = height * Mathf.Sin(ang) * 0.5f; points[p] = new Vector2(x, y); if (x < rotationCenter.x) { rotationCenter.x = x; } if (y > rotationCenter.y) { rotationCenter.y = y; } } RotatePoints(points, -obj.rotation, rotationCenter); ((PolygonCollider2D)col).points = points; } col.offset = center; } else { Vector2 offset = new Vector2(obj.x / ppu, -obj.y / ppu); float colWidth = obj.width / ppu; float colHeight = obj.height / ppu; Vector2[] points = new Vector2[4]; float x = obj.x / ppu - 0.5f; float y = -obj.y / ppu + 0.5f; points[0] = new Vector2(x, y); points[1] = new Vector2(x + colWidth, y); points[2] = new Vector2(x + colWidth, y - colHeight); points[3] = new Vector2(x, y - colHeight); RotatePoints(points, -obj.rotation, points[0]); col = tileObject.AddComponent <PolygonCollider2D>(); ((PolygonCollider2D)col).points = points; if (col != null) { col.offset += new Vector2(group.offsetX / ppu, -group.offsetY / ppu); } } } } } } } z--; } Resources.UnloadUnusedAssets(); }
void DrawTiles(ref UiViewDrawParameters parameters, TiledLayer layer) { Rectangle bounds = ScreenBounds; AdvancedDrawBatch batch = parameters.DrawBatch; SamplerState oldSamplerState = batch.SamplerState; batch.SamplerState = SamplerState.PointClamp; int width = layer.Width; int height = layer.Height; float zoom = (float)_zoom.Value / 100f; int unitSize = Tools.Tool.UnitToPixels(zoom); int tileSize = Tools.Tool.UnitToPixels(1); Rectangle target = new Rectangle(bounds.X - CurrentPosition.X, bounds.Y - CurrentPosition.Y, unitSize, unitSize); Rectangle source = new Rectangle(0, 0, tileSize - 1, tileSize - 1); Texture2D tileset = CurrentTemplate.Instance.Tileset(layer.Tileset).Item2; int startY = target.Y; int maxY = 0; ushort[,] tiles = layer.Content; for (int idxX = 0; idxX < width; ++idxX) { target.Y = startY; if (target.Right >= bounds.X && target.X <= bounds.Right) { for (int idxY = 0; idxY < height; ++idxY) { if (target.Bottom >= bounds.Y && target.Y <= bounds.Bottom) { ushort tile = tiles[idxX, idxY]; if (tile != 0xffff) { source.X = (tile & 0xff) * tileSize; source.Y = ((tile >> 8) & 0xff) * tileSize; batch.DrawImage(tileset, target, source, Color.White * 0.5f); } } target.Y += unitSize; maxY = Math.Max(target.Y, maxY); } } target.X += unitSize; } Color color = Color.White * 0.25f; batch.DrawLine(new Point(target.X, bounds.Top), new Point(target.X, maxY), color); batch.DrawLine(new Point(bounds.Left, maxY), new Point(target.X, maxY), color); batch.SamplerState = oldSamplerState; }
/// <summary> /// Gets the value of the TiledLayerFullExtent attached property for a specified TiledLayer. /// </summary> /// <param name="element">The TiledLayer from which the property value is read.</param> /// <returns>The TiledLayerFullExtent property value for the TiledLayer.</returns> public static Envelope GetTiledLayerFullExtent(TiledLayer element) { if (element == null) { throw new ArgumentNullException("element"); } return element.GetValue(TiledLayerFullExtentProperty) as Envelope; }
public DocTiledLayer(string name) : base("Tiles") { Name.StringValue = name; _layer = new TiledLayer(); }
private static void ReadGenericLayerInformation(TiledLayer layer, XElement root) { layer.Name = root.ReadAttribute("name", string.Empty); layer.X = root.ReadAttribute("x", 0); layer.Y = root.ReadAttribute("y", 0); layer.Width = root.ReadAttribute("width", 0); layer.Height = root.ReadAttribute("height", 0); layer.Opacity = root.ReadAttribute("opacity", 1f); layer.Visible = root.ReadAttribute("visible", true); // Read layer properties. PropertyParser.ReadProperties(layer, root); }