Example #1
0
        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(),
            });
        }
        private void ProcessObjectGroup(TiledObjectGroup group)
        {
            foreach (var obj in group.Objects)
            {
                var x = (obj.X ?? 0) + group.OffsetX;
                var y = (obj.Y ?? 0) + group.OffsetY;

                if (obj.Properties.Count == 0)
                {
                    Write($"screen.add(new {obj.Type}({x}, {y}, {obj.Width ?? 1}, {obj.Height ?? 1}));");
                }
                else
                {
                    Write($"inst = new {obj.Type}({x}, {y}, {obj.Width ?? 1}, {obj.Height ?? 1});");
                    foreach (var prop in obj.Properties)
                    {
                        string value;
                        if (prop.Type == PropertyType.Color)
                        {
                            var color = (TiledColor)prop.Value;
                            value = $"make_color({color.Red}, {color.Green}, {color.Blue}, {color.Alpha})";
                        }
                        else
                        {
                            value = prop.Value.ToString();
                        }
                        Write($"inst.{prop.Name} = {value};");
                    }
                    Write("screen.add(inst);");
                }
            }
        }
Example #3
0
        private static IEnumerable <EntityContent> GetMapObjects(TiledObjectGroup layer)
        {
            var result = new List <EntityContent>();

            foreach (var obj in layer.Objects)
            {
                if (string.IsNullOrWhiteSpace(obj.Type))
                {
                    throw new InvalidOperationException("Found object without type!");
                }
                if (string.IsNullOrWhiteSpace(obj.Name))
                {
                    throw new InvalidOperationException("Found object without name!");
                }

                var content = new EntityContent();
                content.Name     = obj.Name;
                content.Type     = obj.Type;
                content.Position = new Vector2(obj.X, obj.Y);

                foreach (var property in obj.Properties)
                {
                    var objProperty = new PropertyContent();
                    objProperty.Name  = property.Key;
                    objProperty.Value = property.Value;

                    content.Properties.Add(objProperty);
                }

                result.Add(content);
            }
            return(result);
        }
Example #4
0
        private void SetupMapEvents(TiledObjectGroup mapObjects)
        {
            foreach (var eventEmitter in mapObjects.objectsWithName(TiledObjects.EventEmitter))
            {
                var bounds = new RectangleF(eventEmitter.position, new Vector2(eventEmitter.width, eventEmitter.height));
                var props  = eventEmitter.properties;
                var type   = props["type"];
                var key    = props["key"];

                switch (type)
                {
                case "timed":
                    float.TryParse(props["interval_min"], out float intervalMin);
                    float.TryParse(props["interval_max"], out float intervalMax);
                    int.TryParse(props["repeat"], out int repeat);

                    scene.addEntity(new TimedEventEmitter(this, key, intervalMin, intervalMax, repeat));
                    break;

                case "collision":
                    int.TryParse(props["physics_layer"], out int physicsLayer);
                    var c = scene.addEntity(new CollisionEventEmitter(this, key, bounds, physicsLayer));
                    break;

                case "interact":
                    var i = scene.addEntity(new InteractEventEmitter(this, key, bounds));
                    Console.WriteLine("interactable placed at " + i.position);
                    break;

                default:
                    Console.Error.WriteLine($"MapEventEmitter of type {type} not recognized!");
                    break;
                }
            }
        }
        public static PlayerSpawnInfo findPlayerSpawn(List <TiledObjectGroup> objectLayers, string prevMap)
        {
            PlayerSpawnInfo psi = new PlayerSpawnInfo(0, 0, 0);

            foreach (TiledObjectGroup tog in objectLayers)
            {
                if (tog.name == "PlayerSpawn")
                {
                    TiledObjectGroup playerSpawnLayer = tog;
                    foreach (TiledObject to in playerSpawnLayer.objects)
                    {
                        if (to.name.Contains(prevMap))
                        {
                            string direction;
                            to.properties.TryGetValue("Direction", out direction);
                            psi.x         = to.x;
                            psi.y         = to.y;
                            psi.direction = int.Parse(direction);
                        }
                        break;
                    }
                }
            }
            return(psi);
        }
Example #6
0
        /// <summary>
        /// Will randomly add enemies
        /// </summary>
        public override void update()
        {
            base.update();
            if (this.scene != null)
            {
                //if chance is true, then start process of creating an enemy
                if (Nez.Random.chance(.05f))
                {
                    Enemy enemy = new Enemy(map, numCollisionLayers, numObjLayers, graphics);

                    TiledObject spawnObj = null;

                    for (int i = 0; i < numCollisionLayers; i++)
                    {
                        int              num       = i + 1;
                        string           layerName = "ObjLayer" + num.ToString();
                        TiledObjectGroup group     = map.getObjectGroup(layerName);
                        //Gets the Obj to spawn at (Not correct right now because it will just end up grabbing a random SpawnGround obj from the LAST obj layer, when it should be a random layer)
                        spawnObj = group.getObjectsOfType("SpawnGround")[Nez.Random.range(0, group.getObjectsOfType("SpawnGround").Count)];
                    }

                    int xSpawn = Nez.Random.range(spawnObj.x, spawnObj.x + spawnObj.width);
                    int ySpawn = (int)(spawnObj.y) - 1;

                    //Finally move the enemy to its psuedo spawn position (entity has to move itself to the correct spawn based off its collider)
                    enemy.transform.setPosition(new Vector2(xSpawn, ySpawn));

                    this.scene.addEntity(enemy);
                }
            }
        }
Example #7
0
 private void SetupPlayerSpawns(TiledObjectGroup mapObjects)
 {
     _playerSpawner = new PlayerSpawner();
     foreach (var spawnObject in mapObjects.objectsWithName(TiledObjects.PlayerSpawn))
     {
         _playerSpawner.AddLocation("player_spawner" + spawnObject.id, spawnObject.x + spawnObject.height / 2, spawnObject.y + spawnObject.height / 2);
     }
 }
Example #8
0
        public static void ReadRectangleObject(TiledObjectGroup layer, XElement root)
        {
            var obj = new TiledRectangleObject();

            // Read generic object information.
            ReadGenericObjectInformation(obj, root);

            layer.Objects.Add(obj);
        }
Example #9
0
 private void SetupCollisions(TiledObjectGroup objectGroup)
 {
     foreach (var collisionObject in objectGroup.objectsWithName(TiledObjects.Collision))
     {
         var collidable = scene.createEntity("collidable" + collisionObject.id, new Vector2((collisionObject.x + collisionObject.width / 2), collisionObject.y + collisionObject.height / 2));
         collidable.tag = Tags.Obstacle;
         var hitbox = collidable.addComponent(new BoxCollider(collisionObject.width, collisionObject.height));
         Flags.setFlagExclusive(ref hitbox.physicsLayer, Layers.MapObstacles);
     }
 }
Example #10
0
 private void SetupPits(TiledObjectGroup objectGroup)
 {
     foreach (var pit in objectGroup.objectsWithName(TiledObjects.Pit))
     {
         var pitEntity = scene.createEntity("pit" + pit.id, new Vector2((pit.x + pit.width / 2), pit.y + pit.height / 2));
         pitEntity.setTag(Tags.Pit);
         var hitbox = pitEntity.addComponent(new BoxCollider(pit.width, pit.height));
         hitbox.isTrigger = true;
         Flags.setFlagExclusive(ref hitbox.physicsLayer, Layers.MapObstacles);
     }
 }
Example #11
0
        private void setupPlayer(TiledObjectGroup objectLayer)
        {
            var spawn = objectLayer.objectWithName("spawn");

            player       = createEntity("player");
            playerObject = player.addComponent(new Player(Game1.gameRef));
            player.transform.setPosition(spawn.x, spawn.y);
            camera.addComponent(new FollowCamera(player));
            endGameZone = objectLayer.objectWithName("endGame");
            playerObject.EndGameZone = endGameZone.x;
        }
Example #12
0
        public static void ReadTileObject(TiledObjectGroup layer, XElement root)
        {
            var obj = new TiledTileObject();

            // Read generic object information.
            ReadGenericObjectInformation(obj, root);

            // Read tile specific stuff.
            obj.Tile = root.ReadAttribute("gid", 0);

            layer.Objects.Add(obj);
        }
Example #13
0
        void renderObjectGroup(TiledObjectGroup group, Graphics graphics)
        {
            var renderPosition = entity.transform.position + _localOffset;

            foreach (var obj in group.objects)
            {
                if (!obj.visible)
                {
                    continue;
                }

                switch (obj.tiledObjectType)
                {
                case TiledObject.TiledObjectType.Ellipse:
                    graphics.batcher.drawCircle(
                        new Vector2(
                            renderPosition.X + obj.x + obj.width * 0.5f,
                            renderPosition.Y + obj.y + obj.height * 0.5f),
                        obj.width * 0.5f,
                        group.color);
                    break;

                case TiledObject.TiledObjectType.Image:
                    throw new NotImplementedException("Image layers are not yet supported");

                case TiledObject.TiledObjectType.Polygon:
                    graphics.batcher.drawPoints(renderPosition, obj.polyPoints, group.color, true);
                    break;

                case TiledObject.TiledObjectType.Polyline:
                    graphics.batcher.drawPoints(renderPosition, obj.polyPoints, group.color, false);
                    break;

                case TiledObject.TiledObjectType.None:
                    graphics.batcher.drawHollowRect(
                        renderPosition.X + obj.x,
                        renderPosition.Y + obj.y,
                        obj.width,
                        obj.height,
                        group.color);
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }
            }
        }
Example #14
0
        private void SetupItemSpawners(TiledObjectGroup objectGroup)
        {
            foreach (var spawnObject in objectGroup.objectsWithName(TiledObjects.ItemSpawn))
            {
                var spawner = scene.addEntity(new Spawner(spawnObject.x + spawnObject.height / 2, spawnObject.y + spawnObject.height / 2));

                // Example event listener for spawning weapons usage
                //var props = spawnObject.properties;
                //if (props.ContainsKey("key") && !string.IsNullOrWhiteSpace(props["key"]))
                //{
                //    var listener = spawner.addComponent(new MapEventListener(props["key"])
                //    {
                //        EventTriggered = _ => spawner.SpawnItem()
                //    });
                //    MapEventListeners.Add(listener);
                //}
                // Example event listener usage
            }
        }
 public static Entity attachTransitionColliders(List <TiledObjectGroup> objectLayers, Entity tiledEntity, string location)
 {
     foreach (TiledObjectGroup tog in objectLayers)
     {
         if (tog.name == "Transitions")
         {
             TiledObjectGroup transitionLayer = tog;
             foreach (TiledObject transition in transitionLayer.objects)
             {
                 string destination;
                 transition.properties.TryGetValue("transitionTo", out destination);
                 TransitionCollider tc = new TransitionCollider(transition.x, transition.y, tileWidth, destination, location);
                 tc.isTrigger = true;
                 tiledEntity.addCollider(tc);
             }
         }
         break;
     }
     return(tiledEntity);
 }
Example #16
0
 public PlayerController(TiledMap arg)
 {
     til         = arg;
     objectLayer = til.getObjectGroup("Eventos");
     foreach (TiledObject hielo in objectLayer.objectsWithName("Hielo"))
     {
         boxCollider.Add(new RectangleF(hielo.x, hielo.y, hielo.width, hielo.height));
     }
     foreach (TiledObject t in objectLayer.objectsWithName("Pinchos"))
     {
         pinchos.Add(new RectangleF(t.x, t.y, t.width, t.height));
     }
     foreach (TiledObject t in objectLayer.objectsWithName("Gravedad"))
     {
         palancas.Add(new RectangleF(t.x, t.y, t.width, t.height));
     }
     foreach (TiledObject t in objectLayer.objectsWithName("Puerta"))
     {
         puertas.Add(new RectangleF(t.x, t.y, t.width, t.height));
         ubicaciones.Add(t.properties["puntoDeTransporte"]);
     }
 }
Example #17
0
        /// <summary>
        ///
        /// </summary>
        public EnemySpawner(TiledMap map, int numCollisionLayers, int numObjLayers, GraphicsDevice graphics)
        {
            this.map = map;
            this.numCollisionLayers = numCollisionLayers;
            this.numObjLayers       = numObjLayers;
            this.graphics           = graphics;

            //Get all the objects
            for (int i = 0; i < numCollisionLayers; i++)
            {
                int              num       = i + 1;
                string           layerName = "ObjLayer" + num.ToString();
                TiledObjectGroup group     = map.getObjectGroup(layerName);
                if (group.getObjectsOfType("SpawnGround") != null)
                {
                    foreach (TiledObject obj in group.getObjectsOfType("SpawnGround"))
                    {
                        objs.Add(obj);
                    }
                }
            }
        }
Example #18
0
        public override void initialize()
        {
            base.initialize();
            this.addRenderer(new DefaultRenderer());
            SetupPostProcess();

            //var deferredRenderer = addRenderer(new DeferredLightingRenderer(
            //    0, 1, 10, 20));
            //deferredRenderer.setAmbientColor(new Color(10, 10, 10));

            _enemiesContainer = addEntity(new ContainerEntity
            {
                name = "container-enemies"
            });
            EnemyEntity.Container = _enemiesContainer;
            _bulletContainer      = addEntity(new ContainerEntity
            {
                name = "container-bullet"
            });
            BulletEntity.Container = _bulletContainer;
            _itemsContainer        = addEntity(new ContainerEntity()
            {
                name = "container-items"
            });

            _currentMap     = content.Load <TiledMap>(Content.Tilemaps.map1);
            _mapBoundsGroup = _currentMap.getObjectGroup("MapBounds");
            var startPos = _currentMap.getObjectGroup("Points").objectWithName("StartPos");

            _mapEnemies = _currentMap.getObjectGroup("Enemies");
            _mapItems   = _currentMap.getObjectGroup("Upgrades");
            Texture2D freePlayerTexture = content.Load <Texture2D>(Content.Textures.tempFlightSprite);

            Entity            map      = createEntity("map");
            TiledMapComponent tiledMap = map.addComponent(new TiledMapComponent(_currentMap, "Level"));

            // Vector2 halfMapDimensions = new Vector2(tiledMap.width, tiledMap.height) / 2.0f;
            // map.setPosition(-halfMapDimensions);
            tiledMap.setRenderLayer(10);
            var flyingPlayer = new FreemovePlayerEntity(freePlayerTexture)
            {
                name = "player-flying"
            };

            flyingPlayer.addComponent <PositionBoundsLimitComponent>();
            this.addEntity(flyingPlayer);
            EnemyEntity.Player = flyingPlayer;

            var platformPlayer = new PlatformPlayerEntity(freePlayerTexture)
            {
                name = "player-platform"
            };

            platformPlayer.transform.position = new Vector2(startPos.x, startPos.y);
            this.addEntity(platformPlayer);

            CameraFollowComponent cameraFollow = new CameraFollowComponent(platformPlayer.transform);

            camera.addComponent(cameraFollow);

            PlayerManagerComponent p = addSceneComponent <PlayerManagerComponent>();

            p.PlatformPlayer       = platformPlayer.getComponent <PlatformPlayerComponent>();
            p.FreemovePlayer       = flyingPlayer.getComponent <FreemovePlayerComponent>();
            p.CameraFollow         = cameraFollow;
            p.OnTogglePlatforming += OnPlatformToggle;
            p.TogglePlatforming();
            //var scanLines = content.loadEffect(@"nez\effects\Invert.mgfxo");

            _bulletTextures     = new Texture2D[1];
            _enemyTextures      = new Texture2D[1];
            _upgradeTextures    = new Texture2D[1];
            _bulletTextures[0]  = content.Load <Texture2D>(Content.Textures.Enemies.bullet);
            _enemyTextures[0]   = content.Load <Texture2D>(Content.Textures.Enemies.enemy1);
            _upgradeTextures[0] = content.Load <Texture2D>(Content.Textures.tempFlightSprite);
            //// EnemyEntity e = new EnemyEntity(enemyTexture, bullet);
            //e.getComponent<EnemyComponent>().Player = flyingPlayer;
            //addEntity(e);

            addEntityProcessor(new UpgradeTriggerProcessor(new Matcher().all(typeof(UpgradeComponent))));

            CreateUi();
            Time.timeScale = 0.0f;
            Core.startCoroutine(WaitToStart(0.5f));

            ChangeCameraPos();
        }
Example #19
0
 public NodeCollection(TiledObjectGroup tiledGroup)
 {
     Name             = tiledGroup.name;
     TiledObjectGroup = tiledGroup;
 }
Example #20
0
        public void Load(string file, GraphicsDevice graphicsDevice)
        {
            int width    = -1;
            int height   = -1;
            int tilesize = -1;
            List <TiledObjectGroup> objectGroups = new List <TiledObjectGroup>();
            List <MapLayer>         layers       = new List <MapLayer>();
            TileSetManager          ts           = new TileSetManager();

            hope = new LightRenderer(graphicsDevice, this);

            using (XmlReader xr = XmlReader.Create(file))
            {
                while (xr.Read())
                {
                    if (xr.NodeType == XmlNodeType.EndElement)
                    {
                        continue;
                    }
                    switch (xr.Name)
                    {
                    case "tileset":
                        using (StringReader sr = new StringReader(xr.ReadOuterXml()))
                            using (XmlReader r = XmlReader.Create(sr))
                                ts.LoadTileSet(file, r, graphicsDevice);
                        break;

                    case "layer":
                        MapLayer layer = null;
                        string   name  = xr["name"];
                        using (StringReader sr = new StringReader(xr.ReadOuterXml()))
                            using (XmlReader r = XmlReader.Create(sr))
                                layer = MapLayer.Load(r, graphicsDevice, ts, System.IO.Path.GetDirectoryName(file));
                        if (!name.StartsWith("Light"))
                        {
                            layers.Add(layer);
                        }
                        else
                        {
                            hope.AddLayer(layer);
                        }
                        break;

                    case "map":
                        width    = int.Parse(xr["width"]);
                        height   = int.Parse(xr["height"]);
                        tilesize = int.Parse(xr["tilewidth"]);                                 //should be same as tileheight
                        break;

                    case "objectgroup":
                        TiledObjectGroup og = new TiledObjectGroup(xr["name"]);
                        og.Load(xr);
                        objectGroups.Add(og);
                        break;

                    default:
                        break;
                    }
                }
            }
            BasicTile.SetTileSize(tilesize);

            this.width        = width;
            this.height       = height;
            this.ObjectGroups = objectGroups.ToArray();
            this.Layers       = layers.ToArray();
            hope.LoadTileSets(ts);

            nodes = new Node[width, height];

            for (int x = 0; x < width; x++)
            {
                for (int y = 0; y < height; y++)
                {
                    nodes[x, y] = new Node(new Index2(x, y));
                }
            }
            for (int x = 0; x < width; x++)
            {
                for (int y = 0; y < height; y++)
                {
                    nodes[x, y].SetNeighbours(GetNeighbours(x, y));
                }
            }

            var lightbulbs = GetGroupByName("Lights");

            foreach (var lightbulb in lightbulbs.Objects)
            {
                hope.AddLight(new Light((Index2)lightbulb.Position, (short)lightbulb.Properties.GetPropertyAsInt("Strength"), 1f, lightbulb.Properties.GetPropertyAsColor("Color")));
            }
        }
Example #21
0
        //protected void GetParameters(int x, int y, int z, out Index3 index, out bool interactive, out bool animation, out TiledProperties properties)
        //{
        //	index = new Index3(x, y, z);
        //	interactive = Layers[z].IsInteractive(x,y);
        //	animation = Layers[z].IsAnimation(x,y);
        //	properties = Layers[z].GetProperties(x, y);
        //}

        //public bool IsAnimated(Vector2 pixel, int z = -1)
        //{
        //	bool result = false;
        //	Index2 index = (Index2) (pixel / 32);
        //	if (z == -1)
        //	{
        //		for (int _z = 0; _z < Layers.Length; _z++)
        //		{
        //			GetParameters(index.X, index.Y, _z, out Index3 _index, out bool i, out result, out TiledProperties p);
        //		}
        //		return result;
        //	}
        //	GetParameters(index.X, index.Y, z, out Index3 __index, out bool _i, out result, out TiledProperties _p);
        //	return result;
        //}

        protected Node[] GetNeighbours(int x, int y)
        {
            Node[,] buf = new Node[3, 3];

            for (int xOff = -1; xOff <= 1; xOff++)
            {
                for (int yOff = -1; yOff <= 1; yOff++)
                {
                    if (x + xOff < 0 ||
                        y + yOff < 0 ||
                        x + xOff >= width ||
                        y + yOff >= height ||
                        (xOff == 0 && yOff == 0))
                    {
                        buf[1 + xOff, 1 + yOff] = null;
                    }
                    else
                    {
                        buf[1 + xOff, 1 + yOff] = nodes[x + xOff, y + yOff];
                    }
                }
            }

            TiledObjectGroup group = GetGroupByName("Pathfinding");

            int rx = x * BasicTile.Size;
            int ry = y * BasicTile.Size;

            foreach (var obj in group.Objects.Where(o => o.Type == "Room"))
            {
                if (obj.Rectangle.Right == rx || obj.Rectangle.X == rx)
                {
                    if (obj.Rectangle.Y <= ry && obj.Rectangle.Bottom >= ry + BasicTile.Size)                     //Complete Left Side
                    {
                        for (int j = 0; j < 3; j++)
                        {
                            buf[0, j] = null;
                        }
                    }
                    else if (obj.Rectangle.Y <= ry - BasicTile.Size && obj.Rectangle.Bottom >= ry)                     //Left Top
                    {
                        buf[0, 0] = null;
                    }
                    else if (obj.Rectangle.Y <= ry + BasicTile.Size && obj.Rectangle.Bottom >= ry + 2 * BasicTile.Size)                     //Left Bottom
                    {
                        buf[0, 2] = null;
                    }
                }
                if (obj.Rectangle.Right == rx + BasicTile.Size || obj.Rectangle.X == rx + BasicTile.Size)
                {
                    if (obj.Rectangle.Y <= ry && obj.Rectangle.Bottom >= ry + BasicTile.Size)                     //Complete Right Side
                    {
                        for (int j = 0; j < 3; j++)
                        {
                            buf[2, j] = null;
                        }
                    }
                    else if (obj.Rectangle.Y <= ry - BasicTile.Size && obj.Rectangle.Bottom >= ry)                     //Right Top
                    {
                        buf[2, 0] = null;
                    }
                    else if (obj.Rectangle.Y <= ry + BasicTile.Size && obj.Rectangle.Bottom >= ry + 2 * BasicTile.Size)                     //Right Bottom
                    {
                        buf[2, 2] = null;
                    }
                }
                if (obj.Rectangle.Bottom == ry + BasicTile.Size || obj.Rectangle.Y == ry + BasicTile.Size)
                {
                    if (obj.Rectangle.X <= rx && obj.Rectangle.Right >= rx + BasicTile.Size)                     //Complete Bottom Side
                    {
                        for (int j = 0; j < 3; j++)
                        {
                            buf[j, 2] = null;
                        }
                    }
                    else if (obj.Rectangle.X <= rx - BasicTile.Size && obj.Rectangle.Right >= rx)                     //Bottom Left
                    {
                        buf[0, 2] = null;
                    }
                    else if (obj.Rectangle.X <= rx + BasicTile.Size && obj.Rectangle.Right >= rx + 2 * BasicTile.Size)                     //Bottom Right
                    {
                        buf[2, 2] = null;
                    }
                }
                if (obj.Rectangle.Bottom == ry || obj.Rectangle.Y == ry)
                {
                    if (obj.Rectangle.X <= rx && obj.Rectangle.Right >= rx + BasicTile.Size)                     //Complete Top Side
                    {
                        for (int j = 0; j < 3; j++)
                        {
                            buf[j, 0] = null;
                        }
                    }
                    else if (obj.Rectangle.X <= rx - BasicTile.Size && obj.Rectangle.Right >= rx)                     //Top Left
                    {
                        buf[0, 0] = null;
                    }
                    else if (obj.Rectangle.X <= rx + BasicTile.Size && obj.Rectangle.Right >= rx + 2 * BasicTile.Size)                     //Top Right
                    {
                        buf[2, 0] = null;
                    }
                }
            }

            if (true)            //???
            {
                foreach (var door in GetGroupByName("Pathfinding").Objects.Where(o => o.Type == "Door"))
                {
                    int xd1 = (int)(door.Position.X / BasicTile.Size);
                    int yd1 = (int)(door.Position.Y / BasicTile.Size);
                    int xd2 = -1;
                    int yd2 = -1;
                    //Should be 64 > 32
                    if (door.Size.X > door.Size.Y)
                    {
                        xd2 = xd1 + 1;
                        yd2 = yd1;
                    }
                    //Should be 64 > 32
                    else if (door.Size.Y > door.Size.X)
                    {
                        xd2 = xd1;
                        yd2 = yd1 + 1;
                    }
                    else
                    {
                        throw new FormatException("Error on Map. Door objects in the Pathfinding Layer must contain two tiles!");
                    }
                    if (x == xd1 && y == yd1)
                    {
                        buf[xd2 - x, yd2 - y] = nodes[xd2, yd2];
                    }
                    else if (x == xd2 && y == yd2)
                    {
                        buf[1 + xd1 - x, 1 + yd1 - y] = nodes[xd1, yd1];
                    }
                }
            }


            List <Node> result = new List <Node>();

            for (int i = 0; i < 3; i++)
            {
                for (int j = 0; j < 3; j++)
                {
                    if (buf[i, j] != null)
                    {
                        result.Add(buf[i, j]);
                    }
                }
            }
            return(result.ToArray());
        }
Example #22
0
    /// <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();
    }
 public EnemySpawnController(TiledMap tiledMap)
 {
     this._tiledMap    = tiledMap;
     this._objectLayer = tiledMap.getObjectGroup("objects");
 }
Example #24
0
        private void AddToNodeCollectionEntity(TiledObjectGroup tiledGroup)
        {
            var nodeEntity = findEntity("node-collections") ?? createEntity("node-collections");

            nodeEntity.addComponent(new NodeCollection(tiledGroup));
        }
Example #25
0
        public static void Load(string leveldir, string filename)
        {
            string fullname = Main.startdir + "\\Levels\\" + leveldir + "\\" + filename;

            if (File.Exists(fullname))
            {
                //Load the map using NTiled
                XDocument document = XDocument.Load(fullname);
                TiledMap  map      = new TiledReader().Read(document);

                //Tilesets
                foreach (TiledTileset tileset in map.Tilesets)
                {
                    if (tileset.Image != null && File.Exists(Main.startdir + "\\Levels\\" + leveldir + "\\" + tileset.Image.Source))
                    {
                        Program.game.Content.RootDirectory = "Levels";
                        Tileset ts = new Tileset(Program.game.Content.Load <Texture2D>(leveldir + "\\" + new FileInfo(tileset.Image.Source).Name));

                        //Generate all the tile rectangles within the tileset.
                        int i = 0;
                        for (int y = 0; y < tileset.Image.Height; y += 16)
                        {
                            for (int x = 0; x < tileset.Image.Width; x += 16)
                            {
                                ts.tilesetparts.Add(new Rectangle(x, y, 16, 16));
                                AssignProperties(tileset, i, ts);
                                i++;
                            }
                        }

                        tilesets.Add(ts);
                    }
                }

                //Layers
                foreach (TiledLayer layer in map.Layers)
                {
                    TiledTileLayer   tlayer = layer as TiledTileLayer;
                    TiledObjectGroup olayer = layer as TiledObjectGroup;

                    if (tlayer != null)
                    {
                        int i = 0, tilesetid = 0;
                        for (int y = 0; y < layer.Height * 16; y += 16)
                        {
                            for (int x = 0; x < layer.Width * 16; x += 16)
                            {
                                if (tlayer.Tiles[i] != 0)
                                {
                                    //TODO: Find the correct tileset for each tile.
                                    //OLD CODE:

                                    //if (!tilesets[tilesetid].tilesetparts.Count > !tilesets[tilesetid].tileids.Contains(tlayer.Tiles[i]))
                                    //{
                                    //    Console.WriteLine(tlayer.Tiles[i]);
                                    //    //tilesetid = -1;
                                    //    for (int tsi = 0; tsi < tilesets.Count; tsi++)
                                    //    {
                                    //        if (tilesets[tsi].tileids.Contains(tlayer.Tiles[i])) { tilesetid = tsi; break; }
                                    //    }
                                    //}
                                    //else { Console.WriteLine(tlayer.Tiles[i]); }

                                    //Spawn all the tiles
                                    if (tilesetid != -1)
                                    {
                                        tiles.Add(new Tile(tilesetid, tlayer.Tiles[i] - 1, tilesets[tilesetid].tilesetparts[tlayer.Tiles[i] - 1], new Vector2(x, y)));
                                    }
                                }
                                i++;
                            }
                        }
                    }

                    if (olayer != null)
                    {
                        foreach (TiledObject obj in olayer.Objects)
                        {
                            switch (obj.Type)
                            {
                            case "Camera H Border Lock": objects.Add(new CameraHBorder(new Rectangle((int)obj.X, (int)obj.Y, (int)obj.Width, (int)obj.Height), obj.Properties.ContainsKey("Stops Player") ? (obj.Properties["Stops Player"] == "1" || obj.Properties["Stops Player"].ToUpper() == "TRUE") : false)); break;

                            case "Camera V Border Lock": objects.Add(new CameraVBorder(new Rectangle((int)obj.X, (int)obj.Y, (int)obj.Width, (int)obj.Height), obj.Properties.ContainsKey("Stops Player") ? (obj.Properties["Stops Player"] == "1" || obj.Properties["Stops Player"].ToUpper() == "TRUE") : false)); break;

                            case "Death Trigger": objects.Add(new DeathTrigger(new Rectangle((int)obj.X, (int)obj.Y, (int)obj.Width, (int)obj.Height))); break;

                            case "Ring": objects.Add(new Ring((float)obj.X, (float)obj.Y)); break;
                            }
                        }
                    }
                }

                //Assign Playerstarts
                if (map.Properties["Sonic Player Start"] != null)
                {
                    playerstarts[0] = new Vector2(Convert.ToSingle(map.Properties["Sonic Player Start"].Split(',')[0]), Convert.ToSingle(map.Properties["Sonic Player Start"].Split(',')[1]));
                }
                if (map.Properties["Tails Player Start"] != null)
                {
                    playerstarts[1] = new Vector2(Convert.ToSingle(map.Properties["Tails Player Start"].Split(',')[0]), Convert.ToSingle(map.Properties["Tails Player Start"].Split(',')[1]));
                }
                if (map.Properties["Knuckles Player Start"] != null)
                {
                    playerstarts[2] = new Vector2(Convert.ToSingle(map.Properties["Knuckles Player Start"].Split(',')[0]), Convert.ToSingle(map.Properties["Knuckles Player Start"].Split(',')[1]));
                }

                //Assign Camerastarts
                if (map.Properties["Sonic Camera Start"] != null)
                {
                    camerastarts[0] = new Vector2(Convert.ToSingle(map.Properties["Sonic Camera Start"].Split(',')[0]), Convert.ToSingle(map.Properties["Sonic Camera Start"].Split(',')[1]));
                }
                if (map.Properties["Tails Camera Start"] != null)
                {
                    camerastarts[1] = new Vector2(Convert.ToSingle(map.Properties["Tails Camera Start"].Split(',')[0]), Convert.ToSingle(map.Properties["Tails Camera Start"].Split(',')[1]));
                }
                if (map.Properties["Knuckles Camera Start"] != null)
                {
                    camerastarts[2] = new Vector2(Convert.ToSingle(map.Properties["Knuckles Camera Start"].Split(',')[0]), Convert.ToSingle(map.Properties["Knuckles Camera Start"].Split(',')[1]));
                }

                //TODO: Fix the camerastart assignments.

                //Move players to their correct start positions
                foreach (Player plr in Main.players)
                {
                    if (plr.GetType() == typeof(Sonic))
                    {
                        plr.pos = playerstarts[0];
                    }
                    else if (plr.GetType() == typeof(Tails))
                    {
                        plr.pos = playerstarts[1];
                    }
                    else if (plr.GetType() == typeof(Knuckles))
                    {
                        plr.pos = playerstarts[2];
                    }

                    if (plr.GetType() == typeof(Sonic))
                    {
                        Camera.pos = camerastarts[0] * Main.scalemodifier;
                    }
                    else if (plr.GetType() == typeof(Tails))
                    {
                        Camera.pos = camerastarts[1] * Main.scalemodifier;
                    }
                    else if (plr.GetType() == typeof(Knuckles))
                    {
                        Camera.pos = camerastarts[2] * Main.scalemodifier;
                    }

                    plr.active = true;
                }

                Program.game.Content.RootDirectory = "Content";
            }
            else
            {
                MessageBox.Show("ERROR: The given level (\"" + filename + "\") does not exist!", "SoniC#", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Example #26
0
        private static void ReadObjectGroup(TiledMap map, XElement root)
        {
            var layer = new TiledObjectGroup();

            // Read generic layer information.
            ReadGenericLayerInformation(layer, root);

            // Read the used to display the objects in this group (if any).
            layer.Color = ColorTranslator.FromHtml(root.ReadAttribute("color", string.Empty));

            // Read all objects.
            foreach (var objectElement in root.GetElements("object"))
            {
                // Is this a tile object?
                if (objectElement.HasAttribute("gid"))
                {
                    ObjectParser.ReadTileObject(layer, objectElement);
                }
                else if (objectElement.HasElement("ellipse"))
                {
                    // TODO: Add support for ellipsis objects.
                }
                else if (objectElement.HasElement("polygon"))
                {
                    // TODO: Add support for polygon objects.
                }
                else if (objectElement.HasElement("polyline"))
                {
                    // TODO: Add support for polyline objects.
                }
                else
                {
                    ObjectParser.ReadRectangleObject(layer, objectElement);
                }
            }

            map.Layers.Add(layer);
        }
Example #27
0
        public string CompileMap(string mapPath)
        {
            MainMap   map;
            BorderMap borderMap;

            try
            {
                string        mapDirectory = Path.GetDirectoryName(mapPath);
                XmlSerializer serializer   = new XmlSerializer(typeof(TiledMap));

                FileStream mapStream = new FileStream(mapPath, FileMode.Open, FileAccess.Read);
                TiledMap   tiledMain = (TiledMap)serializer.Deserialize(mapStream);
                mapStream.Close();
                mapStream.Dispose();
                map = new MainMap(tiledMain, mapDirectory, Context);

                string borderMapPath = Path.Combine(mapDirectory, map.MapLayer.Properties.RetrieveString(Resources.STR_BORDER_MAP_FILE, Context, map.MapLayer));

                /* Load the map representing the border block */


                FileStream borderStream = new FileStream(borderMapPath, FileMode.Open, FileAccess.Read);
                TiledMap   tiledBorder  = (TiledMap)serializer.Deserialize(borderStream);
                borderStream.Close();
                borderStream.Dispose();
                borderMap = new BorderMap(tiledBorder, Context, mapDirectory);
            }
            catch (CompilerErrorException cex)
            {
                throw cex;
            }
            catch (Exception ex)
            {
                Context.ExitError("could not deserialize map file(s): {0}", ex, ex.Message);
                return(null);
            }

            /* Tiled Map is loaded, we need to create libmap2agb maps now */
            MapHeader header = new MapHeader();

            header.ShowName    = (byte)map.MapLayer.Properties.RetrieveFormattedInt(Resources.STR_HEAD_SHOW_NAME, Context, map.MapLayer);
            header.Music       = (ushort)map.MapLayer.Properties.RetrieveFormattedInt(Resources.STR_HEAD_MUSIC, Context, map.MapLayer);
            header.Weather     = (byte)map.MapLayer.Properties.RetrieveFormattedInt(Resources.STR_HEAD_WEATHER, Context, map.MapLayer);
            header.Light       = (byte)map.MapLayer.Properties.RetrieveFormattedInt(Resources.STR_HEAD_LIGHT, Context, map.MapLayer);
            header.BattleStyle = (byte)map.MapLayer.Properties.RetrieveFormattedInt(Resources.STR_HEAD_BATTLETYPE, Context, map.MapLayer);
            header.Cave        = (byte)map.MapLayer.Properties.RetrieveFormattedInt(Resources.STR_HEAD_CAVE, Context, map.MapLayer);
            header.Name        = (byte)map.MapLayer.Properties.RetrieveFormattedInt(Resources.STR_HEAD_NAME, Context, map.MapLayer);
            header.Index       = (ushort)map.MapLayer.Properties.RetrieveFormattedInt(Resources.STR_HEAD_INDEX, Context, map.MapLayer);
            header.Unknown     = (byte)map.MapLayer.Properties.RetrieveFormattedInt(Resources.STR_HEAD_UNKNOWN, Context, map.MapLayer);
            bool escapeRope = map.MapLayer.Properties.RetrieveBoolean(Resources.STR_HEAD_ESCAPEROPE, Context, map.MapLayer);
            bool canDig     = map.MapLayer.Properties.RetrieveBoolean(Resources.STR_HEAD_DIG, Context, map.MapLayer);

            header.EscapeRope = (byte)((escapeRope ? (1 << 1) : 0) | (canDig ? 1 : 0));

            header.Footer = new MapFooter();
            header.Footer.FirstTilesetInternal  = 0x082D49B8;
            header.Footer.SecondTilesetInternal = 0x082D49D0;
            header.Footer.Width  = map.Child.Width;
            header.Footer.Height = map.Child.Height;


            /* Build the border block */
            header.Footer.BorderBlock = Fill2DMap(borderMap.BorderMapTiles, borderMap.Child.Width, borderMap.Child.Height, borderMap.Child);

            header.Footer.BorderHeight = (byte)borderMap.Child.Height;
            header.Footer.BorderWidth  = (byte)borderMap.Child.Width;

            /* Build the map block */
            header.Footer.MapBlock = Fill2DMap(map.MapTiles, map.Child.Width, map.Child.Height, map.Child);
            FillCollisionMap(map.CollisionTiles, map.Child.Width, map.Child.Height, map.Child, header.Footer.MapBlock);

            EventHeader      mapEventHeader = new EventHeader();
            TiledObjectGroup eventGroup     = map.Child.ObjectGroups.GetObjectByMatchingProperties(Resources.STR_OBJLAYER_NAME, Resources.STR_OBJLAYER_EVENT, Context);

            if (eventGroup == null)
            {
                Context.ExitError("could not find entity layer in object layers");
            }
            foreach (TiledObject obj in eventGroup.Objects)
            {
                if (obj.GlobalIdentifier.TileGetTileObject(map.Child.TilesetDefinitions, Context).Type == Resources.STR_EVTTYPE_PERSON)
                {
                    EventEntityPerson person = new EventEntityPerson();
                    person.Id          = (byte)obj.Properties.RetrieveFormattedInt(Resources.STR_EVT_P_NR, Context, obj, false, 0);
                    person.Picture     = (byte)obj.Properties.RetrieveFormattedInt(Resources.STR_EVT_P_IMG, Context, obj, false, 0);
                    person.Field2      = (byte)(obj.Properties.RetrieveBoolean(Resources.STR_EVT_P_RIVAL, Context, obj, false, false) ? 1 : 0);
                    person.Field3      = (byte)obj.Properties.RetrieveFormattedInt(Resources.STR_EVT_P_F3, Context, obj, false, 0);
                    person.X           = (short)(obj.X / 16);
                    person.Y           = (short)(obj.Y / 16);
                    person.Height      = (byte)obj.Properties.RetrieveFormattedInt(Resources.STR_EVT_HEIGHT, Context, obj, false, 0);
                    person.Behaviour   = (byte)obj.Properties.RetrieveFormattedInt(Resources.STR_EVT_P_RUNBEHAV, Context, obj, false, 0);
                    person.Movement    = (byte)obj.Properties.RetrieveFormattedInt(Resources.STR_EVT_P_MOVEMENT, Context, obj, false, 0);
                    person.FieldB      = (byte)obj.Properties.RetrieveFormattedInt(Resources.STR_EVT_P_FB, Context, obj, false, 0);
                    person.IsTrainer   = (byte)(obj.Properties.RetrieveBoolean(Resources.STR_EVT_P_TRAINER, Context, obj, false, false) ? 1 : 0);
                    person.FieldD      = (byte)obj.Properties.RetrieveFormattedInt(Resources.STR_EVT_P_FD, Context, obj, false, 0);
                    person.AlertRadius = (ushort)obj.Properties.RetrieveFormattedInt(Resources.STR_EVT_P_SIGHT, Context, obj, false, 0);
                    person.Script      = obj.Properties.RetrieveString(Resources.STR_EVT_SCRIPT, Context, obj, false, "");
                    person.Flag        = (ushort)obj.Properties.RetrieveFormattedInt(Resources.STR_EVT_P_FLAG, Context, obj, false, 0x200);
                    person.Padding     = 0x0000;

                    mapEventHeader.Persons.Add(person);
                }
            }

            header.Events = mapEventHeader;
            StringBuilder sb = new StringBuilder();

            MapHeaderCompile(Context, header, sb, mapPath);

            Context.ExitCode = CompilerExitCode.EXIT_SUCCESS;

            return(sb.ToString());
        }
Example #28
0
        protected override TiledMap Read(ContentReader reader, TiledMap existingInstance)
        {
            var result = new TiledMap();

            result.FirstGid   = reader.ReadInt32();
            result.Width      = reader.ReadInt32();
            result.Height     = reader.ReadInt32();
            result.TileWidth  = reader.ReadInt32();
            result.TileHeight = reader.ReadInt32();
            if (reader.ReadBoolean())
            {
                result.BackgroundColor = reader.ReadColor();
            }
            result.RenderOrder = (TiledRenderOrder)reader.ReadInt32();
            result.Orientation = (TiledMapOrientation)reader.ReadInt32();
            this.ReadProperties(reader, result.Properties);
            var layerCount = reader.ReadInt32();

            for (var i = 0; i < layerCount; i++)
            {
                var        layerType = reader.ReadInt32();
                TiledLayer layer     = null;
                if (layerType == 1)
                {
                    var newLayer = new TiledImageLayer();
                    newLayer.AssetName = reader.ReadString();
                    layer = newLayer;
                }
                else if (layerType == 2)
                {
                    var newLayer = new TiledTileLayer();
                    newLayer.X      = reader.ReadInt32();
                    newLayer.Y      = reader.ReadInt32();
                    newLayer.Width  = reader.ReadInt32();
                    newLayer.Height = reader.ReadInt32();
                    newLayer.Tiles  = new TiledTile[reader.ReadInt32()];

                    for (var j = 0; j < newLayer.Tiles.Length; j++)
                    {
                        if (reader.ReadBoolean())
                        {
                            newLayer.Tiles[j]    = new TiledTile();
                            newLayer.Tiles[j].Id = reader.ReadInt32();
                            newLayer.Tiles[j].FlippedHorizonally = reader.ReadBoolean();
                            newLayer.Tiles[j].FlippedVertically  = reader.ReadBoolean();
                            newLayer.Tiles[j].FlippedDiagonally  = reader.ReadBoolean();
                        }
                    }

                    newLayer.Color = reader.ReadColor();
                    layer          = newLayer;
                }

                if (layer == null)
                {
                    throw new NotSupportedException();
                }

                result.Layers.Add(layer);
                layer.Offset = reader.ReadVector2();
                this.ReadProperties(reader, layer.Properties);
                layer.Name    = reader.ReadString();
                layer.Visible = reader.ReadBoolean();
                layer.Opacity = reader.ReadSingle();
            }
            var objectGroupsCount = reader.ReadInt32();

            for (var i = 0; i < objectGroupsCount; i++)
            {
                var objectGroup = new TiledObjectGroup();
                result.ObjectGroups.Add(objectGroup);

                objectGroup.Name    = reader.ReadString();
                objectGroup.Color   = reader.ReadColor();
                objectGroup.Opacity = reader.ReadSingle();
                objectGroup.Visible = reader.ReadBoolean();
                this.ReadProperties(reader, objectGroup.Properties);
                var objectsCount = reader.ReadInt32();
                for (var j = 0; j < objectsCount; j++)
                {
                    var obj = new TiledObject();
                    objectGroup.Objects.Add(obj);

                    obj.Id              = reader.ReadInt32();
                    obj.Name            = reader.ReadString();
                    obj.Type            = reader.ReadString();
                    obj.X               = reader.ReadInt32();
                    obj.Y               = reader.ReadInt32();
                    obj.Width           = reader.ReadInt32();
                    obj.Height          = reader.ReadInt32();
                    obj.Rotation        = reader.ReadInt32();
                    obj.Gid             = reader.ReadInt32();
                    obj.Visible         = reader.ReadBoolean();
                    obj.TiledObjectType = (TiledObject.TiledObjectTypes)reader.ReadInt32();
                    obj.ObjectType      = reader.ReadString();
                    var pointsCount = reader.ReadInt32();
                    for (var k = 0; k < pointsCount; k++)
                    {
                        obj.PolyPoints.Add(reader.ReadVector2());
                    }
                    this.ReadProperties(reader, obj.Properties);
                }
            }

            var tileSetCount = reader.ReadInt32();

            for (var i = 0; i < tileSetCount; i++)
            {
                var tileSet = new TiledTileSet();
                result.TileSets.Add(tileSet);
                tileSet.Spacing = reader.ReadInt32();
                tileSet.Margin  = reader.ReadInt32();
                this.ReadProperties(reader, tileSet.Properties);

                var tileCount = reader.ReadInt32();
                for (var j = 0; j < tileCount; j++)
                {
                    var tile = new TiledTileSetTile();
                    tileSet.Tiles.Add(tile);
                    tile.Id = reader.ReadInt32();
                    if (reader.ReadBoolean())
                    {
                        var animationFrameCount = reader.ReadInt32();
                        tile.AnimationFrames = new List <TiledTileSetAnimationFrame>(animationFrameCount);
                        for (var k = 0; k < animationFrameCount; k++)
                        {
                            var animationFrame = new TiledTileSetAnimationFrame();
                            tile.AnimationFrames.Add(animationFrame);

                            animationFrame.TileId   = reader.ReadInt32();
                            animationFrame.Duration = reader.ReadSingle();
                        }
                    }

                    this.ReadProperties(reader, tile.Properties);
                    var x      = reader.ReadInt32();
                    var y      = reader.ReadInt32();
                    var width  = reader.ReadInt32();
                    var height = reader.ReadInt32();
                    tile.SourceRect = new Rectangle(x, y, width, height);
                }

                tileSet.FirstGid     = reader.ReadInt32();
                tileSet.Image        = reader.ReadString();
                tileSet.ImageTexture = reader.ContentManager.Load <Texture2D>(tileSet.Image);
            }

            return(result);
        }