コード例 #1
0
        private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
        {
            string worldName = string.IsNullOrEmpty(WorldName.Text) ? _currentItem.Name : WorldName.Text;

            var worldPath  = Path.Combine(TorchBase.Instance.Config.InstancePath, "Saves", worldName);
            var checkpoint = _currentItem.Checkpoint;

            if (Directory.Exists(worldPath))
            {
                MessageBox.Show("World already exists with that name.");
                return;
            }
            Directory.CreateDirectory(worldPath);
            foreach (var file in Directory.EnumerateFiles(_currentItem.Path, "*", SearchOption.AllDirectories))
            {
                File.Copy(file, Path.Combine(worldPath, file.Replace($"{_currentItem.Path}\\", "")));
            }

            checkpoint.SessionName = worldName;

            MyLocalCache.SaveCheckpoint(checkpoint, worldPath);


            _instanceManager.SelectWorld(worldPath, false);
            _instanceManager.ImportSelectedWorldConfig();
            Close();
        }
コード例 #2
0
        public WorldGeneratorDialog(InstanceManager instanceManager)
        {
            _instanceManager = instanceManager;
            InitializeComponent();
            _loadLocalization();
            var scenarios = MyLocalCache.GetAvailableWorldInfos(Path.Combine(MyFileSystem.ContentPath, "CustomWorlds"));

            foreach (var tup in scenarios)
            {
                string      directory     = tup.Item1;
                MyWorldInfo info          = tup.Item2;
                string      localizedName = MyTexts.GetString(MyStringId.GetOrCompute(info.SessionName));
                var         checkpoint    = MyLocalCache.LoadCheckpoint(directory, out _);
                checkpoint.OnlineMode = MyOnlineModeEnum.PUBLIC;
                _checkpoints.Add(new PremadeCheckpointItem {
                    Name = localizedName, Icon = Path.Combine(directory, "thumb.jpg"), Path = directory, Checkpoint = checkpoint
                });
            }

            /*
             * var premadeCheckpoints = Directory.EnumerateDirectories(Path.Combine("Content", "CustomWorlds"));
             * foreach (var path in premadeCheckpoints)
             * {
             *  var thumbPath = Path.GetFullPath(Directory.EnumerateFiles(path).First(x => x.Contains("thumb")));
             *
             *  _checkpoints.Add(new PremadeCheckpointItem
             *  {
             *      Path = path,
             *      Icon = thumbPath,
             *      Name = Path.GetFileName(path)
             *  });
             * }*/
            PremadeCheckpoints.ItemsSource = _checkpoints;
        }
コード例 #3
0
        public void SaveConfig()
        {
            _viewModel.Save(_configPath);
            Log.Info("Saved DS config.");
            try
            {
                MyObjectBuilderSerializer.DeserializeXML(Path.Combine(Config.LoadWorld, "Sandbox.sbc"), out MyObjectBuilder_Checkpoint checkpoint, out ulong sizeInBytes);
                if (checkpoint == null)
                {
                    Log.Error($"Failed to load {Config.LoadWorld}, checkpoint null ({sizeInBytes} bytes, instance {TorchBase.Instance.Config.InstancePath})");
                    return;
                }
                checkpoint.Settings = Config.SessionSettings;
                checkpoint.Mods.Clear();
                foreach (var modId in Config.Mods)
                {
                    checkpoint.Mods.Add(new MyObjectBuilder_Checkpoint.ModItem(modId));
                }

                MyLocalCache.SaveCheckpoint(checkpoint, Config.LoadWorld);
                Log.Info("Saved world config.");
            }
            catch (Exception e)
            {
                Log.Error("Failed to write sandbox config, changes will not appear on server");
                Log.Error(e);
            }
        }
コード例 #4
0
        public MyGuiScreenMainMenu(bool pauseGame)
            : base(Vector2.Zero, null, null)
        {
            if (MyGuiScreenGamePlay.Static == null)
            {
                m_closeOnEsc = false;
            }
            else
            {
                m_pauseGame = pauseGame;
                if (m_pauseGame && MySandboxGame.IsPaused == false)
                {
                    MySandboxGame.UserPauseToggle();
                }
            }

            //if (MyGuiScreenGamePlay.Static.GetGameType() == MyGuiScreenGamePlayType.MAIN_MENU) m_closeOnEsc = false;
            //if (MyGuiScreenGamePlay.Static.IsPausable()) MySandboxGame.SwitchPause();

            //Because then it is visible under credits, help, etc..
            m_drawEvenWithoutFocus = false;

            if (MyGuiScreenGamePlay.Static == null)
            {
                //We dont want to load last session if we end up game in main menu
                MyLocalCache.SaveLastSessionInfo(null);
            }

            try
            {
                m_newsSerializer = new XmlSerializer(typeof(MyNews));
            }
            catch { };
        }
コード例 #5
0
        private static void SaveRespawnShip(MyPlayer player)
        {
            if (!MySession.Static.Settings.RespawnShipDelete)
            {
                return;
            }

            System.Diagnostics.Debug.Assert(player.RespawnShip != null, "Saving a null respawn ship");
            if (player.RespawnShip == null)
            {
                return;
            }

            MyCubeGrid oldHome;

            if (MyEntities.TryGetEntityById <MyCubeGrid>(player.RespawnShip[0], out oldHome))
            {
                ulong  sizeInBytes = 0;
                string sessionPath = MySession.Static.CurrentPath;
                Console.WriteLine(sessionPath);
                string fileName = "RS_" + player.Client.SteamUserId + ".sbr";
                ParallelTasks.Parallel.Start(delegate()
                {
                    MyLocalCache.SaveRespawnShip((MyObjectBuilder_CubeGrid)oldHome.GetObjectBuilder(), sessionPath, fileName, out sizeInBytes);
                });
            }
        }
コード例 #6
0
ファイル: VRageGame.cs プロジェクト: kingpeti/Torch
#pragma warning restore 649

        private void DoLoadSession(string sessionPath)
        {
            if (!Path.IsPathRooted(sessionPath))
            {
                sessionPath = Path.Combine(MyFileSystem.SavesPath, sessionPath);
            }

            if (!Sandbox.Engine.Platform.Game.IsDedicated)
            {
                MySessionLoader.LoadSingleplayerSession(sessionPath);
                return;
            }
            MyObjectBuilder_Checkpoint checkpoint = MyLocalCache.LoadCheckpoint(sessionPath, out ulong checkpointSize);

            if (MySession.IsCompatibleVersion(checkpoint))
            {
                if (MyWorkshop.DownloadWorldModsBlocking(checkpoint.Mods, null).Success)
                {
                    // MySpaceAnalytics.Instance.SetEntry(MyGameEntryEnum.Load);
                    MySession.Load(sessionPath, checkpoint, checkpointSize);
                    _hostServerForSession(MySession.Static, MyMultiplayer.Static);
                }
                else
                {
                    MyLog.Default.WriteLineAndConsole("Unable to download mods");
                }
            }
            else
            {
                MyLog.Default.WriteLineAndConsole(MyTexts.Get(MyCommonTexts.DialogTextIncompatibleWorldVersion)
                                                  .ToString());
            }
        }
コード例 #7
0
        private void endActionLoadSaves(IMyAsyncResult result, MyGuiScreenProgressAsync screen)
        {
            screen.CloseScreen();

            var selectedRow = m_worldsTable.SelectedRow;
            var world       = (MySteamWorkshop.SubscribedItem)selectedRow.UserData;



            string safeName        = MyUtils.StripInvalidChars(world.Title);
            var    tempSessionPath = MyLocalCache.GetSessionSavesPath(safeName, false, false);

            if (Directory.Exists(tempSessionPath))
            {
                OverwriteWorldDialog();
            }
            else
            {
                MySteamWorkshop.CreateWorldInstanceAsync(world, MySteamWorkshop.MyWorkshopPathInfo.CreateWorldInfo(), false, delegate(bool success, string sessionPath)
                {
                    if (success)
                    {
                        OnSuccess(sessionPath);
                    }
                });
            }
        }
コード例 #8
0
ファイル: ConfigForm.cs プロジェクト: whztt07/SpaceEngineers
        private void startButton_Click(object sender, EventArgs e)
        {
            if (m_selectedSessionSettings == null)
            {
                return;
            }

            if (MyFakes.ENABLE_BATTLE_SYSTEM && battleButton.Checked && m_selectedSessionSettings != null)
            {
                MyBattleHelper.FillDefaultBattleServerSettings(m_selectedSessionSettings, true);
            }

            saveConfigButton_Click(sender, e);

            if (m_isService) // Service
            {
                RefreshWorldsList();
                if (startGameButton.Checked)
                {
                    // fix for new game selected - new game will be started and not last saved game instead
                    MyLocalCache.SaveLastSessionInfo("");
                }
                startService();
            }
            else // Local / Console
            {
                // When running without host process, console is not properly attached on debug (no console output)
                string[] cmdLine = Environment.GetCommandLineArgs();
                Process.Start(cmdLine[0].Replace(".vshost.exe", ".exe"), ((cmdLine.Length > 1) ? cmdLine[1] : "") + " -console -ignorelastsession");
                Close();
            }
        }
コード例 #9
0
        private void StartNewSandbox()
        {
            MyLog.Default.WriteLine("StartNewSandbox - Start");

            GetSettingsFromControls();

            // Load the checkpoint
            ulong checkpointSizeInBytes;
            var   sesionPath = m_scenarioTypesGroup.SelectedButton.UserData as string;

            var checkpoint = MyLocalCache.LoadCheckpoint(sesionPath, out checkpointSizeInBytes);

            if (checkpoint == null)
            {
                return;
            }

            GetSettingsFromControls();
            checkpoint.Settings    = m_settings;
            checkpoint.SessionName = m_nameTextbox.Text;
            checkpoint.Password    = GetPassword();
            checkpoint.Description = GetDescription();
            checkpoint.Mods        = m_mods;

            SetupWorldGeneratorSettings(checkpoint);

            MySessionLoader.LoadSingleplayerSession(
                checkpoint,
                sesionPath,
                checkpointSizeInBytes,
                () =>
            {
                MySession.Static.Save(Path.Combine(MyFileSystem.SavesPath, checkpoint.SessionName.Replace(':', '-')));
            });
        }
コード例 #10
0
ファイル: ConfigForm.cs プロジェクト: whztt07/SpaceEngineers
        private void gamesListBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (gamesListBox.SelectedIndex != -1)
            {
                ulong sizeInBytes;

                WorldItem worldItem = (WorldItem)gamesListBox.Items[gamesListBox.SelectedIndex];
                ((MyConfigDedicated <T>)MySandboxGame.ConfigDedicated).LoadWorld = worldItem.SessionPath;

                var loadPath = worldItem.SessionPath;
                MyObjectBuilder_Checkpoint checkpoint = MyLocalCache.LoadCheckpoint(loadPath, out sizeInBytes);

                m_selectedSessionSettings = checkpoint.Settings;

                if (m_selectedSessionSettings != null && battleButton.Checked)
                {
                    MyBattleHelper.FillDefaultBattleServerSettings(m_selectedSessionSettings, true);
                }

                MySandboxGame.ConfigDedicated.Mods.Clear();
                foreach (var mod in checkpoint.Mods)
                {
                    if (mod.PublishedFileId != 0)
                    {
                        MySandboxGame.ConfigDedicated.Mods.Add(mod.PublishedFileId);
                    }
                }

                modIdsTextBox.Text = string.Join(Environment.NewLine, MySandboxGame.ConfigDedicated.Mods.ToArray());

                FillSessionSettingsItems();
            }
        }
コード例 #11
0
        private void TravelSectorLoaded(MyMwcTravelTypeEnum travelType, MyMwcVector3Int targetSector, byte[] sectorDataResponse, MyMwcObjectBuilder_Sector cachedSector)
        {
            var checkpoint = GetCheckpointBuilder(false);

            checkpoint.SectorObjectBuilder = cachedSector;

            // Overwrite current sector
            checkpoint.CurrentSector.Position = targetSector;
            UpdatePlayerPosition(travelType, ref checkpoint.PlayerObjectBuilder.ShipObjectBuilder.PositionAndOrientation.Position);

            if (sectorDataResponse != null)
            {
                checkpoint.SectorObjectBuilder = MyMwcObjectBuilder_Base.FromBytes <MyMwcObjectBuilder_Sector>(sectorDataResponse);
                MyLocalCache.Save(null, checkpoint.SectorObjectBuilder, checkpoint.CurrentSector);
            }

            // Change NEW_STORY to LOAD_CHECKPOINT, because it's necessary, travel is never new story
            MyMwcStartSessionRequestTypeEnum?sessionStart = null;

            if (MyGuiScreenGamePlay.Static != null)
            {
                sessionStart = MyGuiScreenGamePlay.Static.GetSessionType();
                if (sessionStart.HasValue && sessionStart.Value == MyMwcStartSessionRequestTypeEnum.NEW_STORY)
                {
                    sessionStart = MyMwcStartSessionRequestTypeEnum.LOAD_CHECKPOINT;
                }
            }

            MyGuiScreenGamePlay.ReloadGameplayScreen(checkpoint, sessionStart, null, null, travelType);
        }
コード例 #12
0
        public static void Load(bool displaySuccessMessage = false)
        {
            MyMwcLog.WriteLine("MySmallShipTemplates.Load() - START");
            MyMwcLog.IncreaseIndent();
            for (int i = 0; i < m_templates.Length; i++)
            {
                m_templates[i] = new List <MySmallShipTemplate>();
            }

            try
            {
                MyMwcObjectBuilder_SmallShipTemplates templatesBuilder;

                templatesBuilder = MyLocalCache.LoadGlobalData().Templates;

                foreach (var templateBuilder in templatesBuilder.SmallShipTemplates)
                {
                    m_templates[(int)templateBuilder.Builder.ShipType].Add(new MySmallShipTemplate(templateBuilder));
                }
                LoadTemplateTiers();
                MyMwcLog.WriteLine("Load state - OK");
                if (displaySuccessMessage)
                {
                    MyGuiManager.AddScreen(new MyGuiScreenMessageBox(MyMessageBoxType.MESSAGE, Localization.MyTextsWrapperEnum.TemplatesLoadSuccess, Localization.MyTextsWrapperEnum.Success, Localization.MyTextsWrapperEnum.Ok, null));
                }
            }
            catch (Exception ex)
            {
                MyMwcLog.WriteLine("Load state - ERROR");
                MyMwcLog.WriteLine(ex.Message);
                MyGuiManager.AddScreen(new MyGuiScreenMessageBox(MyMessageBoxType.ERROR, Localization.MyTextsWrapperEnum.TemplatesLoadError, Localization.MyTextsWrapperEnum.Error, Localization.MyTextsWrapperEnum.Ok, onMessageBox));
            }
            MyMwcLog.DecreaseIndent();
            MyMwcLog.WriteLine("MySmallShipTemplates.Load() - END");
        }
コード例 #13
0
        public MyServerAction Travel(MyMwcTravelTypeEnum travelType, MyMwcSectorIdentifier targetSector)
        {
            Debug.Assert(targetSector.SectorType == MyMwcSectorTypeEnum.STORY, "Travel is allowed only in story");

            TryPause();

            var sector = MyLocalCache.LoadSector(targetSector);

            if (sector == null)
            {
                var storySectorId = targetSector;
                storySectorId.UserId = null;
                sector = MyLocalCache.LoadSector(storySectorId);
            }

            if (sector != null)
            {
                TravelSectorLoaded(travelType, targetSector.Position, null, sector);
                return(null);
            }
            else // Not using server...so sector is "from generator"
            {
                TravelSectorLoaded(travelType, targetSector.Position, null, MyMwcObjectBuilder_Sector.UseGenerator());
                return(null);
            }
        }
コード例 #14
0
        private MyServerAction CheckpointLoaded(MyMwcObjectBuilder_Checkpoint checkpoint)
        {
            MyGameplayConstants.SetGameplayDifficulty(checkpoint.SessionObjectBuilder.Difficulty);

            Debug.Assert((checkpoint.CheckpointName == null && checkpoint.CurrentSector.UserId != null) || (checkpoint.CheckpointName != null && checkpoint.CurrentSector.UserId == null));

            var cacheSector = MyLocalCache.LoadSector(checkpoint.CurrentSector);

            if (cacheSector != null)
            {
                checkpoint.SectorObjectBuilder = cacheSector;
                MyGuiScreenGamePlay.ReloadGameplayScreen(checkpoint, MyMwcStartSessionRequestTypeEnum.LOAD_CHECKPOINT, MyGuiScreenGamePlayType.GAME_STORY);
                return(null);
            }
            else
            {
                // Checkpoint and sector is stored on filesystem
                throw new MyDataCorruptedException("Last checkpoint sector corrupted");

                //MyServerAction loadAction = new MyServerAction(MyTextsWrapperEnum.EnterSectorInProgressPleaseWait);
                //loadAction.BeginAction = c => c.BeginLoadSector(null, c);
                //loadAction.EndAction = (c, r) => LastCheckpointSectorLoaded(checkpoint, c.EndLoadSector(r));
                //loadAction.Start();
                //return loadAction;
            }
        }
コード例 #15
0
ファイル: ConfigForm.cs プロジェクト: whztt07/SpaceEngineers
        private void saveConfigButton_Click(object sender, EventArgs e)
        {
            SaveConfiguration();

            if (!string.IsNullOrEmpty(MySandboxGame.ConfigDedicated.LoadWorld) && !MySandboxGame.ConfigDedicated.SessionSettings.Battle)
            {
                ulong sizeInBytes;
                var   path = MySandboxGame.ConfigDedicated.LoadWorld;

                MyObjectBuilder_Checkpoint checkpoint = MyLocalCache.LoadCheckpoint(path, out sizeInBytes);

                if (!string.IsNullOrWhiteSpace(MySandboxGame.ConfigDedicated.WorldName))
                {
                    checkpoint.SessionName = MySandboxGame.ConfigDedicated.WorldName;
                }

                checkpoint.Settings = m_selectedSessionSettings;

                checkpoint.Mods.Clear();
                foreach (ulong publishedFileId in MySandboxGame.ConfigDedicated.Mods)
                {
                    checkpoint.Mods.Add(new MyObjectBuilder_Checkpoint.ModItem(publishedFileId));
                }

                MyLocalCache.SaveCheckpoint(checkpoint, path);
            }
        }
コード例 #16
0
 private void CheckContinueButtonVisibility()
 {
     if (m_continueButton != null)
     {
         MyObjectBuilder_LastSession lastSession = MyLocalCache.GetLastSession();
         bool visible = lastSession != null && (lastSession.Path == null || Directory.Exists(lastSession.Path)) && (!lastSession.IsLobby || MyGameService.LobbyDiscovery.ContinueToLobbySupported);
         m_continueButton.Visible = visible;
     }
 }
コード例 #17
0
    private void CreateMainMenu(Vector2 leftButtonPositionOrigin, out Vector2 lastButtonPosition)
    {
        base.GamepadHelpTextId     = MySpaceTexts.MainMenuScreen_Help_Screen;
        base.EnabledBackgroundFade = false;
        MyGuiControlButton myGuiControlButton = null;
        int num = (MyPerGameSettings.MultiplayerEnabled ? 7 : 6);
        MyObjectBuilder_LastSession lastSession = MyLocalCache.GetLastSession();

        if (lastSession != null && (lastSession.Path == null || MyPlatformGameSettings.GAME_SAVES_TO_CLOUD || Directory.Exists(lastSession.Path)) && (!lastSession.IsLobby || MyGameService.LobbyDiscovery.ContinueToLobbySupported))
        {
            m_continueButton = MakeButton(leftButtonPositionOrigin - num-- *MyGuiConstants.MENU_BUTTONS_POSITION_DELTA - MyGuiConstants.MENU_BUTTONS_POSITION_DELTA / 2f, MyCommonTexts.ScreenMenuButtonContinueGame, OnContinueGameClicked);
            Controls.Add(m_continueButton);
            m_elementGroup.Add(m_continueButton);
            GenerateContinueTooltip(lastSession, m_continueButton, new Vector2(0.003f, -0.0025f));
            m_continueButton.FocusChanged += FocusChangedContinue;
        }
        else
        {
            num--;
        }
        myGuiControlButton = MakeButton(leftButtonPositionOrigin - num-- *MyGuiConstants.MENU_BUTTONS_POSITION_DELTA, MyCommonTexts.ScreenMenuButtonCampaign, OnClickNewGame);
        Controls.Add(myGuiControlButton);
        m_elementGroup.Add(myGuiControlButton);
        myGuiControlButton = MakeButton(leftButtonPositionOrigin - num-- *MyGuiConstants.MENU_BUTTONS_POSITION_DELTA, MyCommonTexts.ScreenMenuButtonLoadGame, OnClickLoad);
        Controls.Add(myGuiControlButton);
        m_elementGroup.Add(myGuiControlButton);
        if (MyPerGameSettings.MultiplayerEnabled)
        {
            myGuiControlButton = MakeButton(leftButtonPositionOrigin - num-- *MyGuiConstants.MENU_BUTTONS_POSITION_DELTA, MyCommonTexts.ScreenMenuButtonJoinGame, OnJoinWorld);
            Controls.Add(myGuiControlButton);
            m_elementGroup.Add(myGuiControlButton);
        }
        myGuiControlButton = MakeButton(leftButtonPositionOrigin - num-- *MyGuiConstants.MENU_BUTTONS_POSITION_DELTA, MyCommonTexts.ScreenMenuButtonOptions, OnClickOptions);
        Controls.Add(myGuiControlButton);
        m_elementGroup.Add(myGuiControlButton);
        lastButtonPosition = myGuiControlButton.Position;

        myGuiControlButton = MakeButton(leftButtonPositionOrigin - num-- *MyGuiConstants.MENU_BUTTONS_POSITION_DELTA, MyCommonTexts.ScreenMenuButtonOptions, OnClickMenuPacks);
        Controls.Add(myGuiControlButton);
        m_elementGroup.Add(myGuiControlButton);
        lastButtonPosition = myGuiControlButton.Position;

        if (MyFakes.ENABLE_MAIN_MENU_INVENTORY_SCENE)
        {
            myGuiControlButton = MakeButton(leftButtonPositionOrigin - num-- *MyGuiConstants.MENU_BUTTONS_POSITION_DELTA, MyCommonTexts.ScreenMenuButtonInventory, OnClickInventory);
            Controls.Add(myGuiControlButton);
            m_elementGroup.Add(myGuiControlButton);
            lastButtonPosition = myGuiControlButton.Position;
        }
        if (!MyPlatformGameSettings.LIMITED_MAIN_MENU)
        {
            m_exitGameButton = MakeButton(leftButtonPositionOrigin - num-- *MyGuiConstants.MENU_BUTTONS_POSITION_DELTA, MyCommonTexts.ScreenMenuButtonExitToWindows, OnClickExitToWindows);
            Controls.Add(m_exitGameButton);
            m_elementGroup.Add(m_exitGameButton);
            lastButtonPosition = m_exitGameButton.Position;
        }
    }
コード例 #18
0
        private void NewGameSectorLoaded(MyMwcObjectBuilder_Checkpoint checkpoint, byte[] sectorData, MyMissionID missionId)
        {
            checkpoint.SectorObjectBuilder = MyMwcObjectBuilder_Base.FromBytes <MyMwcObjectBuilder_Sector>(sectorData);

            // Save sector to cache
            MyLocalCache.Save(null, checkpoint.SectorObjectBuilder, checkpoint.CurrentSector);

            checkpoint.CurrentSector.UserId = MyClientServer.LoggedPlayer.GetUserId(); //TODO: should this be send by server?
            ReloadGameplayNewGame(checkpoint, missionId);
        }
コード例 #19
0
        public static void LoadSingleplayerSession(string sessionPath)
        {
            MyLog.Default.WriteLine("LoadSession() - Start");
            MyLog.Default.WriteLine(sessionPath);

            ulong checkpointSizeInBytes;
            var   checkpoint = MyLocalCache.LoadCheckpoint(sessionPath, out checkpointSizeInBytes);

            CheckDx11AndLoad(checkpoint, sessionPath, checkpointSizeInBytes);
        }
コード例 #20
0
        public override bool Update(bool hasFocus)
        {
            if (!hasFocus)
            {
                return(base.Update(hasFocus));
            }

            if (m_childScreenLaunched && hasFocus)
            {
                CloseScreenNow();
            }

            if (m_childScreenLaunched)
            {
                return(base.Update(hasFocus));
            }

            if (MyInput.Static.IsKeyPress(MyKeys.Escape))
            {
                MyGuiScreenMainMenu.ReturnToMainMenu();
                return(base.Update(hasFocus));
            }

            switch (m_quickLaunchType)
            {
            case MyQuickLaunchType.LAST_SANDBOX:
            {
                var lastSessionPath = MyLocalCache.GetLastSessionPath();
                if (lastSessionPath != null && System.IO.Directory.Exists(lastSessionPath))
                {
                    MyGuiScreenLoadSandbox.LoadSingleplayerSession(lastSessionPath);
                }
                else
                {
                    MySandboxGame.AfterLogos();
                }
                m_childScreenLaunched = true;
            }
            break;

            case MyQuickLaunchType.NEW_SANDBOX:
            {
                MyGuiScreenStartSandbox.QuickstartSandbox(null);
                m_childScreenLaunched = true;
            }
            break;

            default:
            {
                throw new InvalidBranchException();
            }
            }

            return(base.Update(hasFocus));
        }
コード例 #21
0
        private bool TrySaveAs()
        {
            MyStringId?errorType = null;

            if (m_nameTextbox.Text.Length < 5)
            {
                errorType = MySpaceTexts.ErrorNameTooShort;
            }
            else if (m_nameTextbox.Text.Length > 30)
            {
                errorType = MySpaceTexts.ErrorNameTooLong;
            }


            if (m_existingSessionNames != null)
            {
                foreach (var name in m_existingSessionNames)
                {
                    if (name == m_nameTextbox.Text)
                    {
                        errorType = MySpaceTexts.ErrorNameAlreadyExists;
                    }
                }
            }

            if (errorType != null)
            {
                var messageBox = MyGuiSandbox.CreateMessageBox(
                    messageText: MyTexts.Get(errorType.Value),
                    messageCaption: MyTexts.Get(MySpaceTexts.MessageBoxCaptionError));
                messageBox.SkipTransition = true;
                messageBox.InstantClose   = false;
                MyGuiSandbox.AddScreen(messageBox);
                return(false);
            }

            if (m_fromMainMenu)
            {
                string name = MyUtils.StripInvalidChars(m_nameTextbox.Text);
                if (string.IsNullOrWhiteSpace(name))
                {
                    name = MyLocalCache.GetSessionSavesPath(name + MyUtils.GetRandomInt(int.MaxValue).ToString("########"), false, false);
                }
                MyAsyncSaving.Start(customName: name);
                MySession.Static.Name = m_nameTextbox.Text;
                this.CloseScreen();
                return(true);
            }

            m_copyFrom.SessionName = m_nameTextbox.Text;
            MyGuiSandbox.AddScreen(new MyGuiScreenProgressAsync(MySpaceTexts.SavingPleaseWait, null,
                                                                beginAction: () => new SaveResult(MyUtils.StripInvalidChars(m_nameTextbox.Text), m_sessionPath, m_copyFrom),
                                                                endAction: (result, screen) => { screen.CloseScreen(); this.CloseScreen(); }));
            return(true);
        }
コード例 #22
0
        public static void LoadMission(string sessionPath, bool multiplayer, MyOnlineModeEnum onlineMode, short maxPlayers,
                                       MyGameModeEnum gameMode = MyGameModeEnum.Survival)
        {
            MyLog.Default.WriteLine("LoadSession() - Start");
            MyLog.Default.WriteLine(sessionPath);

            ulong checkpointSizeInBytes;
            var   checkpoint = MyLocalCache.LoadCheckpoint(sessionPath, out checkpointSizeInBytes);

            CheckDx11AndLoad(sessionPath, multiplayer, onlineMode, maxPlayers, gameMode, checkpoint, checkpointSizeInBytes);
        }
コード例 #23
0
        private List <Tuple <string, MyWorldInfo> > GetAvailableOfficialBattlesInfos()
        {
            MySandboxGame.Log.WriteLine("Loading official castle siege worlds - START");
            var result = new List <Tuple <string, MyWorldInfo> >();

            using (MySandboxGame.Log.IndentUsing(LoggingOptions.ALL))
            {
                MyLocalCache.GetWorldInfoFromDirectory(m_officialBattlesPath, result);
            }
            MySandboxGame.Log.WriteLine("Loading official castle siege worlds - END");
            return(result);
        }
コード例 #24
0
        public static void DoReload()
        {
            GC.Collect(2, GCCollectionMode.Forced);
            MySandboxGame.Log.WriteLine(String.Format("RELOAD TEST, Menu GC: {0} B", GC.GetTotalMemory(false).ToString("##,#")));
            MySandboxGame.Log.WriteLine(String.Format("RELOAD TEST, Menu WS: {0} B", Process.GetCurrentProcess().PrivateMemorySize64.ToString("##,#")));
            var session = MyLocalCache.GetAvailableWorldInfos().OrderByDescending(s => s.Item2.LastLoadTime).FirstOrDefault();

            if (session != null)
            {
                MySessionLoader.LoadSingleplayerSession(session.Item1);
            }
        }
コード例 #25
0
        private void SandboxSectorLoaded(MyMwcVector3Int targetSector, MyMwcObjectBuilder_Checkpoint checkpoint, MyMwcObjectBuilder_Sector cachedSector, MyMwcStartSessionRequestTypeEnum startSessionType, MyMissionID?startMission)
        {
            if (checkpoint.SectorObjectBuilder == null) // Server said, use cache
            {
                checkpoint.SectorObjectBuilder = cachedSector;
            }
            else
            {
                MyLocalCache.SaveCheckpoint(checkpoint);
            }

            MyGuiScreenGamePlay.ReloadGameplayScreen(checkpoint, startSessionType, MyGuiScreenGamePlayType.GAME_SANDBOX, startMission);
        }
コード例 #26
0
        private void scenario_SelectedChanged(MyGuiControlRadioButtonGroup group)
        {
            SetDefaultName();

            // If the scenario selected is "Empty World" it will select Safe as the default environment, but only if this setting wasn't changed before
            if (!m_isHostilityChanged)
            {
                m_environment.SelectItemByKey(0);
                // It will change with the above code to true
                m_isHostilityChanged = false;
            }

            if (MyFakes.ENABLE_PLANETS)
            {
                m_worldGeneratorButton.Enabled = true;
                if (m_worldGeneratorButton.Enabled)
                {
                    if (WorldGenerator != null)
                    {
                        WorldGenerator.GetSettings(m_settings);
                        AsteroidAmount = WorldGenerator.AsteroidAmount;
                    }
                    else
                    {
                        //GK: If AsteroidAmount==0 it will cause no Asteroids spawned near player in Asteroids Scenario
                        AsteroidAmount = -1;
                    }
                }
                else if (m_settings != null)
                {
                    AsteroidAmount         = 0;
                    m_settings.EnableFlora = true;
                }
            }
            else
            {
                UpdateAsteroidAmountEnabled(true);
            }

            var   checkpointPath = group.SelectedButton.UserData as string;
            ulong size;
            var   checkpoint = MyLocalCache.LoadCheckpoint(checkpointPath, out size);

            if (checkpoint != null)
            {
                m_settings = CopySettings(checkpoint.Settings);
                SetSettingsToControls();
            }
        }
コード例 #27
0
        private void QuickstartScenario(string scenarioName)
        {
            string path        = "CustomWorlds";
            string sessionPath = Path.Combine(MyFileSystem.ContentPath, path, scenarioName);
            ulong  sizeInBytes;
            MyObjectBuilder_Checkpoint checkpoint = MyLocalCache.LoadCheckpoint(sessionPath, out sizeInBytes);

            if (checkpoint != null)
            {
                MySessionLoader.LoadSingleplayerSession(checkpoint, sessionPath, sizeInBytes, delegate
                {
                    MyAsyncSaving.Start(null, Path.Combine(MyFileSystem.SavesPath, checkpoint.SessionName.Replace(':', '-')));
                });
            }
        }
コード例 #28
0
        public MyServerAction SaveLastCheckpoint(bool createChapter = false)
        {
            if (MyMultiplayerGameplay.IsRunning && !MyMultiplayerGameplay.Static.IsHost)
            {
                return(null);
            }

            var lastChapterTime = MyLocalCache.GetLastChapterTimestamp();
            var nextChapterTime = lastChapterTime + TimeSpan.FromHours(3);

            if (MyMissions.ActiveMission == null && DateTime.Now > nextChapterTime)
            {
                createChapter = true;
            }

            MyMwcSectorIdentifier sectorId = MyGuiScreenGamePlay.Static.GetSectorIdentifier();

            if (CanBeSaved(false, sectorId, false))
            {
                var notification = new MyHudNotification.MyNotification(Localization.MyTextsWrapperEnum.SavingSectorToServer, 2500);
                MyHudNotification.AddNotification(notification);

                var checkpoint = GetCheckpointBuilder(true);
                checkpoint.CurrentSector.UserId = MyClientServer.LoggedPlayer.GetUserId(); // Saving players checkpoint

                if (MySession.PlayerShip != null && checkpoint.PlayerObjectBuilder.ShipObjectBuilder != null)
                {
                    float refilRatio = 0.5f;

                    var ship = checkpoint.PlayerObjectBuilder.ShipObjectBuilder;
                    ship.ArmorHealth     = MathHelper.Clamp(ship.ArmorHealth, refilRatio * MySession.PlayerShip.MaxArmorHealth, MySession.PlayerShip.MaxArmorHealth);
                    ship.ShipHealthRatio = MathHelper.Clamp(ship.ShipHealthRatio, refilRatio, 1.0f);
                    ship.Fuel            = MathHelper.Clamp(ship.Fuel, refilRatio * MySession.PlayerShip.MaxFuel, MySession.PlayerShip.MaxFuel);
                    ship.Oxygen          = MathHelper.Clamp(ship.Oxygen, refilRatio * MySession.PlayerShip.MaxOxygen, MySession.PlayerShip.MaxOxygen);
                    checkpoint.PlayerObjectBuilder.Health = MathHelper.Clamp(checkpoint.PlayerObjectBuilder.Health, refilRatio * 100, 100);
                }

                // Need to store actual checkpoint...because when we travel, we receive only sector, not checkpoint
                MyGuiScreenGamePlay.Static.AddEnterSectorResponse(checkpoint, null);

                Debug.Assert(checkpoint.CurrentSector.UserId != null, "Saving last checkpoint as story");
                UpdatePlayerStartDummy(checkpoint);

                MyLocalCache.SaveCheckpoint(checkpoint, createChapter);
                checkpoint.SectorObjectBuilder = null; // Don't save sector
            }
            return(null);
        }
コード例 #29
0
        public MyServerAction LoadLastCheckpoint()
        {
            TryPause();

            var checkpoint = MyLocalCache.LoadCheckpoint();

            if (checkpoint != null)
            {
                CheckpointLoaded(checkpoint);
            }
            else
            {
                throw new MyDataCorruptedException("Last checkpoint corrupted");
            }
            return(null);
        }
コード例 #30
0
        public static void LoadLastSession()
        {
            var lastSessionPath = MyLocalCache.GetLastSessionPath();

            if (!MyFileSystem.DirectoryExists(lastSessionPath))
            {
                MyGuiSandbox.AddScreen(MyGuiSandbox.CreateMessageBox(
                                           messageText: MyTexts.Get(MyCommonTexts.MessageBoxLastSessionNotFound),
                                           messageCaption: MyTexts.Get(MyCommonTexts.MessageBoxCaptionError),
                                           styleEnum: MyMessageBoxStyleEnum.Error));

                return;
            }

            LoadSingleplayerSession(lastSessionPath);
        }