示例#1
0
    /// <summary>
    /// Saves map to xml file. Gets name from 3D input field.
    /// </summary>
    public void SaveMap()
    {
        if (mapName.Length == 0 || mapName.IndexOfAny(Path.GetInvalidFileNameChars()) != -1)
        {
            msg.SetText("Map name is not correct!", 4f, Color.red);
            return;
        }

        mapPath = PathToMapsDir + "/" + Path.GetFileNameWithoutExtension(mapName) + ".xml";

        Map map = new Map(mapName, elementTypes, biomeType, difficulty);

        if (map.IsMapDefined)
        {
            MapSerializer mapSerializer = new MapSerializer(mapPath);
            mapSerializer.Serialize(map);
            msg.SetText($"Saved map correctly in: {mapPath}", 6f, Color.green);

            MakeMapMiniature();

            RankingManager.RemoveAllRecords(map.name);
            SaveLoadManager.ClearSave(map);
        }
        else
        {
            msg.SetText("Cannot save this map due to some problems!", 4f, Color.red);
        }
    }
示例#2
0
        public static void Init(TypeMap types, Class2TypeMap class2type)
        {
            RuntimeExceptionSerializer.Init(
                types.Get(ETCH_RUNTIME_EXCEPTION_TYPE_NAME), class2type);

            ListSerializer.Init(
                types.Get(ETCH_LIST_TYPE_NAME), class2type);

            MapSerializer.Init(
                types.Get(ETCH_MAP_TYPE_NAME), class2type);

            /*    SetSerializer.Init(
             *      types.Get(ETCH_SET_TYPE_NAME), class2type); */

            DateSerializer.Init(
                types.Get(ETCH_DATETIME_TYPE_NAME), class2type);

            AuthExceptionSerializer.Init(
                types.Get(ETCH_AUTH_EXCEPTION_TYPE_NAME), class2type);

            XType t3 = types.Get(ETCH_EXCEPTION_MESSAGE_NAME);

            t3.PutValidator(_mf_result, Validator_RuntimeException.Get());
            t3.PutValidator(_mf__messageId, Validator_long.Get(0));
            t3.PutValidator(_mf__inReplyTo, Validator_long.Get(0));
        }
示例#3
0
    void Awake()
    {
        LoadMap();
        bool isLoaded = (mapSerializer != null) && mapSerializer.IsInitialized();

        gridCanvas = GetComponentInChildren <Canvas>();

        cells = new HexCell[height * width];

        for (int row = 0; row < height; row++)
        {
            for (int column = 0; column < width; column++)
            {
                CreateCell(column, row, isLoaded);
            }
        }

        mapSerializer = null;
        selectedCell  = cells[GetCellIndex(0, 0)];

        gameState = FindObjectOfType <GameState>();
        gameState.MovePlayerToCell(selectedCell);

        ComputeBoundingRect();
    }
示例#4
0
 public async Task <ActionResult <string> > GetMap()
 {
     if (MasterGameController.TheGame.Map == null)
     {
         return(NotFound());
     }
     return(await Task.Run(() => MapSerializer.Serialize(MasterGameController.TheGame.Map)));
 }
示例#5
0
    public static void SaveMap()
    {
        string path = EditorUtility.SaveFilePanel("", "", "", "xml");

        if (path != null || path != "")
        {
            MapSerializer.Save(currentMap, path);
        }
    }
示例#6
0
    public void Load()
    {
        if (input.text == "")
        {
            return;
        }

        MapSerializer.LoadMap(Application.streamingAssetsPath + "/maps/" + input.text + ".map");
    }
示例#7
0
        public IMap Generate(string mapName, IRandom random, IProgress <string> progress)
        {
            var mapData = DataFileLoader.LoadFile(MapFile);
            var map     = MapSerializer.Deserialize(SystemContainer, mapData, mapName);

            map.MapKey = new MapKey(mapName);

            return(map);
        }
示例#8
0
文件: Main.cs 项目: agrath/cumberland
        public static void Main(string[] args)
        {
            bool showHelp = false;
            bool showVersion = false;

            // search in the local directory for espg files
            // so Windows ppl don't have to have it installed
            ProjFourWrapper.CustomSearchPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

            MapSerializer ms = new MapSerializer();
            ms.AddDatabaseFeatureSourceType<PostGISFeatureSource>();
            ms.AddDatabaseFeatureSourceType<Cumberland.Data.SqlServer.SqlServerFeatureSource>();

            OptionSet options = new OptionSet();

            options.Add("h|help",  "show this message and exit",
                        delegate (string v) { showHelp = v!= null; });
            options.Add("v|version",
                        "Displays the version",
                        delegate(string v) { showVersion = v != null; });

            options.Parse(args);

            if (showVersion)
            {
                System.Console.WriteLine("Version " +
                                         System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString());
                return;
            }

            if (showHelp)
            {
                ShowHelp(options);
                return;
            }

            if (args.Length == 0)
            {
                Console.WriteLine("No Map file specified");
                ShowHelp(options);
                return;
            }

            if (args.Length == 1)
            {
                Console.WriteLine("No output file specified");
                ShowHelp(options);
                return;
            }

            Map map = ms.Deserialize(args[0]);

            File.WriteAllText(args[1],
                KeyholeMarkupLanguage.CreateFromMap(map),
                Encoding.UTF8);
        }
        public void Serialize_File1_TestMap_ReturnsExpectedSerialization(int testCase)
        {
            var testMap = GetTestMap(testCase);

            var result = MapSerializer.Serialize(testMap);

            var expected = LoadSerializedData(testCase);

            result.Should().BeEquivalentTo(expected);
        }
示例#10
0
        private void LoadVaultData(ISystemContainer systemContainer)
        {
            var vaultFiles = _vaultDataProvider.GetData();

            foreach (var vaultFile in vaultFiles)
            {
                var vault = MapSerializer.Deserialize(systemContainer, vaultFile);
                systemContainer.MapSystem.AddVault(vault);
            }
        }
示例#11
0
 public SaveState GetSaveState()
 {
     return(new SaveState
     {
         Entities = _systemContainer.EntityEngine.MutableEntities.Select(e => EntitySerializer.Serialize(e)).ToList(),
         Maps = _systemContainer.MapSystem.MapCollection.AllMaps.Select(m => MapSerializer.Serialize(m)).ToList(),
         Time = _systemContainer.TimeSystem.CurrentTime,
         Messages = _systemContainer.MessageSystem.AllMessages.Select(m => MessageSerializer.Serialize(m)).ToList()
     });
 }
示例#12
0
        public async Task <ActionResult> SetMap()
        {
            using (StreamReader streamReader = new StreamReader(Request.Body, Encoding.UTF8))
            {
                string json = await streamReader.ReadToEndAsync();

                await Task.Run(() => MasterGameController.TheGame.Map = MapSerializer.Deserialize(json, MasterGameController.TheGame.Tiles));
            }
            return(Ok());
        }
示例#13
0
        public void Deserialize_File1_ReturnsTestMap(int testCase)
        {
            string serialisedText = LoadSerializedData(testCase);

            var result = MapSerializer.Deserialize(systemContainer, serialisedText);

            var reserialised = MapSerializer.Serialize(result);

            var expected = GetTestMap(testCase);

            result.Should().BeEquivalentTo(expected);
        }
示例#14
0
    public void SaveMap()
    {
        if (path == "")
        {
                        #if UNITY_EDITOR
            path = EditorUtility.SaveFilePanel("Select file location", "", "map", "vlmap");
                        #endif
        }

        MapSerializer mapSerializer = new MapSerializer();
        mapSerializer.SaveMap(map, path);
    }
示例#15
0
        public void SaveSystem_GetSaveState_WithMap_ReturnsSaveStateWithSerialisedMap()
        {
            var mapCell = new Entity(0, "Map Cell", new IEntityComponent[] { new Appearance(), new Physical() });

            _mutableEntities.Add(mapCell);
            var map = new Map("key", mapCell);

            _mapCollection.Add(map.MapKey, map);

            var result = _saveSystem.GetSaveState();

            var expected = MapSerializer.Serialize(map);

            result.Maps.Single().Should().Be(expected);
        }
示例#16
0
        /*
         * 22 = field 4, type String
         * 07 = length 7
         * 08 = field 1, type Varint
         * 01 = -1 (zigzag)
         * 12 = field 2, type String
         * 03 = length 3
         * 61-62-63 = abc
         * 22 = field 4, type String
         * 05 = length 5
         * 12 = field 2, type String
         * 03 = length 3
         * 64-65-66 = def
         * 22 = field 4, type String
         * 07 = length 7
         * 08 = field 1, type Varint
         * 02 = 1 (zigzag)
         * 12 = field 2, type String
         * 03 = length 3
         * 67-68-69 = ghi
         */
        public void ReadWriteMapWorks(SerializerFeatures keyFeatures, string expected)
        {
            using var ms = new MemoryStream();

            var data = new Dictionary <int, string>
            {
                { -1, "abc" },
                { 0, "def" },
                { 1, "ghi" },
            };

            var writer = ProtoWriter.State.Create(ms, null);

            try
            {
                MapSerializer.CreateDictionary <int, string>().WriteMap(ref writer, 4, default, data, keyFeatures, default);
示例#17
0
    void LoadMap()
    {
        if (mapAsset != null)
        {
            mapSerializer = new MapSerializer();
            mapSerializer.Load(mapAsset);

            if (!mapSerializer.IsInitialized())
            {
                Debug.LogWarning("Failed to load map");
            }
            else if ((mapSerializer.Width != width) || (mapSerializer.Height != height))
            {
                Debug.LogWarning("Loaded map is incompatible");
            }
        }
    }
示例#18
0
    public static void LoadMap()
    {
        string path = EditorUtility.OpenFilePanel("", "", "xml");

        if (path != null || path != "")
        {
            hasMap = false;
            Map map = MapSerializer.Load(path);

            if (map != null)
            {
                hasMap       = true;
                currentMap   = map;
                currentFloor = 0;
            }
        }
    }
 private SaveState GetTestSaveState(int saveState)
 {
     return(new SaveState()
     {
         Seed = "TestSeed",
         Maps = new List <string> {
             MapSerializer.Serialize(GetTestMap(0))
         },
         Entities = new List <string>()
         {
             EntitySerializer.Serialize(GetTestEntity(0))
         },
         Messages = new List <string> {
             "This is a test message"
         },
         Time = 42
     });
 }
示例#20
0
    public void LoadMap()
    {
        CloseMap();

                #if UNITY_EDITOR
        path = EditorUtility.OpenFilePanel("Load map", "", "vlmap");
                #endif

        MapSerializer mapSerializer = new MapSerializer();
        this.map = mapSerializer.LoadMap(path);

        mapController.RegenerateMap(map);
        shipPannelController.RegenerateShip(map.ships);
        mapController.RegenerateMapEvents();

        mapInformationSetting.SetActive(true);
        UpdateDisplay();
    }
示例#21
0
        public void MapSerializesToJson()
        {
            //2x4 map
            Tile tile = new Tile(1, TileMovementFlags.None);
            List <List <Tile> > tiles = new List <List <Tile> >();

            tiles.Add(new List <Tile> {
                tile, tile, tile, tile
            });
            tiles.Add(new List <Tile> {
                tile, tile, tile, tile
            });
            Map    aMap       = new Map(tiles);
            string serialized = MapSerializer.Serialize(aMap);

            string expected = "{\"Width\":2,\"Height\":4,\"Tiles\":[[1,1,1,1],[1,1,1,1]]}";

            Assert.That(serialized, Is.EqualTo(expected));
        }
示例#22
0
    private void DrawGUI()
    {
        EditorGUILayout.LabelField("Normalized file has to be in Assets/Maps");

        EditorGUILayout.BeginHorizontal();
        EditorGUILayout.LabelField("Normalized file name");
        normalizedFileName = EditorGUILayout.TextField(normalizedFileName);
        EditorGUILayout.EndHorizontal();

        EditorGUILayout.BeginHorizontal();
        EditorGUILayout.LabelField("New file name");
        newFileName = EditorGUILayout.TextField(newFileName);
        EditorGUILayout.EndHorizontal();

        EditorGUILayout.BeginHorizontal();
        EditorGUILayout.LabelField("Level ID");
        levelId = EditorGUILayout.TextField(levelId);
        EditorGUILayout.EndHorizontal();

        EditorGUILayout.BeginHorizontal();
        EditorGUILayout.LabelField("Biome");
        biomeType = (Biomes)EditorGUILayout.EnumPopup(biomeType);
        EditorGUILayout.EndHorizontal();

        EditorGUILayout.BeginHorizontal();
        EditorGUILayout.LabelField("Difficulty");
        difficulty = (Difficulty)EditorGUILayout.EnumPopup(difficulty);
        EditorGUILayout.EndHorizontal();

        if (!File.Exists(Path.Combine(Application.dataPath, "Resources/Maps", normalizedFileName)) || string.IsNullOrEmpty(levelId) ||
            string.IsNullOrEmpty(newFileName))
        {
            GUI.enabled = false;
        }

        if (GUILayout.Button("Convert"))
        {
            MapSerializer serializer = new MapSerializer(MapSerializer.MapsPath + "/" + newFileName);
            serializer.ConvertNormalizedFile(MapSerializer.MapsPath + "/" + normalizedFileName, levelId, biomeType, difficulty);
        }

        GUI.enabled = false;
    }
示例#23
0
    public void LoadMap()
    {
        // Load map
        string        mapName       = GameObject.Find("SceneSetting").GetComponent <SceneSetting>().MapName;
        string        path          = Application.dataPath + "/maps/" + mapName + ".vlmap";
        MapController mapController = GameObject.Find("Map").GetComponent <MapController>();
        MapSerializer mapSerializer = new MapSerializer();

        map = mapSerializer.LoadMap(path);
        mapController.RegenerateMap(map);

        timer.VirtualTime   = map.StartTime;
        timer.gameStartTime = map.StartTime;

        // GameObject.Find ("RoundManager").GetComponent<RoundManager> ().SimulationPhaseStartTime = map.StartTime;
        // timeWidgetController.SetSpeedOne();

        PreprocessOilSpillingEvent();
    }
示例#24
0
        public void MapDeserializesFromJson()
        {
            Tile        tile1 = new Tile(1, TileMovementFlags.BulletPassable);
            List <Tile> tiles = new List <Tile> {
                tile1
            };
            string source = "{\"Width\":2,\"Height\":4,\"Tiles\":[[1,1,1,1],[1,1,1,1]]}";

            Map map = MapSerializer.Deserialize(source, tiles);

            Assert.That(map.Width, Is.EqualTo(2));
            Assert.That(map.Height, Is.EqualTo(4));
            foreach (Tile[] row in map.Tiles)
            {
                foreach (Tile t in row)
                {
                    Assert.That(t, Is.EqualTo(tile1));
                }
            }
        }
示例#25
0
    public static void SaveLevelProgress(Map mapToSave, int movesCount)
    {
        PrepareDirectory();
        string        path       = GetPathFromMap(mapToSave);
        MapSerializer serializer = new MapSerializer(path);

        serializer.Serialize(mapToSave);

        XmlDocument doc = new XmlDocument();

        doc.Load(path);

        XmlNode      rootNode = doc.SelectSingleNode("SokobanLevel");
        XmlAttribute attr     = doc.CreateAttribute("moves");

        attr.Value = movesCount.ToString();
        rootNode.Attributes.Append(attr);

        doc.Save(path);
    }
示例#26
0
    private IEnumerator OpenLevelCoroutine(Difficulty difficulty)
    {
        MapSerializer serializer      = new MapSerializer(MapSerializer.MapsPath + "/" + LevelManager.CurrentManager.RandomMap(difficulty).name);
        Map           deserializedMap = serializer.Deserialize(true);

        LevelManager.CurrentManager.SetBackgroundColor(deserializedMap.biomeType);

        camAnim.SetInteger("view", LEVEL);
        camAnim.SetTrigger("switch");

        yield return(new WaitForSeconds(0.5f));

        module1.SetActive(false);
        module2.SetActive(false);
        module3.SetActive(false);
        credits.SetActive(false);

        camAnim.enabled = false;

        LevelManager.CurrentManager.LoadLevel(deserializedMap);
    }
示例#27
0
    public void NextLevel()
    {
        if (!winScreenModule1.GetBool("show"))
        {
            return;
        }
        winScreenModule1.SetBool("show", false);

        StartCoroutine(NextLevelCoroutine());

        IEnumerator NextLevelCoroutine()
        {
            yield return(new WaitForSeconds(1f));

            MapSerializer serializer      = new MapSerializer(MapSerializer.MapsPath + "/" + RandomMap(CurrentDifficulty).name);
            Map           deserializedMap = serializer.Deserialize(true);

            SetBackgroundColor(deserializedMap.biomeType);
            LoadLevel(deserializedMap);
        }
    }
示例#28
0
        public void Load()
        {
            var directoryName = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Saves");
            var fileName      = Path.Combine(directoryName, "saveFile.sav");

            var loadedState = SaveStateSerializer.Deserialize(File.ReadAllText(fileName));

            _systemContainer.TimeSystem.CurrentTime = loadedState.Time;

            _systemContainer.Seed = loadedState.Seed;

            _systemContainer.MapSystem.Initialise();

            _systemContainer.EntityEngine.Initialise(_systemContainer);

            foreach (var savedEntity in loadedState.Entities)
            {
                var entity = EntitySerializer.Deserialize(_systemContainer, savedEntity);
                if (entity.Name == "Player")
                {
                    _systemContainer.PlayerSystem.Player = entity;
                }
            }

            foreach (var savedMap in loadedState.Maps)
            {
                var map = MapSerializer.Deserialize(_systemContainer, savedMap);

                _systemContainer.MapSystem.MapCollection.Add(map.MapKey, map);
            }

            _systemContainer.MessageSystem.Initialise();

            foreach (var savedMessage in loadedState.Messages)
            {
                var message = MessageSerializer.Deserialize(savedMessage);

                _systemContainer.MessageSystem.AllMessages.Add(message);
            }
        }
示例#29
0
    public static Map LoadLevelProgress(Map defaultMap, out int movesCount)
    {
        string path = GetPathFromMap(defaultMap);

        if (!SaveExists(defaultMap))
        {
            movesCount = 0;
            return(null);
        }

        MapSerializer serializer    = new MapSerializer(path);
        Map           savedProgress = serializer.Deserialize(false);

        XmlDocument doc = new XmlDocument();

        doc.Load(path);
        XmlNode rootNode = doc.SelectSingleNode("SokobanLevel");

        movesCount = int.Parse(rootNode.Attributes.GetNamedItem("moves").Value);

        return(savedProgress);
    }
示例#30
0
    public void SaveMap()
    {
        Debug.Assert((mapAsset != null), "Invalid map asset");
        if (mapAsset != null)
        {
            mapSerializer = new MapSerializer(width, height);

            for (int row = 0; row < height; row++)
            {
                for (int column = 0; column < width; column++)
                {
                    int     index = GetCellIndex(column, row);
                    HexCell cell  = cells[index];

                    MapSerializer.CellProperties cellProperties = new MapSerializer.CellProperties();
                    cellProperties.m_Type = cell.GetType();

                    mapSerializer.SetValue(column, row, cellProperties);
                }
            }

            mapSerializer.Save(mapAsset);
        }
    }
示例#31
0
        public void TestRelativeToAbsoluteStylePointSymbolImagePath()
        {
            MapSerializer ms = new MapSerializer();
            Map m = ms.Deserialize("../../maps/mexico.xml");

            Assert.IsTrue(Path.IsPathRooted(m.Layers[5].Styles[2].PointSymbolImagePath));
        }
示例#32
0
    IEnumerator InstantiateButtons()
    {
        yield return(new WaitForSeconds(0.4f));

        int number = 1;

        for (int i = 0; i < 4; i++)
        {
            Vector3 pos = new Vector3(-6.4f, 8.8f - (3.3f * i), 0f);

            for (int j = 0; j < 5; j++)
            {
                GameObject obj = Instantiate(module2MapButton);
                spawnedMapButtons.Add(obj);
                obj.transform.SetParent(module2Levels.transform);
                obj.transform.localPosition = pos;

                obj.name = "PreLevel" + number.ToString();

                RankingManager.Record?bestResult = RankingManager.GetTheBestRecord("PreLevel" + number.ToString());

                if (bestResult != null)
                {
                    obj.transform.GetChild(0).GetComponent <TextMeshPro>().text += $" <size=\"1\"><b>{((RankingManager.Record)bestResult).points.ToString()}</b></size>";
                }
                else
                {
                    obj.transform.GetChild(0).GetComponent <TextMeshPro>().text += " <size=\"1\"><b>0</b></size>";
                }

                Button3D btn = obj.GetComponent <Button3D>();

                string iconPath = $"Maps/{Path.GetFileNameWithoutExtension($"{obj.name}_icon.jpg")}";

                MeshRenderer renderer = obj.GetComponent <MeshRenderer>();
                Material     mat      = new Material(Shader.Find("Legacy Shaders/Diffuse"));
                Texture2D    texture  = Resources.Load <Texture2D>(iconPath);
                print(iconPath);

                if (texture != null)
                {
                    mat.mainTexture   = texture;
                    renderer.material = mat;
                }

                btn.OnClick.AddListener((sender) =>
                {
                    MapSerializer serializer = new MapSerializer(MapSerializer.MapsPath + "/" + sender.name);
                    Map deserializedMap      = serializer.Deserialize(true);

                    module2Levels.SetActive(false);
                    module2Info.SetActive(true);

                    currentLevelModule2 = sender.name;

                    RankingManager.Record[] records = RankingManager.GetRecords(currentLevelModule2);
                    TextMeshPro text = module2Info.transform.GetChild(2).GetComponent <TextMeshPro>();
                    text.text        = "";

                    SetMapIcon(MapSerializer.MapsPath + "/" + sender.name + ".xml", module2Info.transform.GetChild(0).gameObject);

                    foreach (RankingManager.Record r in records)
                    {
                        text.text += $"Points: <b>{r.points.ToString()} | </b>Count of moves: <b>{r.moves.ToString()}</b> | Date: <b>{r.date.ToShortDateString()} {r.date.ToShortTimeString()}</b>\n";
                    }

                    Button3D playBtn      = module2Info.transform.GetChild(4).GetComponent <Button3D>();
                    Button3D playSavedBtn = module2Info.transform.GetChild(5).GetComponent <Button3D>();

                    playSavedBtn.isClickable = SaveLoadManager.SaveExists(deserializedMap);

                    playSavedBtn.OnClick.RemoveAllListeners();

                    if (playSavedBtn.isClickable)
                    {
                        playSavedBtn.OnClick.AddListener(s =>
                        {
                            Map progressedMap = SaveLoadManager.LoadLevelProgress(deserializedMap, out int movesCount);

                            StartCoroutine(Coroutine());

                            IEnumerator Coroutine()
                            {
                                camAnim.SetInteger("view", LEVEL);
                                camAnim.SetTrigger("switch");

                                yield return(new WaitForSeconds(0.5f));

                                if (spawnModule2ButtonsCor != null)
                                {
                                    StopCoroutine(spawnModule2ButtonsCor);
                                    spawnModule2ButtonsCor = null;
                                }

                                foreach (GameObject o in spawnedMapButtons)
                                {
                                    Destroy(o);
                                }

                                spawnedMapButtons.Clear();

                                module2.SetActive(false);
                                module2Info.SetActive(false);

                                camAnim.enabled = false;

                                LevelManager.CurrentManager.SetBackgroundColor(progressedMap.biomeType);
                                LevelManager.CurrentManager.LoadLevel(progressedMap, movesCount);
                            }
                        });
                    }

                    playBtn.OnClick.RemoveAllListeners();
                    playBtn.OnClick.AddListener(s =>
                    {
                        SaveLoadManager.ClearSave(deserializedMap);

                        StartCoroutine(Coroutine());

                        IEnumerator Coroutine()
                        {
                            camAnim.SetInteger("view", LEVEL);
                            camAnim.SetTrigger("switch");

                            yield return(new WaitForSeconds(0.5f));

                            if (spawnModule2ButtonsCor != null)
                            {
                                StopCoroutine(spawnModule2ButtonsCor);
                                spawnModule2ButtonsCor = null;
                            }

                            foreach (GameObject o in spawnedMapButtons)
                            {
                                Destroy(o);
                            }

                            spawnedMapButtons.Clear();

                            module2.SetActive(false);
                            module2Info.SetActive(false);

                            camAnim.enabled = false;

                            LevelManager.CurrentManager.SetBackgroundColor(deserializedMap.biomeType);
                            LevelManager.CurrentManager.LoadLevel(deserializedMap);
                        }
                    });
                });

                number++;
                pos += new Vector3(5.3f, 0f, 0f);
                yield return(new WaitForSeconds(0.075f));
            }
        }

        spawnModule2ButtonsCor = null;
    }
示例#33
0
        public void TestAddUnsupportedFileFeatureSource()
        {
            Map m = new Map();
            Layer l = new Layer();
            l.Id = "l";
            l.Data = new DummyFileProvider();
            m.Layers.Add(l);

            string x = MapSerializer.Serialize(m);

            MapSerializer ms = new MapSerializer();

            // should fail as this not a supported provider
            m2 = ms.Deserialize(new MemoryStream(UTF8Encoding.UTF8.GetBytes((x))));
        }
示例#34
0
        public void TestFillTexturePath()
        {
            MapSerializer ms = new MapSerializer();
            Map m = ms.Deserialize("../../maps/mexico.xml");

            Assert.IsTrue(Path.IsPathRooted(m.Layers[4].Styles[0].FillTexturePath));
        }
示例#35
0
        public void TestRelativeToAbsoluteMapFilePath()
        {
            MapSerializer ms = new MapSerializer();
            Map m = ms.Deserialize("../../maps/mexico.xml");

            Assert.IsTrue(Path.IsPathRooted((m.Layers[0].Data as IFileFeatureSource).FilePath));
        }
示例#36
0
        public void TestSimpleFeatureSourceSerialization()
        {
            Map m = new Map();
            Layer l = new Layer();

            SimpleFeatureSource sfs = new SimpleFeatureSource(FeatureType.Polygon);
            Polygon p = new Polygon();

            Ring r = new Ring();
            r.Points.Add(new Point(0,0));
            r.Points.Add(new Point(0,5));
            r.Points.Add(new Point(5,5));
            r.Points.Add(new Point(5,0));
            r.Close();
            p.Rings.Add(r);

            Ring hole = new Ring();
            hole.Points.Add(new Point(1,1));
            hole.Points.Add(new Point(2,1));
            hole.Points.Add(new Point(2,2));
            hole.Points.Add(new Point(2,1));
            hole.Close();
            p.Rings.Add(hole);

            sfs.Features.Add(p);

            l.Data = sfs;
            m.Layers.Add(l);

            MapSerializer ms = new MapSerializer();
            string s = MapSerializer.Serialize(m);

            Map m2 = ms.Deserialize(new MemoryStream(UTF8Encoding.UTF8.GetBytes((s))));

            Assert.AreEqual(1, m2.Layers.Count);
            Assert.AreEqual(1, (m2.Layers[0].Data as SimpleFeatureSource).Features.Count);
            Assert.AreEqual(2, ((m2.Layers[0].Data as SimpleFeatureSource).Features[0] as Polygon).Rings.Count);
        }
示例#37
0
        public void SetUp()
        {
            MapSerializer ms = new MapSerializer();
            ms.AddDatabaseFeatureSourceType<DummyDBProvider>();
            ms.AddFileFeatureSourceType<DummyFileProvider>();

            m1 = new Map();
            m1.Extents = new Rectangle(0,0,10,10);
            m1.Height = 123;
            m1.Width = 321;
            m1.Projection = "+init=epsg:4326";
            m1.BackgroundColor = Color.FromArgb(4,3,2,1);

            Layer l1 = new Layer();
            l1.Id = "l1";
            DummyDBProvider db = new DummyDBProvider();
            l1.Data = db;
            l1.Projection = "+init=epsg:2236";
            l1.Theme = ThemeType.NumericRange;
            l1.ThemeField = "MyField";
            l1.LabelField = "MyLabelField";
            l1.Visible = false;
            l1.MinScale = 99;
            l1.MaxScale = 88;
            l1.AllowDuplicateLabels = false;

            db.ConnectionString = "MyConnString";
            db.ForcedFeatureType = FeatureType.Polyline;
            db.ForcedSpatialType = SpatialType.Geographic;
            db.ForcedSrid = 1234;
            db.TableName = "MyTable";
            db.ForcedGeometryColumn = "MyGeoColumn";

            Style s1 = new Style();
            s1.Id = "MyStyle";
            s1.LineColor = Color.FromArgb(255, 180, 34, 34);
            s1.LineStyle = LineStyle.Dashed;
            s1.LineWidth = 23;
            s1.PointSize = 4;
            s1.PointSymbol = PointSymbolType.Image;
            s1.PointSymbolShape = PointSymbolShapeType.Square;
            s1.UniqueThemeValue = "MyValue";
            s1.MaxRangeThemeValue = 30000;
            s1.MinRangeThemeValue = 4;
            s1.FillStyle = FillStyle.None;
            s1.ShowLabels = true;
            s1.LabelColor = Color.FromArgb(0,1,2,3);
            s1.LabelFont = LabelFont.SansSerif;
            s1.LabelFontEmSize = 1234;
            s1.LabelPosition = LabelPosition.BottomLeft;
            s1.LabelPixelOffset = 42;
            s1.LabelDecoration = LabelDecoration.Outline;
            s1.LabelOutlineColor = Color.FromArgb(9,9,9,9);
            s1.LabelOutlineWidth = 99f;
            s1.LabelAngle = 45f;
            s1.LabelCustomFont = "font";

            s1.MinScale = 0;
            s1.MaxScale = 1;
            s1.LabelMinScale = 10;
            s1.LabelMaxScale = 100;
            s1.DrawPointSymbolOnPolyLine = true;
            s1.CalculateLabelAngleForPolyLine = false;
            s1.FillTexturePath = "../../../Cumberland.Tests/maps/images/swamps.png";

            s1.Simplify = true;
            s1.SimplifyTolerance = 99;

            s1.UniqueElseFlag = true;

            l1.Styles.Add(s1);

            m1.Layers.Add(l1);

            Layer l2 = new Layer();
            l2.Id = "l2";
            l2.Data = new DummyFileProvider();
            m1.Layers.Add(l2);

            string s = MapSerializer.Serialize(m1);

            m2 = ms.Deserialize(new MemoryStream(UTF8Encoding.UTF8.GetBytes((s))));
        }
示例#38
0
文件: Main.cs 项目: agrath/cumberland
        public static void Main(string[] args)
        {
            #region check arguments

            Rectangle worldExtents = null;
            Rectangle extents = new Rectangle();
            string path = ".";
            bool showHelp = false;
            int maxZoomLevel = 19;
            int minZoomLevel = 0;
            bool onlyCount = false;
            TileConsumer consumer = TileConsumer.GoogleMaps;
            bool mxzlChanged = false;
            bool mnzlChanged = false;
            int bleedInPixels = 0;
            bool showVersion = false;

            OptionSet options = new OptionSet();
            options.Add("e|extents=",
                        "comma-delimited extents for clipping tile generation (e.g. -180,-90,180,90).  Overrides the map file.  (Must be in map's coordinate system)",
                        delegate (string v) { extents = ParseExtents(v); });
            options.Add("h|help",  "show this message and exit",
                        delegate (string v) { showHelp = v!= null; });
            options.Add("o|output=",
                        "the path of the where to create.  Defaults to current directory",
                        delegate (string v) { path = v; });
            options.Add("x|maxzoom=",
                        "the maximum zoom level",
                        delegate (string v) { maxZoomLevel = int.Parse(v, CultureInfo.InvariantCulture); mxzlChanged = true; });
            options.Add("n|minzoom=",
                        "the minimum zoom level",
                        delegate (string v) { minZoomLevel = int.Parse(v, CultureInfo.InvariantCulture); mnzlChanged = true; });
            options.Add("t|test",
                        "Test - only calculate the total and return",
                        delegate (string v) { onlyCount = v != null; });
            options.Add("c|consumer=",
                        "The consumer.  Valid values are 'googlemaps', 'tms', and 've'.",
                        delegate (string v)
                        {
                if (v == "googlemaps")
                {
                    consumer = TileConsumer.GoogleMaps;
                }
                else if (v == "tms")
                {
                    consumer = TileConsumer.TileMapService;
                }
                else if (v == "ve")
                {
                    consumer = TileConsumer.VirtualEarth;
                }
                else
                {
                    System.Console.WriteLine("Error: Unknown consumer.");
                    ShowHelp(options);
                    return;
                }
            });
            options.Add("w|worldextents=",
                        "comma-delimited extents for defining world (e.g. -180,-90,180,90). Valid only for TMS",
                        delegate (string v) { worldExtents = ParseExtents(v); } );
            options.Add("b|bleed=",
                        "the bleed in pixels for tiles (useful for catching overrunning symbols/labels from other tiles",
                        delegate (string v) { bleedInPixels = int.Parse(v, CultureInfo.InvariantCulture); });
            options.Add("v|version",
                        "shows the version and exits",
                        delegate (string v) { showVersion = v != null; });

            List<string> rest = options.Parse(args);

            if (showVersion)
            {
                System.Console.WriteLine("Version " +
                                         System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString());
                return;
            }

            if (showHelp)
            {
                ShowHelp(options);
                return;
            }

            if (rest.Count == 0)
            {
                System.Console.WriteLine("No map provided");
                ShowHelp(options);
                return;
            }

            if (!File.Exists(rest[0]))
            {
                System.Console.WriteLine("Map xml file not found");
                ShowHelp(options);
                return;
            }

            if ((consumer == TileConsumer.GoogleMaps || consumer == TileConsumer.VirtualEarth) &&
                worldExtents != null)
            {
                System.Console.WriteLine("Error: cannot set world extents for this consumer");
                ShowHelp(options);
                return;
            }

            #endregion

            #region get map

            // search in the local directory for espg files
            // so Windows ppl don't have to have it installed
            ProjFourWrapper.CustomSearchPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

            MapSerializer ms = new MapSerializer();
            ms.AddDatabaseFeatureSourceType<Cumberland.Data.PostGIS.PostGISFeatureSource>();
            ms.AddDatabaseFeatureSourceType<Cumberland.Data.SqlServer.SqlServerFeatureSource>();

            Map map = ms.Deserialize(rest[0]);

            // use map extents as clipping range if not provided
            if (extents.IsEmpty && !map.Extents.IsEmpty)
            {
                extents = map.Extents;
            }

            // if map has a projection, reproject clipping area
            if ((consumer == TileConsumer.GoogleMaps || consumer == TileConsumer.VirtualEarth) &&
                !extents.IsEmpty)
            {
                if (!string.IsNullOrEmpty(map.Projection))
                {
                    using (ProjFourWrapper src = new ProjFourWrapper(map.Projection))
                    {
                        using (ProjFourWrapper dst = new ProjFourWrapper(ProjFourWrapper.SphericalMercatorProjection))
                        {
                            extents = new Rectangle(src.Transform(dst, extents.Min),
                                                    src.Transform(dst, extents.Max));
                        }
                    }
                }
                else
                {
                    System.Console.WriteLine(@"Warning: Your map doesn't have a projection.
                                            Unless your data is in spherical mercator,
                                            you will not get correct tiles");
                }
            }

            if (consumer == TileConsumer.VirtualEarth)
            {
                if (!mnzlChanged) minZoomLevel = 1;
                if (!mxzlChanged) maxZoomLevel = 23;
            }

            #endregion

            #region calculate total # of tiles

            TileProvider tp;
            if (worldExtents == null)
            {
                tp = new TileProvider(consumer);
            }
            else
            {
                tp = new TileProvider(consumer, worldExtents);
            }
            tp.DrawExceptionsOnTile = false;
            tp.BleedInPixels = bleedInPixels;

            // calculate total number of tiles
            long totalCount = 0;
            for (int ii = minZoomLevel; ii <= maxZoomLevel; ii++)
            {
                //System.Console.WriteLine(tp.ClipRectangleAtZoomLevel(extents, ii).ToString());
                if (extents.IsEmpty)
                {
                    int across = tp.CalculateNumberOfTilesAcross(ii);
                    totalCount += (Convert.ToInt64(across)*Convert.ToInt64(across));
                }
                else
                {
                    System.Drawing.Rectangle r = tp.ClipRectangleAtZoomLevel(extents, ii);
                    totalCount += Convert.ToInt64(r.Width+1) * Convert.ToInt64(r.Height+1);
                }
            }

            string info = string.Format("0{0} of {1}", new string(' ', totalCount.ToString().Length-1),totalCount);
            System.Console.Write(info);

            if (onlyCount)
            {
                return;
            }

            #endregion

            #region render tiles

            Directory.CreateDirectory(path);

            #region Handle TMS xml file

            XmlWriter writer = null;

            if (consumer == TileConsumer.TileMapService)
            {
                writer = new XmlTextWriter(Path.Combine(path, "tilemapresource.xml"),
                                                 Encoding.UTF8);
                writer.WriteStartDocument();

                writer.WriteStartElement("TileMap");
                writer.WriteAttributeString("version", "1.0.0");
                writer.WriteAttributeString("tilemapservice", "http://tms.osgeo.org/1.0.0");

                writer.WriteElementString("Title", string.Empty);
                writer.WriteElementString("Abstract", string.Empty);

                int epsg;
                if (ProjFourWrapper.TryParseEpsg(map.Projection, out epsg))
                {
                    writer.WriteElementString("SRS", "EPSG:" + epsg.ToString());
                }
                else
                {
                    writer.WriteElementString("SRS", string.Empty);

                    System.Console.WriteLine("Warning: could not parse epsg code from map projection.  SRS element not set");
                }

                writer.WriteStartElement("BoundingBox");
                writer.WriteAttributeString("minx", extents.Min.X.ToString());
                writer.WriteAttributeString("miny", extents.Min.Y.ToString());
                writer.WriteAttributeString("maxx", extents.Max.X.ToString());
                writer.WriteAttributeString("maxy", extents.Max.Y.ToString());
                writer.WriteEndElement(); // BoundingBox

                writer.WriteStartElement("Origin");
                writer.WriteAttributeString("x", extents.Center.X.ToString());
                writer.WriteAttributeString("y", extents.Center.Y.ToString());
                writer.WriteEndElement(); // Origin

                writer.WriteStartElement("TileFormat");
                writer.WriteAttributeString("width", "256");
                writer.WriteAttributeString("height", "256");
                writer.WriteAttributeString("mime-type", "image/png");
                writer.WriteAttributeString("extension", "png");
                writer.WriteEndElement(); // TileFormat

                writer.WriteStartElement("TileSets");
                writer.WriteAttributeString("profile", "local");
            }

            #endregion

            long current = 0;
            for (int ii = minZoomLevel; ii <= maxZoomLevel; ii++)
            {
                string tilepath = Path.Combine(path, ii.ToString());

                if (consumer == TileConsumer.VirtualEarth)
                {
                    tilepath = path;
                }

                Directory.CreateDirectory(tilepath);

                System.Drawing.Rectangle r;
                if (extents.IsEmpty)
                {
                    int across = tp.CalculateNumberOfTilesAcross(ii);
                    r = new System.Drawing.Rectangle(0, 0, across, across);
                }
                else
                {
                    r = tp.ClipRectangleAtZoomLevel(extents, ii);
                }

                if (consumer == TileConsumer.TileMapService)
                {
                    writer.WriteStartElement("TileSet");
                    writer.WriteAttributeString("href", tilepath);
                    writer.WriteAttributeString("units-per-pixel", tp.CalculateMapUnitsPerPixel(ii).ToString());
                    writer.WriteAttributeString("order", ii.ToString());
                    writer.WriteEndElement(); // TileSet
                }

                for (int x = r.Left; x <= (r.Left+r.Width); x++)
                {
                    string xtilepath = Path.Combine(tilepath, x.ToString());

                    if (consumer == TileConsumer.VirtualEarth)
                    {
                        xtilepath = path;
                    }

                    Directory.CreateDirectory(xtilepath);

                    for (int y = r.Top; y <= (r.Top+r.Height); y++)
                    {
                        current++;

                        // render tile and save to file
                        Bitmap b = tp.DrawTile(map, x, y, ii);
                        string tileFile = string.Format("{0}{1}{2}.png",
                                      xtilepath,
                                      Path.DirectorySeparatorChar,
                                      (consumer == TileConsumer.VirtualEarth ? tp.ConvertTileToQuadKey(x,y,ii) : y.ToString()));
                        b.Save(tileFile ,ImageFormat.Png);

                        // update count in console
                        Console.SetCursorPosition(0, Console.CursorTop);
                        Console.Write(current.ToString());
                        Console.SetCursorPosition(info.Length+1, Console.CursorTop);
                    }
                }
            }

            if (consumer == TileConsumer.TileMapService)
            {
                writer.WriteEndElement(); // TileSets
                writer.WriteEndElement(); // TileMap
                writer.Close();
            }

            #endregion

            System.Console.WriteLine("Finished!");
        }
示例#39
0
文件: Main.cs 项目: agrath/cumberland
        public static void Main(string[] args)
        {
            IMapDrawer drawer = new MapDrawer();

            bool showHelp = false;
            string path = "out.png";
            int w = -1;
            int h = -1;
            Rectangle extents = new Rectangle();
            bool showVersion = false;

            OptionSet options = new OptionSet();
            options.Add("e|extents=",
                        "comma-delimited extents (e.g. -180,-90,180,90) ",
                        delegate (string v) { extents = ParseExtents(v); });
            options.Add("h|help",  "show this message and exit",
                        delegate (string v) { showHelp = v!= null; });
            options.Add("o|output=",
                        "the path of the PNG image to create",
                        delegate (string v) { path = v; });
            options.Add("w|width=",
                        "the width of the image in pixels",
                        delegate (string v) { w = int.Parse(v); });
            options.Add("t|height=",
                        "the height of the image in pixels",
                        delegate (string v) { h = int.Parse(v); });
            options.Add("v|version",
                        "shows the version and exits",
                        delegate (string v) { showVersion = v != null; });

            List<string> rest = options.Parse(args);

            if (showVersion)
            {
                System.Console.WriteLine("Version " +
                                         System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString());
                return;
            }

            if (showHelp)
            {
                ShowHelp(options);
                return;
            }

            if (rest.Count == 0)
            {
                System.Console.WriteLine("No map specified");
                ShowHelp(options);
                return;
            }

            // search in the local directory for espg files
            // so Windows ppl don't have to have it installed
            ProjFourWrapper.CustomSearchPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

            MapSerializer ms = new MapSerializer();
            ms.AddDatabaseFeatureSourceType<PostGISFeatureSource>();
            ms.AddDatabaseFeatureSourceType<SqlServerFeatureSource>();

            Map map = ms.Deserialize(rest[0]);
            if (w > 0) map.Width = w;
            if (h > 0) map.Height = h;
            if (!extents.IsEmpty) map.Extents = extents;

            System.Console.WriteLine(map.Layers.Count + " Layer(s) loaded");

            Bitmap b = drawer.Draw(map);

            if (System.IO.Path.GetExtension(path) != ".png")
            {
                path += ".png";
            }

            b.Save(path, ImageFormat.Png);
        }
示例#40
0
        private void LoadMap(string filename, MapSerializer.Format format)
        {
            if (String.IsNullOrWhiteSpace(filename) || !File.Exists(filename))
            {
                if (File.Exists(filename + ".xml") && format == MapSerializer.Format.NormalXml)
                {
                    LoadMap(filename + ".xml", MapSerializer.Format.NormalXml);
                    return;
                }

                if(File.Exists(filename + ".ini") && format == MapSerializer.Format.SimpleTrainer)
                {
                    LoadMap(filename + ".ini", MapSerializer.Format.SimpleTrainer);
                    return;
                }

                if (File.Exists(filename + ".xml") && format == MapSerializer.Format.Menyoo)
                {
                    LoadMap(filename + ".xml", MapSerializer.Format.Menyoo);
                    return;
                }

                if (File.Exists(filename + ".SP00N") && format == MapSerializer.Format.SpoonerLegacy)
                {
                    LoadMap(filename + ".SP00N", MapSerializer.Format.SpoonerLegacy);
                    return;
                }

                UI.Notify("~b~~h~Map Editor~h~~w~~n~" + Translation.Translate("The filename was empty or the file does not exist!"));
                return;
            }
            var handles = new List<int>();
            var des = new MapSerializer();
            try
            {
                var map2Load = des.Deserialize(filename, format);
                if (map2Load == null) return;

                if (map2Load.Metadata != null && map2Load.Metadata.LoadingPoint.HasValue)
                {
                    Game.Player.Character.Position = map2Load.Metadata.LoadingPoint.Value;
                    Wait(500);
                }

                foreach (MapObject o in map2Load.Objects)
                {
                    if(o == null) continue;
                    _loadedEntities++;
                    switch (o.Type)
                    {
                        case ObjectTypes.Prop:
                            var newProp = PropStreamer.CreateProp(ObjectPreview.LoadObject(o.Hash), o.Position, o.Rotation,
                                o.Dynamic && !o.Door, o.Quaternion == new Quaternion() {X = 0, Y = 0, Z = 0, W = 0} ? null : o.Quaternion,
                                drawDistance: _settings.DrawDistance);
                            AddItemToEntityMenu(newProp);

                            if (o.Door)
                            {
                                PropStreamer.Doors.Add(newProp.Handle);
                                newProp.FreezePosition = false;
                            }

                            if (o.Id != null && !PropStreamer.Identifications.ContainsKey(newProp.Handle))
                            {
                                PropStreamer.Identifications.Add(newProp.Handle, o.Id);
                                handles.Add(newProp.Handle);
                            }
                            break;
                        case ObjectTypes.Vehicle:
                            Vehicle tmpVeh;
                            AddItemToEntityMenu(tmpVeh = PropStreamer.CreateVehicle(ObjectPreview.LoadObject(o.Hash), o.Position, o.Rotation.Z, o.Dynamic, drawDistance: _settings.DrawDistance));
                            tmpVeh.PrimaryColor = (VehicleColor) o.PrimaryColor;
                            tmpVeh.SecondaryColor = (VehicleColor)o.SecondaryColor;
                            if (o.Id != null && !PropStreamer.Identifications.ContainsKey(tmpVeh.Handle))
                            {
                                PropStreamer.Identifications.Add(tmpVeh.Handle, o.Id);
                                handles.Add(tmpVeh.Handle);
                            }
                            if (o.SirensActive)
                            {
                                PropStreamer.ActiveSirens.Add(tmpVeh.Handle);
                                tmpVeh.SirenActive = true;
                            }
                            break;
                        case ObjectTypes.Ped:
                            Ped pedid;
                            AddItemToEntityMenu(pedid = PropStreamer.CreatePed(ObjectPreview.LoadObject(o.Hash), o.Position - new Vector3(0f, 0f, 1f), o.Rotation.Z, o.Dynamic, drawDistance: _settings.DrawDistance));
                            if((o.Action == null || o.Action == "None") && !PropStreamer.ActiveScenarios.ContainsKey(pedid.Handle))
                                PropStreamer.ActiveScenarios.Add(pedid.Handle, "None");
                            else if (o.Action != null && o.Action != "None" && !PropStreamer.ActiveScenarios.ContainsKey(pedid.Handle))
                            {
                                PropStreamer.ActiveScenarios.Add(pedid.Handle, o.Action);
                                if (o.Action == "Any" || o.Action == "Any - Walk")
                                    Function.Call(Hash.TASK_USE_NEAREST_SCENARIO_TO_COORD, pedid.Handle, pedid.Position.X, pedid.Position.Y,
                                        pedid.Position.Z, 100f, -1);
                                else if(o.Action == "Any - Warp")
                                    Function.Call(Hash.TASK_USE_NEAREST_SCENARIO_TO_COORD_WARP, pedid.Handle, pedid.Position.X, pedid.Position.Y,
                                            pedid.Position.Z, 100f, -1);
                                else if (o.Action == "Wander")
                                    pedid.Task.WanderAround();
                                else
                                {
                                    Function.Call(Hash.TASK_START_SCENARIO_IN_PLACE, pedid.Handle, ObjectDatabase.ScrenarioDatabase[o.Action], 0, 0);
                                }
                            }

                            if (o.Id != null && !PropStreamer.Identifications.ContainsKey(pedid.Handle))
                            {
                                PropStreamer.Identifications.Add(pedid.Handle, o.Id);
                                handles.Add(pedid.Handle);
                            }

                            if (o.Relationship == null)
                                PropStreamer.ActiveRelationships.Add(pedid.Handle, DefaultRelationship.ToString());
                            else
                            {
                                PropStreamer.ActiveRelationships.Add(pedid.Handle, o.Relationship);
                                if (o.Relationship != DefaultRelationship.ToString())
                                {
                                    ObjectDatabase.SetPedRelationshipGroup(pedid, o.Relationship);
                                }
                            }

                            if (o.Weapon == null)
                                PropStreamer.ActiveWeapons.Add(pedid.Handle, WeaponHash.Unarmed);
                            else
                            {
                                PropStreamer.ActiveWeapons.Add(pedid.Handle, o.Weapon.Value);
                                if (o.Weapon != WeaponHash.Unarmed)
                                {
                                    pedid.Weapons.Give(o.Weapon.Value, 999, true, true);
                                }
                            }
                            break;
                        case ObjectTypes.Pickup:
                            var newPickup = PropStreamer.CreatePickup(o.Hash, o.Position, o.Rotation.Z, o.Amount, o.Dynamic, o.Quaternion);
                            newPickup.Timeout = o.RespawnTimer;
                            AddItemToEntityMenu(newPickup);
                            if (o.Id != null && !PropStreamer.Identifications.ContainsKey(newPickup.ObjectHandle))
                            {
                                PropStreamer.Identifications.Add(newPickup.ObjectHandle, o.Id);
                                handles.Add(newPickup.ObjectHandle);
                            }
                            break;
                    }
                }
                foreach (MapObject o in map2Load.RemoveFromWorld)
                {
                    if(o == null) continue;
                    PropStreamer.RemovedObjects.Add(o);
                    Prop returnedProp = Function.Call<Prop>(Hash.GET_CLOSEST_OBJECT_OF_TYPE, o.Position.X, o.Position.Y,
                        o.Position.Z, 1f, o.Hash, 0);
                    if (returnedProp == null || returnedProp.Handle == 0) continue;
                    MapObject tmpObj = new MapObject()
                    {
                        Hash = returnedProp.Model.Hash,
                        Position = returnedProp.Position,
                        Rotation = returnedProp.Rotation,
                        Quaternion = Quaternion.GetEntityQuaternion(returnedProp),
                        Type = ObjectTypes.Prop,
                        Id = _mapObjCounter.ToString(),
                    };
                    _mapObjCounter++;
                    AddItemToEntityMenu(tmpObj);
                    returnedProp.Delete();
                }
                foreach (Marker marker in map2Load.Markers)
                {
                    if(marker == null) continue;
                    _markerCounter++;
                    marker.Id = _markerCounter;
                    PropStreamer.Markers.Add(marker);
                    AddItemToEntityMenu(marker);
                }

                if (_settings.LoadScripts && format == MapSerializer.Format.NormalXml &&
                    File.Exists(new FileInfo(filename).Directory.FullName + "\\" + Path.GetFileNameWithoutExtension(filename) + ".js"))
                {
                    JavascriptHook.StartScript(File.ReadAllText(new FileInfo(filename).Directory.FullName + "\\" + Path.GetFileNameWithoutExtension(filename) + ".js"), handles);
                }

                if (map2Load.Metadata != null && map2Load.Metadata.TeleportPoint.HasValue)
                {
                    Game.Player.Character.Position = map2Load.Metadata.TeleportPoint.Value;
                }

                PropStreamer.CurrentMapMetadata = map2Load.Metadata ?? new MapMetadata();

                PropStreamer.CurrentMapMetadata.Filename = filename;

                UI.Notify("~b~~h~Map Editor~h~~w~~n~" + Translation.Translate("Loaded map") + " ~h~" + filename + "~h~.");
            }
            catch (Exception e)
            {
                UI.Notify("~r~~h~Map Editor~h~~w~~n~" + Translation.Translate("Map failed to load, see error below."));
                UI.Notify(e.Message);

                File.AppendAllText("scripts\\MapEditor.log", DateTime.Now + " MAP FAILED TO LOAD:\r\n" + e.ToString() + "\r\n");
            }
        }
示例#41
0
        private void SaveMap(string filename, MapSerializer.Format format)
        {
            if (String.IsNullOrWhiteSpace(filename))
            {
                UI.Notify("~b~~h~Map Editor~h~~w~~n~" + Translation.Translate("The filename was empty!"));
                return;
            }

            var ser = new MapSerializer();
            var tmpmap = new Map();
            try
            {
                tmpmap.Objects.AddRange(format == MapSerializer.Format.SimpleTrainer
                    ? PropStreamer.GetAllEntities().Where(p => p.Type == ObjectTypes.Prop)
                    : PropStreamer.GetAllEntities());
                tmpmap.RemoveFromWorld.AddRange(PropStreamer.RemovedObjects);
                tmpmap.Markers.AddRange(PropStreamer.Markers);
                tmpmap.Metadata = PropStreamer.CurrentMapMetadata;

                ser.Serialize(filename, tmpmap, format);
                UI.Notify("~b~~h~Map Editor~h~~w~~n~" + Translation.Translate("Saved current map as") + " ~h~" + filename + "~h~.");
                _changesMade = 0;
            }
            catch (Exception e)
            {
                UI.Notify("~r~~h~Map Editor~h~~w~~n~" + Translation.Translate("Map failed to save, see error below."));
                UI.Notify(e.Message);
            }
        }