Esempio n. 1
0
	void Start ()
	{
		//Hide map icons with given tag
		MapVisibility.setVisibilityForTag (tagForHiddenObjects, false);
		// Draw a line from this node to all children
		drawLinesToChildren ();
	}
Esempio n. 2
0
        /// <summary>
        /// Updates tilemap, e.g. when the current map has changed.
        /// </summary>
        public void UpdateTilemap()
        {
            string tiledMapFilename = this.CurrentMap.TiledMapFilename.Replace(".tmx", string.Empty);

            this.TileMap = this.contentManager.Load <TiledMap>(tiledMapFilename);

            this.ObjectTileset = this.contentManager.Load <TiledMapTileset>("tilemaps/objects");

            this.mapVisibility = new MapVisibility(this.GetTileInfo, 5);
        }
Esempio n. 3
0
    public void TurnsOnMapVisibilityForGivenTag()
    {
        MapObject obj1 = SetUpMapObject("dontToggle", false);
        MapObject obj2 = SetUpMapObject("dontToggle", false);
        MapObject obj3 = SetUpMapObject("doToggle", false);
        MapObject obj4 = SetUpMapObject("doToggle", false);

        MapVisibility.setVisibilityForTag("doToggle", true);

        Assert.False(obj1.isVisible());
        Assert.False(obj2.isVisible());
        Assert.True(obj3.isVisible());
        Assert.True(obj4.isVisible());
    }
Esempio n. 4
0
		void SetupMapTab(MapClassification tab, MapVisibility filter, string tabButtonName, string tabContainerName, ScrollItemWidget itemTemplate)
		{
			var tabContainer = widget.Get<ContainerWidget>(tabContainerName);
			tabContainer.IsVisible = () => currentTab == tab;
			var tabScrollpanel = tabContainer.Get<ScrollPanelWidget>("MAP_LIST");
			tabScrollpanel.Layout = new GridLayout(tabScrollpanel);
			scrollpanels.Add(tab, tabScrollpanel);

			var tabButton = widget.Get<ButtonWidget>(tabButtonName);
			tabButton.IsHighlighted = () => currentTab == tab;
			tabButton.IsVisible = () => tabMaps[tab].Any();
			tabButton.OnClick = () => SwitchTab(tab, itemTemplate);

			RefreshMaps(tab, filter);
		}
Esempio n. 5
0
	public void completeNode ()
	{
		// Can't complete without unlocking
		if (state == NodeState.UNLOCKED) {
			state = NodeState.COMPLETED;

			// Show all hidden objects
			if (tagForHiddenObjects != null) {
				Debug.Log (tagForHiddenObjects.Length);
				MapVisibility.setVisibilityForTag (tagForHiddenObjects, true);
			}

			// Unlock all child nodes
			for (int i = 0; i < childNodes.Length; i++) {
				childNodes [i].unlockNode ();
			}
		}
	}
Esempio n. 6
0
        public void TestEmptyMap()
        {
            // set up
            var mapVisibility = new MapVisibility(GetTileInfoEmptyMap, viewRadius: 5);

            // run
            var pos = new MapPosition(5, 5);

            mapVisibility.Update(pos);

            // check
            for (int x = 0; x < 11; x++)
            {
                for (int y = 0; y < 11; y++)
                {
                    Assert.IsTrue(mapVisibility.IsVisible(new MapPosition(x, y)));
                }
            }
Esempio n. 7
0
        // The standard constructor for most purposes
        public Map(string path)
        {
            Path = path;
            Container = GlobalFileSystem.OpenPackage(path, null, int.MaxValue);

            AssertExists("map.yaml");
            AssertExists("map.bin");

            var yaml = new MiniYaml(null, MiniYaml.FromStream(Container.GetContent("map.yaml"), path));
            FieldLoader.Load(this, yaml);

            // Support for formats 1-3 dropped 2011-02-11.
            // Use release-20110207 to convert older maps to format 4
            // Use release-20110511 to convert older maps to format 5
            // Use release-20141029 to convert older maps to format 6
            if (MapFormat < 6)
                throw new InvalidDataException("Map format {0} is not supported.\n File: {1}".F(MapFormat, path));

            var nd = yaml.ToDictionary();

            // Format 6 -> 7 combined the Selectable and UseAsShellmap flags into the Class enum
            if (MapFormat < 7)
            {
                MiniYaml useAsShellmap;
                if (nd.TryGetValue("UseAsShellmap", out useAsShellmap) && bool.Parse(useAsShellmap.Value))
                    Visibility = MapVisibility.Shellmap;
                else if (Type == "Mission" || Type == "Campaign")
                    Visibility = MapVisibility.MissionSelector;
            }

            SpawnPoints = Exts.Lazy(() =>
            {
                var spawns = new List<CPos>();
                foreach (var kv in ActorDefinitions.Where(d => d.Value.Value == "mpspawn"))
                {
                    var s = new ActorReference(kv.Value.Value, kv.Value.ToDictionary());

                    spawns.Add(s.InitDict.Get<LocationInit>().Value(null));
                }

                return spawns.ToArray();
            });

            RuleDefinitions = MiniYaml.NodesOrEmpty(yaml, "Rules");
            SequenceDefinitions = MiniYaml.NodesOrEmpty(yaml, "Sequences");
            VoxelSequenceDefinitions = MiniYaml.NodesOrEmpty(yaml, "VoxelSequences");
            WeaponDefinitions = MiniYaml.NodesOrEmpty(yaml, "Weapons");
            VoiceDefinitions = MiniYaml.NodesOrEmpty(yaml, "Voices");
            NotificationDefinitions = MiniYaml.NodesOrEmpty(yaml, "Notifications");
            TranslationDefinitions = MiniYaml.NodesOrEmpty(yaml, "Translations");
            PlayerDefinitions = MiniYaml.NodesOrEmpty(yaml, "Players");

            ActorDefinitions = MiniYaml.NodesOrEmpty(yaml, "Actors");
            SmudgeDefinitions = MiniYaml.NodesOrEmpty(yaml, "Smudges");

            MapTiles = Exts.Lazy(LoadMapTiles);
            MapResources = Exts.Lazy(LoadResourceTiles);
            MapHeight = Exts.Lazy(LoadMapHeight);

            TileShape = Game.ModData.Manifest.TileShape;
            SubCellOffsets = Game.ModData.Manifest.SubCellOffsets;
            LastSubCell = (SubCell)(SubCellOffsets.Length - 1);
            DefaultSubCell = (SubCell)Game.ModData.Manifest.SubCellDefaultIndex;

            if (Container.Exists("map.png"))
                using (var dataStream = Container.GetContent("map.png"))
                    CustomPreview = new Bitmap(dataStream);

            PostInit();

            // The Uid is calculated from the data on-disk, so
            // format changes must be flushed to disk.
            // TODO: this isn't very nice
            if (MapFormat < 7)
                Save(path);

            Uid = ComputeHash();
        }
Esempio n. 8
0
        void Run(Action <string> emitError, Action <string> emitWarning, MapPlayers players, MapVisibility visibility, ActorInfo worldActorInfo, CPos[] spawnPoints)
        {
            if (players.Players.Count > 64)
            {
                emitError("Defining more than 64 players is not allowed.");
            }

            var worldOwnerFound = false;
            var playerNames     = players.Players.Values.Select(p => p.Name).ToHashSet();

            foreach (var player in players.Players.Values)
            {
                foreach (var ally in player.Allies)
                {
                    if (!playerNames.Contains(ally))
                    {
                        emitError("Allies contains player {0} that is not in list.".F(ally));
                    }
                }

                foreach (var enemy in player.Enemies)
                {
                    if (!playerNames.Contains(enemy))
                    {
                        emitError("Enemies contains player {0} that is not in list.".F(enemy));
                    }
                }

                if (player.OwnsWorld)
                {
                    worldOwnerFound = true;
                    if (player.Enemies.Any() || player.Allies.Any())
                    {
                        emitWarning("The player {0} owning the world should not have any allies or enemies.".F(player.Name));
                    }

                    if (player.Playable)
                    {
                        emitError("The player {0} owning the world can't be playable.".F(player.Name));
                    }
                }
                else if (visibility == MapVisibility.MissionSelector && player.Playable && !player.LockFaction)
                {
                    // Missions must lock the faction of the player to force the server to override the default Random faction
                    emitError("The player {0} must specify LockFaction: True.".F(player.Name));
                }
            }

            if (!worldOwnerFound)
            {
                emitError("Found no player owning the world.");
            }

            var factions = worldActorInfo.TraitInfos <FactionInfo>().Select(f => f.InternalName).ToHashSet();

            foreach (var player in players.Players.Values)
            {
                if (!string.IsNullOrWhiteSpace(player.Faction) && !factions.Contains(player.Faction))
                {
                    emitError("Invalid faction {0} chosen for player {1}.".F(player.Faction, player.Name));
                }
            }

            if (worldActorInfo.HasTraitInfo <MapStartingLocationsInfo>())
            {
                var playerCount = players.Players.Count(p => p.Value.Playable);
                if (playerCount > spawnPoints.Length)
                {
                    emitError("The map allows {0} possible players, but defines only {1} spawn points".F(playerCount, spawnPoints.Length));
                }

                if (spawnPoints.Distinct().Count() != spawnPoints.Length)
                {
                    emitError("Duplicate spawn point locations detected.");
                }
            }
        }
Esempio n. 9
0
        internal MapChooserLogic(Widget widget, string initialMap, Action onExit, Action <string> onSelect, MapVisibility filter)
        {
            selectedUid = WidgetUtils.ChooseInitialMap(initialMap);

            var approving = new Action(() => { Ui.CloseWindow(); onSelect(selectedUid); });
            var canceling = new Action(() => { Ui.CloseWindow(); onExit(); });

            widget.Get <ButtonWidget>("BUTTON_OK").OnClick     = approving;
            widget.Get <ButtonWidget>("BUTTON_CANCEL").OnClick = canceling;

            scrollpanel        = widget.Get <ScrollPanelWidget>("MAP_LIST");
            scrollpanel.Layout = new GridLayout(scrollpanel);

            itemTemplate = scrollpanel.Get <ScrollItemWidget>("MAP_TEMPLATE");

            var gameModeDropdown = widget.GetOrNull <DropDownButtonWidget>("GAMEMODE_FILTER");

            if (gameModeDropdown != null)
            {
                var selectableMaps = Game.ModData.MapCache.Where(m => m.Status == MapStatus.Available && (m.Map.Visibility & filter) != 0);
                var gameModes      = selectableMaps
                                     .GroupBy(m => m.Type)
                                     .Select(g => Pair.New(g.Key, g.Count())).ToList();

                // 'all game types' extra item
                gameModes.Insert(0, Pair.New(null as string, selectableMaps.Count()));

                Func <Pair <string, int>, string> showItem =
                    x => "{0} ({1})".F(x.First ?? "All Game Types", x.Second);

                Func <Pair <string, int>, ScrollItemWidget, ScrollItemWidget> setupItem = (ii, template) =>
                {
                    var item = ScrollItemWidget.Setup(template,
                                                      () => gameMode == ii.First,
                                                      () => { gameMode = ii.First; EnumerateMaps(onSelect, filter); });
                    item.Get <LabelWidget>("LABEL").GetText = () => showItem(ii);
                    return(item);
                };

                gameModeDropdown.OnClick = () =>
                                           gameModeDropdown.ShowDropDown("LABEL_DROPDOWN_TEMPLATE", 210, gameModes, setupItem);

                gameModeDropdown.GetText = () => showItem(gameModes.First(m => m.First == gameMode));
            }

            var mapfilterInput = widget.GetOrNull <TextFieldWidget>("MAPFILTER_INPUT");

            if (mapfilterInput != null)
            {
                mapfilterInput.TakeKeyboardFocus();
                mapfilterInput.OnEscKey = () =>
                {
                    if (mapfilterInput.Text.Length == 0)
                    {
                        canceling();
                    }
                    else
                    {
                        mapFilter = mapfilterInput.Text = null;
                        EnumerateMaps(onSelect, filter);
                    }

                    return(true);
                };
                mapfilterInput.OnEnterKey   = () => { approving(); return(true); };
                mapfilterInput.OnTextEdited = () =>
                { mapFilter = mapfilterInput.Text; EnumerateMaps(onSelect, filter); };
            }

            var randomMapButton = widget.GetOrNull <ButtonWidget>("RANDOMMAP_BUTTON");

            if (randomMapButton != null)
            {
                randomMapButton.OnClick = () =>
                {
                    var uid = visibleMaps.Random(Game.CosmeticRandom);
                    selectedUid = uid;
                    scrollpanel.ScrollToItem(uid, smooth: true);
                };
                randomMapButton.IsDisabled = () => visibleMaps == null || visibleMaps.Length == 0;
            }

            EnumerateMaps(onSelect, filter);
        }
Esempio n. 10
0
 void RefreshMaps(MapClassification tab, MapVisibility filter)
 {
     tabMaps[tab] = modData.MapCache.Where(m => m.Status == MapStatus.Available &&
                                           m.Class == tab && (m.Visibility & filter) != 0).ToArray();
 }
Esempio n. 11
0
 void RefreshMaps(MapClassification tab, MapVisibility filter)
 {
     tabMaps[tab] = Game.ModData.MapCache.Where(m => m.Status == MapStatus.Available &&
         m.Class == tab && (m.Map.Visibility & filter) != 0).ToArray();
 }
Esempio n. 12
0
 public static MapVisibility ConvertMapVisibility(int i)
 {
     return(MapVisibility.GetMapVisibility(i));
 }
Esempio n. 13
0
        internal MapChooserLogic(Widget widget, ModData modData, string initialMap,
                                 MapClassification initialTab, Action onExit, Action <string> onSelect, MapVisibility filter)
        {
            this.widget   = widget;
            this.modData  = modData;
            this.onSelect = onSelect;

            var approving = new Action(() => { UI.CloseWindow(); onSelect(selectedUid); });
            var canceling = new Action(() => { UI.CloseWindow(); onExit(); });

            var okButton = widget.Get <ButtonWidget>("BUTTON_OK");

            okButton.Disabled = this.onSelect == null;
            okButton.OnClick  = approving;
            widget.Get <ButtonWidget>("BUTTON_CANCEL").OnClick = canceling;

            var itemTemplate = widget.Get <ScrollItemWidget>("MAP_TEMPLATE");

            widget.RemoveChild(itemTemplate);

            var randomMapButton = widget.GetOrNull <ButtonWidget>("RANDOMMAP_BUTTON");

            if (randomMapButton != null)
            {
                randomMapButton.OnClick = () =>
                {
                    var uid = visibleMaps.Random(WarGame.CosmeticRandom);
                    selectedUid = uid;
                };

                randomMapButton.IsDisabled = () => visibleMaps == null || visibleMaps.Length == 0;
            }


            SetupMapTab(MapClassification.User, filter, "USER_MAPS_TAB_BUTTON", "USER_MAPS_TAB", itemTemplate);
            SetupMapTab(MapClassification.System, filter, "SYSTEM_MAPS_TAB_BUTTON", "SYSTEM_MAPS_TAB", itemTemplate);

            if (initialMap == null && tabMaps.Keys.Contains(initialTab) && tabMaps[initialTab].Any())
            {
                selectedUid = WarGame.ModData.MapCache.ChooseInitialMap(tabMaps[initialTab].Select(mp => mp.Uid).First(),
                                                                        WarGame.CosmeticRandom);
                currentTab = initialTab;
            }
            else
            {
                selectedUid = WarGame.ModData.MapCache.ChooseInitialMap(initialMap, WarGame.CosmeticRandom);
                currentTab  = tabMaps.Keys.FirstOrDefault(k => tabMaps[k].Select(mp => mp.Uid).Contains(selectedUid));
            }

            SwitchTab(currentTab, itemTemplate);
        }
Esempio n. 14
0
        // The standard constructor for most purposes
        public Map(string path)
        {
            Path      = path;
            Container = GlobalFileSystem.OpenPackage(path, null, int.MaxValue);

            AssertExists("map.yaml");
            AssertExists("map.bin");

            var yaml = new MiniYaml(null, MiniYaml.FromStream(Container.GetContent("map.yaml"), path));

            FieldLoader.Load(this, yaml);

            // Support for formats 1-3 dropped 2011-02-11.
            // Use release-20110207 to convert older maps to format 4
            // Use release-20110511 to convert older maps to format 5
            // Use release-20141029 to convert older maps to format 6
            if (MapFormat < 6)
            {
                throw new InvalidDataException("Map format {0} is not supported.\n File: {1}".F(MapFormat, path));
            }

            var nd = yaml.ToDictionary();

            // Format 6 -> 7 combined the Selectable and UseAsShellmap flags into the Class enum
            if (MapFormat < 7)
            {
                MiniYaml useAsShellmap;
                if (nd.TryGetValue("UseAsShellmap", out useAsShellmap) && bool.Parse(useAsShellmap.Value))
                {
                    Visibility = MapVisibility.Shellmap;
                }
                else if (Type == "Mission" || Type == "Campaign")
                {
                    Visibility = MapVisibility.MissionSelector;
                }
            }

            // Load players
            foreach (var my in nd["Players"].ToDictionary().Values)
            {
                var player = new PlayerReference(my);
                Players.Add(player.Name, player);
            }

            Actors = Exts.Lazy(() =>
            {
                var ret = new Dictionary <string, ActorReference>();
                foreach (var kv in nd["Actors"].ToDictionary())
                {
                    ret.Add(kv.Key, new ActorReference(kv.Value.Value, kv.Value.ToDictionary()));
                }
                return(ret);
            });

            // Smudges
            Smudges = Exts.Lazy(() =>
            {
                var ret = new List <SmudgeReference>();
                foreach (var name in nd["Smudges"].ToDictionary().Keys)
                {
                    var vals = name.Split(' ');
                    var loc  = vals[1].Split(',');
                    ret.Add(new SmudgeReference(vals[0], new int2(
                                                    Exts.ParseIntegerInvariant(loc[0]),
                                                    Exts.ParseIntegerInvariant(loc[1])),
                                                Exts.ParseIntegerInvariant(vals[2])));
                }

                return(ret);
            });

            RuleDefinitions          = MiniYaml.NodesOrEmpty(yaml, "Rules");
            SequenceDefinitions      = MiniYaml.NodesOrEmpty(yaml, "Sequences");
            VoxelSequenceDefinitions = MiniYaml.NodesOrEmpty(yaml, "VoxelSequences");
            WeaponDefinitions        = MiniYaml.NodesOrEmpty(yaml, "Weapons");
            VoiceDefinitions         = MiniYaml.NodesOrEmpty(yaml, "Voices");
            NotificationDefinitions  = MiniYaml.NodesOrEmpty(yaml, "Notifications");
            TranslationDefinitions   = MiniYaml.NodesOrEmpty(yaml, "Translations");

            MapTiles     = Exts.Lazy(() => LoadMapTiles());
            MapResources = Exts.Lazy(() => LoadResourceTiles());
            MapHeight    = Exts.Lazy(() => LoadMapHeight());

            TileShape      = Game.ModData.Manifest.TileShape;
            SubCellOffsets = Game.ModData.Manifest.SubCellOffsets;
            LastSubCell    = (SubCell)(SubCellOffsets.Length - 1);
            DefaultSubCell = (SubCell)Game.ModData.Manifest.SubCellDefaultIndex;

            if (Container.Exists("map.png"))
            {
                using (var dataStream = Container.GetContent("map.png"))
                    CustomPreview = new Bitmap(dataStream);
            }

            PostInit();

            // The Uid is calculated from the data on-disk, so
            // format changes must be flushed to disk.
            // TODO: this isn't very nice
            if (MapFormat < 7)
            {
                Save(path);
            }

            Uid = ComputeHash();
        }
Esempio n. 15
0
        // The standard constructor for most purposes
        public Map(string path)
        {
            Path      = path;
            Container = GlobalFileSystem.OpenPackage(path, null, int.MaxValue);

            AssertExists("map.yaml");
            AssertExists("map.bin");

            var yaml = new MiniYaml(null, MiniYaml.FromStream(Container.GetContent("map.yaml"), path));

            FieldLoader.Load(this, yaml);

            // Support for formats 1-3 dropped 2011-02-11.
            // Use release-20110207 to convert older maps to format 4
            // Use release-20110511 to convert older maps to format 5
            // Use release-20141029 to convert older maps to format 6
            if (MapFormat < 6)
            {
                throw new InvalidDataException("Map format {0} is not supported.\n File: {1}".F(MapFormat, path));
            }

            var nd = yaml.ToDictionary();

            // Format 6 -> 7 combined the Selectable and UseAsShellmap flags into the Class enum
            if (MapFormat < 7)
            {
                MiniYaml useAsShellmap;
                if (nd.TryGetValue("UseAsShellmap", out useAsShellmap) && bool.Parse(useAsShellmap.Value))
                {
                    Visibility = MapVisibility.Shellmap;
                }
                else if (Type == "Mission" || Type == "Campaign")
                {
                    Visibility = MapVisibility.MissionSelector;
                }
            }

            SpawnPoints = Exts.Lazy(() =>
            {
                var spawns = new List <CPos>();
                foreach (var kv in ActorDefinitions.Where(d => d.Value.Value == "mpspawn"))
                {
                    var s = new ActorReference(kv.Value.Value, kv.Value.ToDictionary());

                    spawns.Add(s.InitDict.Get <LocationInit>().Value(null));
                }

                return(spawns.ToArray());
            });

            RuleDefinitions          = MiniYaml.NodesOrEmpty(yaml, "Rules");
            SequenceDefinitions      = MiniYaml.NodesOrEmpty(yaml, "Sequences");
            VoxelSequenceDefinitions = MiniYaml.NodesOrEmpty(yaml, "VoxelSequences");
            WeaponDefinitions        = MiniYaml.NodesOrEmpty(yaml, "Weapons");
            VoiceDefinitions         = MiniYaml.NodesOrEmpty(yaml, "Voices");
            NotificationDefinitions  = MiniYaml.NodesOrEmpty(yaml, "Notifications");
            TranslationDefinitions   = MiniYaml.NodesOrEmpty(yaml, "Translations");
            PlayerDefinitions        = MiniYaml.NodesOrEmpty(yaml, "Players");

            ActorDefinitions  = MiniYaml.NodesOrEmpty(yaml, "Actors");
            SmudgeDefinitions = MiniYaml.NodesOrEmpty(yaml, "Smudges");

            MapTiles     = Exts.Lazy(LoadMapTiles);
            MapResources = Exts.Lazy(LoadResourceTiles);
            MapHeight    = Exts.Lazy(LoadMapHeight);

            TileShape      = Game.ModData.Manifest.TileShape;
            SubCellOffsets = Game.ModData.Manifest.SubCellOffsets;
            LastSubCell    = (SubCell)(SubCellOffsets.Length - 1);
            DefaultSubCell = (SubCell)Game.ModData.Manifest.SubCellDefaultIndex;

            if (Container.Exists("map.png"))
            {
                using (var dataStream = Container.GetContent("map.png"))
                    CustomPreview = new Bitmap(dataStream);
            }

            PostInit();

            // The Uid is calculated from the data on-disk, so
            // format changes must be flushed to disk.
            // TODO: this isn't very nice
            if (MapFormat < 7)
            {
                Save(path);
            }

            Uid = ComputeHash();
        }
Esempio n. 16
0
        void SetupMapTab(MapClassification tab, MapVisibility filter, string tabButtonName, string tabContainerName, ScrollItemWidget itemTemplate)
        {
            var tabContainer = widget.Get<ContainerWidget>(tabContainerName);
            tabContainer.IsVisible = () => currentTab == tab;
            var tabScrollpanel = tabContainer.Get<ScrollPanelWidget>("MAP_LIST");
            tabScrollpanel.Layout = new GridLayout(tabScrollpanel);
            scrollpanels.Add(tab, tabScrollpanel);

            var tabButton = widget.Get<ButtonWidget>(tabButtonName);
            tabButton.IsHighlighted = () => currentTab == tab;
            tabButton.IsVisible = () => tabMaps[tab].Any();
            tabButton.OnClick = () => SwitchTab(tab, itemTemplate);

            RefreshMaps(tab, filter);
        }
Esempio n. 17
0
        public string GenerateStaticMapURL(StaticMapRequest request)
        {
            string scheme = request.IsSSL ? "https://" : "http://";

            var parametersList = new QueryStringParametersList();

            if (!string.IsNullOrEmpty(request.ApiKey))
            {
                string apiKey = request.ApiKey;
                parametersList.Add("key", apiKey);
            }

            if (request.Center != null)
            {
                ILocationString center = request.Center;

                string centerLocation = center.LocationString;

                parametersList.Add("center", centerLocation);
            }

            if (request.Zoom != default(int))
            {
                parametersList.Add("zoom", request.Zoom.ToString());
            }

            if (request.Scale != default(int))
            {
                if (!ValidScales.Contains(request.Scale))
                {
                    throw new ArgumentException("Scale is invalid; must be a value of 1, 2 or 4");
                }

                parametersList.Add("scale", request.Scale.ToString());
            }

            if (request.Size.Width != default(int) || request.Size.Height != default(int))
            {
                ImageSize imageSize = request.Size;

                parametersList.Add("size", string.Format("{0}x{1}", imageSize.Width, imageSize.Height));
            }
            else
            {
                throw new ArgumentException("Size is invalid");
            }

            if (request.ImageFormat != default(ImageFormat))
            {
                string format;

                switch (request.ImageFormat)
                {
                case ImageFormat.PNG8:
                    format = "png8";
                    break;

                case ImageFormat.PNG32:
                    format = "png32";
                    break;

                case ImageFormat.GIF:
                    format = "gif";
                    break;

                case ImageFormat.JPG:
                    format = "jpg";
                    break;

                case ImageFormat.JPG_baseline:
                    format = "jpg-baseline";
                    break;

                default:
                    throw new ArgumentOutOfRangeException("ImageFormat");
                }

                parametersList.Add("format", format);
            }

            if (request.MapType != null)
            {
                string type;

                switch (request.MapType)
                {
                case MapType.Roadmap:
                    type = "roadmap";
                    break;

                case MapType.Satellite:
                    type = "satellite";
                    break;

                case MapType.Terrain:
                    type = "terrain";
                    break;

                case MapType.Hybrid:
                    type = "hybrid";
                    break;

                default:
                    throw new ArgumentOutOfRangeException("MapType");
                }

                parametersList.Add("maptype", type);
            }

            if (request.Style != null)
            {
                MapStyle style = request.Style;

                var styleComponents = new List <string>();

                if (style.MapFeature != default(MapFeature))
                {
                    string mapFeature;

                    switch (style.MapFeature)
                    {
                    case MapFeature.All:
                        mapFeature = "all";
                        break;

                    case MapFeature.Road:
                        mapFeature = "road";
                        break;

                    case MapFeature.Landscape:
                        mapFeature = "landscape";
                        break;

                    default:
                        throw new ArgumentOutOfRangeException();
                    }

                    styleComponents.Add("feature:" + mapFeature);
                }

                if (style.MapElement != default(MapElement))
                {
                    string element;

                    switch (style.MapElement)
                    {
                    case MapElement.All:
                        element = "all";
                        break;

                    case MapElement.Geometry:
                        element = "geometry";
                        break;

                    case MapElement.Labels:
                        element = "lables";
                        break;

                    default:
                        throw new ArgumentOutOfRangeException();
                    }

                    styleComponents.Add("element:" + element);
                }

                string hue = style.HUE;
                if (hue != null)
                {
                    styleComponents.Add("hue:" + hue);
                }

                float?lightness = style.Lightness;
                if (lightness != null)
                {
                    styleComponents.Add("lightness:" + lightness);
                }


                float?saturation = style.Saturation;
                if (saturation != null)
                {
                    styleComponents.Add("saturation:" + saturation);
                }

                float?gamma = style.Gamma;
                if (gamma != null)
                {
                    styleComponents.Add("gamma:" + gamma);
                }

                bool inverseLightness = style.InverseLightness;
                if (inverseLightness)
                {
                    styleComponents.Add("inverse_lightnes:true");
                }

                MapVisibility mapVisibility = style.MapVisibility;

                if (mapVisibility != default(MapVisibility))
                {
                    string visibility;

                    switch (mapVisibility)
                    {
                    case MapVisibility.On:
                        visibility = "on";
                        break;

                    case MapVisibility.Off:
                        visibility = "off";
                        break;

                    case MapVisibility.Simplified:
                        visibility = "simplified";
                        break;

                    default:
                        throw new ArgumentOutOfRangeException();
                    }

                    styleComponents.Add("visibility:" + visibility);
                }

                parametersList.Add("style", string.Join("|", styleComponents));
            }

            IList <Marker> markers = request.Markers;

            if (markers != null)
            {
                foreach (Marker marker in markers)
                {
                    var markerStyleParams = new List <string>();

                    MarkerStyle markerStyle = marker.Style;
                    if (markerStyle != null)
                    {
                        if (string.IsNullOrWhiteSpace(markerStyle.Color))
                        {
                            throw new ArgumentException("Marker style color can't be empty");
                        }

                        markerStyleParams.Add("color:" + markerStyle.Color);

                        if (!string.IsNullOrWhiteSpace(markerStyle.Label))
                        {
                            markerStyleParams.Add("label:" + markerStyle.Label);
                        }

                        if (markerStyle.Size != default(MarkerSize))
                        {
                            switch (markerStyle.Size)
                            {
                            case MarkerSize.Mid:
                                markerStyleParams.Add("size:mid");
                                break;

                            case MarkerSize.Tiny:
                                markerStyleParams.Add("size:tiny");
                                break;

                            case MarkerSize.Small:
                                markerStyleParams.Add("size:small");
                                break;

                            default:
                                throw new ArgumentOutOfRangeException();
                            }
                        }
                    }

                    string styleString = string.Join("|", markerStyleParams);

                    string locations = string.Join("|", marker.Locations.Select(location => location.LocationString));

                    parametersList.Add("markers", string.Format("{0}|{1}", styleString, locations));
                }
            }

            IList <Path> pathes = request.Pathes;

            if (pathes != null)
            {
                foreach (Path path in pathes)
                {
                    var pathStyleParams = new List <string>();

                    PathStyle pathStyle = path.Style;

                    if (pathStyle != null)
                    {
                        if (string.IsNullOrWhiteSpace(pathStyle.Color))
                        {
                            throw new ArgumentException("Path style color can't be empty");
                        }

                        pathStyleParams.Add("color:" + pathStyle.Color);

                        if (!string.IsNullOrWhiteSpace(pathStyle.FillColor))
                        {
                            pathStyleParams.Add("fillcolor:" + pathStyle.FillColor);
                        }

                        if (pathStyle.Weight != default(int))
                        {
                            pathStyleParams.Add("weight:" + pathStyle.Weight);
                        }
                    }

                    string styleString = string.Join("|", pathStyleParams);

                    string locations = string.Join("|", path.Locations.Select(location => location.LocationString));

                    parametersList.Add("path", string.Format("{0}|{1}", styleString, locations));
                }
            }

            return(scheme + BaseUrl + "?" + parametersList.GetQueryStringPostfix());
        }
Esempio n. 18
0
        internal MapChooserLogic(Widget widget, string initialMap, MapClassification initialTab, Action onExit, Action<string> onSelect, MapVisibility filter)
        {
            this.widget = widget;
            this.onSelect = onSelect;

            var approving = new Action(() => { Ui.CloseWindow(); onSelect(selectedUid); });
            var canceling = new Action(() => { Ui.CloseWindow(); onExit(); });

            var okButton = widget.Get<ButtonWidget>("BUTTON_OK");
            okButton.Disabled = this.onSelect == null;
            okButton.OnClick = approving;
            widget.Get<ButtonWidget>("BUTTON_CANCEL").OnClick = canceling;

            gameModeDropdown = widget.GetOrNull<DropDownButtonWidget>("GAMEMODE_FILTER");

            var itemTemplate = widget.Get<ScrollItemWidget>("MAP_TEMPLATE");
            widget.RemoveChild(itemTemplate);

            var mapFilterInput = widget.GetOrNull<TextFieldWidget>("MAPFILTER_INPUT");
            if (mapFilterInput != null)
            {
                mapFilterInput.TakeKeyboardFocus();
                mapFilterInput.OnEscKey = () =>
                {
                    if (mapFilterInput.Text.Length == 0)
                        canceling();
                    else
                    {
                        mapFilter = mapFilterInput.Text = null;
                        EnumerateMaps(currentTab, itemTemplate);
                    }

                    return true;
                };
                mapFilterInput.OnEnterKey = () => { approving(); return true; };
                mapFilterInput.OnTextEdited = () =>
                {
                    mapFilter = mapFilterInput.Text;
                    EnumerateMaps(currentTab, itemTemplate);
                };
            }

            var randomMapButton = widget.GetOrNull<ButtonWidget>("RANDOMMAP_BUTTON");
            if (randomMapButton != null)
            {
                randomMapButton.OnClick = () =>
                {
                    var uid = visibleMaps.Random(Game.CosmeticRandom);
                    selectedUid = uid;
                    scrollpanels[currentTab].ScrollToItem(uid, smooth: true);
                };
                randomMapButton.IsDisabled = () => visibleMaps == null || visibleMaps.Length == 0;
            }

            var deleteMapButton = widget.Get<ButtonWidget>("DELETE_MAP_BUTTON");
            deleteMapButton.IsDisabled = () => Game.ModData.MapCache[selectedUid].Class != MapClassification.User;
            deleteMapButton.IsVisible = () => currentTab == MapClassification.User;
            deleteMapButton.OnClick = () =>
            {
                DeleteOneMap(selectedUid, (string newUid) =>
                {
                    RefreshMaps(currentTab, filter);
                    EnumerateMaps(currentTab, itemTemplate);
                    if (!tabMaps[currentTab].Any())
                        SwitchTab(Game.ModData.MapCache[newUid].Class, itemTemplate);
                });
            };

            var deleteAllMapsButton = widget.Get<ButtonWidget>("DELETE_ALL_MAPS_BUTTON");
            deleteAllMapsButton.IsVisible = () => currentTab == MapClassification.User;
            deleteAllMapsButton.OnClick = () =>
            {
                DeleteAllMaps(visibleMaps, (string newUid) =>
                {
                    RefreshMaps(currentTab, filter);
                    EnumerateMaps(currentTab, itemTemplate);
                    SwitchTab(Game.ModData.MapCache[newUid].Class, itemTemplate);
                });
            };

            SetupMapTab(MapClassification.User, filter, "USER_MAPS_TAB_BUTTON", "USER_MAPS_TAB", itemTemplate);
            SetupMapTab(MapClassification.System, filter, "SYSTEM_MAPS_TAB_BUTTON", "SYSTEM_MAPS_TAB", itemTemplate);

            if (initialMap == null && tabMaps.Keys.Contains(initialTab) && tabMaps[initialTab].Any())
            {
                selectedUid = WidgetUtils.ChooseInitialMap(tabMaps[initialTab].Select(mp => mp.Uid).First());
                currentTab = initialTab;
            }
            else
            {
                selectedUid = WidgetUtils.ChooseInitialMap(initialMap);
                currentTab = tabMaps.Keys.FirstOrDefault(k => tabMaps[k].Select(mp => mp.Uid).Contains(selectedUid));
            }

            SwitchTab(currentTab, itemTemplate);
        }
Esempio n. 19
0
        internal MapChooserLogic(Widget widget, ModData modData, string initialMap,
                                 MapClassification initialTab, Action onExit, Action <string> onSelect, MapVisibility filter)
        {
            this.widget   = widget;
            this.modData  = modData;
            this.onSelect = onSelect;

            var approving = new Action(() => { Ui.CloseWindow(); onSelect(selectedUid); });
            var canceling = new Action(() => { Ui.CloseWindow(); onExit(); });

            var okButton = widget.Get <ButtonWidget>("BUTTON_OK");

            okButton.Disabled = this.onSelect == null;
            okButton.OnClick  = approving;
            widget.Get <ButtonWidget>("BUTTON_CANCEL").OnClick = canceling;

            gameModeDropdown = widget.GetOrNull <DropDownButtonWidget>("GAMEMODE_FILTER");

            var itemTemplate = widget.Get <ScrollItemWidget>("MAP_TEMPLATE");

            widget.RemoveChild(itemTemplate);

            var mapFilterInput = widget.GetOrNull <TextFieldWidget>("MAPFILTER_INPUT");

            if (mapFilterInput != null)
            {
                mapFilterInput.TakeKeyboardFocus();
                mapFilterInput.OnEscKey = () =>
                {
                    if (mapFilterInput.Text.Length == 0)
                    {
                        canceling();
                    }
                    else
                    {
                        mapFilter = mapFilterInput.Text = null;
                        EnumerateMaps(currentTab, itemTemplate);
                    }

                    return(true);
                };
                mapFilterInput.OnEnterKey   = () => { approving(); return(true); };
                mapFilterInput.OnTextEdited = () =>
                {
                    mapFilter = mapFilterInput.Text;
                    EnumerateMaps(currentTab, itemTemplate);
                };
            }

            var randomMapButton = widget.GetOrNull <ButtonWidget>("RANDOMMAP_BUTTON");

            if (randomMapButton != null)
            {
                randomMapButton.OnClick = () =>
                {
                    var uid = visibleMaps.Random(Game.CosmeticRandom);
                    selectedUid = uid;
                    scrollpanels[currentTab].ScrollToItem(uid, smooth: true);
                };
                randomMapButton.IsDisabled = () => visibleMaps == null || visibleMaps.Length == 0;
            }

            var deleteMapButton = widget.Get <ButtonWidget>("DELETE_MAP_BUTTON");

            deleteMapButton.IsDisabled = () => modData.MapCache[selectedUid].Class != MapClassification.User;
            deleteMapButton.IsVisible  = () => currentTab == MapClassification.User;
            deleteMapButton.OnClick    = () =>
            {
                DeleteOneMap(selectedUid, (string newUid) =>
                {
                    RefreshMaps(currentTab, filter);
                    EnumerateMaps(currentTab, itemTemplate);
                    if (!tabMaps[currentTab].Any())
                    {
                        SwitchTab(modData.MapCache[newUid].Class, itemTemplate);
                    }
                });
            };

            var deleteAllMapsButton = widget.Get <ButtonWidget>("DELETE_ALL_MAPS_BUTTON");

            deleteAllMapsButton.IsVisible = () => currentTab == MapClassification.User;
            deleteAllMapsButton.OnClick   = () =>
            {
                DeleteAllMaps(visibleMaps, (string newUid) =>
                {
                    RefreshMaps(currentTab, filter);
                    EnumerateMaps(currentTab, itemTemplate);
                    SwitchTab(modData.MapCache[newUid].Class, itemTemplate);
                });
            };

            var refreshMapsButton = widget.GetOrNull <ButtonWidget>("REFRESHMAPS_BUTTON");

            if (refreshMapsButton != null)
            {
                refreshMapsButton.OnClick = () =>
                {
                    Game.ModData.MapCache.LoadMaps();
                    RefreshMaps(currentTab, filter);
                    EnumerateMaps(currentTab, itemTemplate);
                };
            }

            SetupMapTab(MapClassification.User, filter, "USER_MAPS_TAB_BUTTON", "USER_MAPS_TAB", itemTemplate);
            SetupMapTab(MapClassification.System, filter, "SYSTEM_MAPS_TAB_BUTTON", "SYSTEM_MAPS_TAB", itemTemplate);

            if (initialMap == null && tabMaps.Keys.Contains(initialTab) && tabMaps[initialTab].Any())
            {
                selectedUid = Game.ModData.MapCache.ChooseInitialMap(tabMaps[initialTab].Select(mp => mp.Uid).First(),
                                                                     Game.CosmeticRandom);
                currentTab = initialTab;
            }
            else
            {
                selectedUid = Game.ModData.MapCache.ChooseInitialMap(initialMap, Game.CosmeticRandom);
                currentTab  = tabMaps.Keys.FirstOrDefault(k => tabMaps[k].Select(mp => mp.Uid).Contains(selectedUid));
            }

            SwitchTab(currentTab, itemTemplate);
        }
Esempio n. 20
0
        void EnumerateMaps(Action <string> onSelect, MapVisibility filter)
        {
            var maps = Game.ModData.MapCache
                       .Where(m => m.Status == MapStatus.Available && (m.Map.Visibility & filter) != 0)
                       .Where(m => gameMode == null || m.Type == gameMode)
                       .Where(m => mapFilter == null ||
                              m.Title.IndexOf(mapFilter, StringComparison.OrdinalIgnoreCase) >= 0 ||
                              m.Author.IndexOf(mapFilter, StringComparison.OrdinalIgnoreCase) >= 0)
                       .OrderBy(m => m.PlayerCount)
                       .ThenBy(m => m.Title);

            scrollpanel.RemoveChildren();
            foreach (var loop in maps)
            {
                var preview = loop;

                // Access the minimap to trigger async generation of the minimap.
                preview.GetMinimap();

                var item = ScrollItemWidget.Setup(preview.Uid, itemTemplate, () => selectedUid == preview.Uid,
                                                  () => selectedUid = preview.Uid, () => { Ui.CloseWindow(); onSelect(preview.Uid); });
                item.IsVisible = () => item.RenderBounds.IntersectsWith(scrollpanel.RenderBounds);

                var titleLabel = item.Get <LabelWidget>("TITLE");
                titleLabel.GetText = () => preview.Title;

                var previewWidget = item.Get <MapPreviewWidget>("PREVIEW");
                previewWidget.Preview = () => preview;

                var detailsWidget = item.GetOrNull <LabelWidget>("DETAILS");
                if (detailsWidget != null)
                {
                    detailsWidget.GetText = () => "{0} ({1} players)".F(preview.Type, preview.PlayerCount);
                }

                var authorWidget = item.GetOrNull <LabelWidget>("AUTHOR");
                if (authorWidget != null)
                {
                    authorWidget.GetText = () => "Created by {0}".F(preview.Author);
                }

                var sizeWidget = item.GetOrNull <LabelWidget>("SIZE");
                if (sizeWidget != null)
                {
                    var size = preview.Bounds.Width + "x" + preview.Bounds.Height;
                    var numberPlayableCells = preview.Bounds.Width * preview.Bounds.Height;
                    if (numberPlayableCells >= 120 * 120)
                    {
                        size += " (Huge)";
                    }
                    else if (numberPlayableCells >= 90 * 90)
                    {
                        size += " (Large)";
                    }
                    else if (numberPlayableCells >= 60 * 60)
                    {
                        size += " (Medium)";
                    }
                    else
                    {
                        size += " (Small)";
                    }
                    sizeWidget.GetText = () => size;
                }

                scrollpanel.AddChild(item);
            }

            visibleMaps = maps.Select(m => m.Uid).ToArray();
            if (visibleMaps.Contains(selectedUid))
            {
                scrollpanel.ScrollToItem(selectedUid);
            }
        }