Ejemplo n.º 1
0
        public async Task SaveGameAsync()
        {
            Log.Info("Saving game");
            if (MySandboxGame.IsGameReady && !MyAsyncSaving.InProgress && Sync.IsServer && !(MySession.Static.LocalCharacter?.IsDead ?? true))
            {
                using (var e = new AutoResetEvent(false))
                {
                    MyAsyncSaving.Start(() =>
                    {
                        MySector.ResetEyeAdaptation = true;
                        e.Set();
                    });

                    await Task.Run(() =>
                    {
                        if (!e.WaitOne(60000))
                        {
                            Log.Error("Save failed!");
                            Multiplayer.SendMessage("Save timed out!", author: "Error");
                        }
                    });
                }
            }
            else
            {
                Log.Error("Cannot save");
            }
        }
Ejemplo n.º 2
0
        public Task SaveGameAsync(Action <SaveGameStatus> callback)
        {
            Log.Info("Saving game");

            if (!MySandboxGame.IsGameReady)
            {
                callback?.Invoke(SaveGameStatus.GameNotReady);
            }
            else if (MyAsyncSaving.InProgress)
            {
                callback?.Invoke(SaveGameStatus.SaveInProgress);
            }
            else
            {
                var e = new AutoResetEvent(false);
                MyAsyncSaving.Start(() => e.Set());

                return(Task.Run(() =>
                {
                    callback?.Invoke(e.WaitOne(5000) ? SaveGameStatus.Success : SaveGameStatus.TimedOut);
                    e.Dispose();
                }));
            }

            return(Task.CompletedTask);
        }
Ejemplo n.º 3
0
 private void OnSaveWorldMessageBoxCallback(MyGuiScreenMessageBox.ResultEnum callbackReturn)
 {
     if (callbackReturn == MyGuiScreenMessageBox.ResultEnum.YES)
         MyAsyncSaving.Start();
     else
         CanBeHidden = true;
 }
Ejemplo n.º 4
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);
        }
Ejemplo n.º 5
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(':', '-')));
                });
            }
        }
Ejemplo n.º 6
0
        private void OnExitToMainMenuMessageBoxCallback(MyGuiScreenMessageBox.ResultEnum callbackReturn)
        {
            switch (callbackReturn)
            {
            case MyGuiScreenMessageBox.ResultEnum.YES:
                MyAudio.Static.Mute = true;
                MyAudio.Static.StopMusic();
                MyAsyncSaving.Start(callbackOnFinished : delegate() { MySandboxGame.Static.OnScreenshotTaken += UnloadAndExitAfterScreeshotWasTaken; });
                break;

            case MyGuiScreenMessageBox.ResultEnum.NO:
                MyAudio.Static.Mute = true;
                MyAudio.Static.StopMusic();
                MySessionLoader.UnloadAndExitToMenu();
                break;

            case MyGuiScreenMessageBox.ResultEnum.CANCEL:
                this.CanBeHidden = true;
                break;
            }
        }
Ejemplo n.º 7
0
        private void OnExitToMainMenuMessageBoxCallback(MyGuiScreenMessageBox.ResultEnum callbackReturn)
        {
            switch (callbackReturn)
            {
            case MyGuiScreenMessageBox.ResultEnum.YES:
                MyAudio.Static.Mute = true;
                MyAudio.Static.StopMusic();
                MyAsyncSaving.Start(callbackOnFinished : delegate() { UnloadAndExitToMenu(); });
                break;

            case MyGuiScreenMessageBox.ResultEnum.NO:
                MyAudio.Static.Mute = true;
                MyAudio.Static.StopMusic();
                UnloadAndExitToMenu();
                break;

            case MyGuiScreenMessageBox.ResultEnum.CANCEL:
                this.CanBeHidden = true;
                break;
            }
        }
 public MyTestersInputComponent()
 {
     AddShortcut(MyKeys.Back, true, true, false, false, () => "Freeze cube builder gizmo", delegate { MyCubeBuilder.Static.FreezeGizmo = !MyCubeBuilder.Static.FreezeGizmo; return(true); });
     AddShortcut(MyKeys.NumPad0, false, false, false, false, () => "Add items to inventory (continuous)", delegate { AddItemsToInventory(0); return(true); });
     AddShortcut(MyKeys.NumPad1, true, false, false, false, () => "Add items to inventory", delegate { AddItemsToInventory(1); return(true); });
     AddShortcut(MyKeys.NumPad2, true, false, false, false, () => "Add components to inventory", delegate { AddItemsToInventory(2); return(true); });
     AddShortcut(MyKeys.NumPad3, true, false, false, false, () => "Fill inventory with iron", FillInventoryWithIron);
     AddShortcut(MyKeys.NumPad4, true, false, false, false, () => "Add to inventory dialog...", delegate { var dialog = new MyGuiScreenDialogInventoryCheat(); MyGuiSandbox.AddScreen(dialog); return(true); });
     AddShortcut(MyKeys.NumPad5, true, false, false, false, () => "Set container type", SetContainerType);
     AddShortcut(MyKeys.NumPad6, true, false, false, false, () => "Toggle debug draw", ToggleDebugDraw);
     AddShortcut(MyKeys.NumPad8, true, false, false, false, () => "Save the game", delegate { MyAsyncSaving.Start(); return(true); });
 }
Ejemplo n.º 9
0
        //  This method is called every update (but only if application has focus)
        public override void HandleUnhandledInput(bool receivedFocusInThisUpdate)
        {
            if (MyInput.Static.ENABLE_DEVELOPER_KEYS || (MySession.Static != null && MySession.Static.Settings.EnableSpectator) || (MyMultiplayer.Static != null && MySession.LocalHumanPlayer != null && MyMultiplayer.Static.IsAdmin(MySession.LocalHumanPlayer.Id.SteamId)))
            {
                //Set camera to player
                if (MyInput.Static.IsNewGameControlPressed(MyControlsSpace.SPECTATOR_NONE))
                {
                    if (MySession.ControlledEntity != null)
                    { //we already are controlling this object
                        if (MyFinalBuildConstants.IS_OFFICIAL)
                        {
                            SetCameraController();
                        }
                        else
                        {
                            var cameraController = MySession.GetCameraControllerEnum();
                            if (cameraController != MyCameraControllerEnum.Entity && cameraController != MyCameraControllerEnum.ThirdPersonSpectator)
                            {
                                SetCameraController();
                            }
                            else
                            {
                                var entities       = MyEntities.GetEntities().ToList();
                                int lastKnownIndex = entities.IndexOf(MySession.ControlledEntity.Entity);

                                var entitiesList = new List <MyEntity>();
                                if (lastKnownIndex + 1 < entities.Count)
                                {
                                    entitiesList.AddRange(entities.GetRange(lastKnownIndex + 1, entities.Count - lastKnownIndex - 1));
                                }

                                if (lastKnownIndex != -1)
                                {
                                    entitiesList.AddRange(entities.GetRange(0, lastKnownIndex + 1));
                                }

                                MyCharacter newControlledObject = null;

                                for (int i = 0; i < entitiesList.Count; i++)
                                {
                                    var character = entitiesList[i] as MyCharacter;
                                    if (character != null && !character.IsDead)
                                    {
                                        newControlledObject = character;
                                        break;
                                    }
                                }

                                if (MySession.LocalHumanPlayer != null && newControlledObject != null)
                                {
                                    MySession.LocalHumanPlayer.Controller.TakeControl(newControlledObject);
                                }
                            }

                            // We could have activated the cube builder in spectator, so deactivate it now
                            if (MyCubeBuilder.Static.IsActivated && !(MySession.ControlledEntity is MyCharacter))
                            {
                                MyCubeBuilder.Static.Deactivate();
                            }
                        }
                    }
                }

                //Set camera to following third person
                if (MyInput.Static.IsNewGameControlPressed(MyControlsSpace.SPECTATOR_DELTA))
                {
                    if (MySession.ControlledEntity != null)
                    {
                        MySession.SetCameraController(MyCameraControllerEnum.SpectatorDelta);
                    }
                }

                //Set camera to spectator
                if (MyInput.Static.IsNewGameControlPressed(MyControlsSpace.SPECTATOR_FREE))
                {
                    if (!MyFakes.ENABLE_BATTLE_SYSTEM || !MySession.Static.Battle || Sync.IsServer)
                    {
                        if (MySession.GetCameraControllerEnum() != MyCameraControllerEnum.Spectator)
                        {
                            MySession.SetCameraController(MyCameraControllerEnum.Spectator);
                        }
                        else if (MyInput.Static.IsAnyShiftKeyPressed())
                        {
                            MyFakes.ENABLE_DEVELOPER_SPECTATOR_CONTROLS = !MyFakes.ENABLE_DEVELOPER_SPECTATOR_CONTROLS;
                        }

                        if (MyInput.Static.IsAnyCtrlKeyPressed() && MySession.ControlledEntity != null)
                        {
                            MySpectator.Static.Position = (Vector3D)MySession.ControlledEntity.Entity.PositionComp.GetPosition() + MySpectator.Static.ThirdPersonCameraDelta;
                            MySpectator.Static.Target   = (Vector3D)MySession.ControlledEntity.Entity.PositionComp.GetPosition();
                        }
                    }
                }

                //Set camera to static spectator, non movable
                if (MyInput.Static.IsNewGameControlPressed(MyControlsSpace.SPECTATOR_STATIC))
                {
                    if (MySession.ControlledEntity != null)
                    {
                        MySession.SetCameraController(MyCameraControllerEnum.SpectatorFixed);

                        if (MyInput.Static.IsAnyCtrlKeyPressed())
                        {
                            MySpectator.Static.Position = (Vector3D)MySession.ControlledEntity.Entity.PositionComp.GetPosition() + MySpectator.Static.ThirdPersonCameraDelta;
                            MySpectator.Static.Target   = (Vector3D)MySession.ControlledEntity.Entity.PositionComp.GetPosition();
                        }
                    }
                }

                //Open console
                if (MyInput.Static.IsNewGameControlPressed(MyControlsSpace.CONSOLE) && MyInput.Static.IsAnyAltKeyPressed())
                {
                    MyGuiScreenConsole.Show();
                }
            }

            if (MyDefinitionErrors.ShouldShowModErrors)
            {
                MyDefinitionErrors.ShouldShowModErrors = false;
                MyGuiSandbox.ShowModErrors();
            }

            // Switch view - cockpit on/off, third person
            if (MyInput.Static.IsNewGameControlPressed(MyControlsSpace.CAMERA_MODE) && CanSwitchCamera)
            {
                MyGuiAudio.PlaySound(MyGuiSounds.HudClick);
                SwitchCamera();
            }

            if (MyInput.Static.IsNewGameControlPressed(MyControlsSpace.HELP_SCREEN))
            {
                if (MyInput.Static.IsAnyCtrlKeyPressed())
                {
                    switch (MySandboxGame.Config.DebugComponentsInfo)
                    {
                    case MyDebugComponent.MyDebugComponentInfoState.NoInfo:
                        MySandboxGame.Config.DebugComponentsInfo = MyDebugComponent.MyDebugComponentInfoState.EnabledInfo;
                        break;

                    case MyDebugComponent.MyDebugComponentInfoState.EnabledInfo:
                        MySandboxGame.Config.DebugComponentsInfo = MyDebugComponent.MyDebugComponentInfoState.FullInfo;
                        break;

                    case MyDebugComponent.MyDebugComponentInfoState.FullInfo:
                        MySandboxGame.Config.DebugComponentsInfo = MyDebugComponent.MyDebugComponentInfoState.NoInfo;
                        break;
                    }

                    MySandboxGame.Config.Save();
                }
                else
                if (MyGuiScreenGamePlay.ActiveGameplayScreen == null)
                {
                    MyGuiAudio.PlaySound(MyGuiSounds.HudMouseClick);
                    MyGuiSandbox.AddScreen(MyGuiScreenGamePlay.ActiveGameplayScreen = MyGuiSandbox.CreateScreen(MyPerGameSettings.GUI.HelpScreen));
                }
            }

            if (MyInput.Static.IsNewGameControlPressed(MyControlsSpace.TOGGLE_HUD))
            {
                MyGuiAudio.PlaySound(MyGuiSounds.HudClick);
                MyHud.MinimalHud = !MyHud.MinimalHud;
            }

            if (MyPerGameSettings.SimplePlayerNames && MyInput.Static.IsNewGameControlPressed(MyControlsSpace.BROADCASTING))
            {
                MyHud.LocationMarkers.Visible = !MyHud.LocationMarkers.Visible;
            }

            var controlledObject        = MySession.ControlledEntity;
            var currentCameraController = MySession.Static.CameraController;

            if (MyInput.Static.IsNewGameControlPressed(MyControlsSpace.MISSION_SETTINGS) && MyGuiScreenGamePlay.ActiveGameplayScreen == null &&
                MyPerGameSettings.Game == Sandbox.Game.GameEnum.SE_GAME &&
                MyFakes.ENABLE_MISSION_TRIGGERS &&
                MySession.Static.Settings.ScenarioEditMode)
            {
                MyGuiSandbox.AddScreen(new Sandbox.Game.Screens.MyGuiScreenMissionTriggers());
            }

            MyStringId context = controlledObject != null ? controlledObject.ControlContext : MySpaceBindingCreator.CX_BASE;

            bool handledByUseObject = false;

            if (MySession.ControlledEntity is VRage.Game.Entity.UseObject.IMyUseObject)
            {
                handledByUseObject = (MySession.ControlledEntity as VRage.Game.Entity.UseObject.IMyUseObject).HandleInput();
            }

            if (controlledObject != null && !handledByUseObject)
            {
                if (!MySandboxGame.IsPaused)
                {
                    if (context == MySpaceBindingCreator.CX_BUILD_MODE || context == MySpaceBindingCreator.CX_CHARACTER || context == MySpaceBindingCreator.CX_SPACESHIP)
                    {
                        if (MyControllerHelper.IsControl(context, MyControlsSpace.PRIMARY_TOOL_ACTION, MyControlStateType.NEW_PRESSED))
                        {
                            if (MyToolbarComponent.CurrentToolbar.ShouldActivateSlot)
                            {
                                MyToolbarComponent.CurrentToolbar.ActivateStagedSelectedItem();
                            }
                            else
                            {
                                controlledObject.BeginShoot(MyShootActionEnum.PrimaryAction);
                            }
                        }

                        if (MyControllerHelper.IsControl(context, MyControlsSpace.PRIMARY_TOOL_ACTION, MyControlStateType.NEW_RELEASED))
                        {
                            controlledObject.EndShoot(MyShootActionEnum.PrimaryAction);
                        }
                        if (MyControllerHelper.IsControl(context, MyControlsSpace.SECONDARY_TOOL_ACTION, MyControlStateType.NEW_PRESSED))
                        {
                            controlledObject.BeginShoot(MyShootActionEnum.SecondaryAction);
                        }
                        if (MyControllerHelper.IsControl(context, MyControlsSpace.SECONDARY_TOOL_ACTION, MyControlStateType.NEW_RELEASED))
                        {
                            controlledObject.EndShoot(MyShootActionEnum.SecondaryAction);
                        }
                    }

                    if (context == MySpaceBindingCreator.CX_CHARACTER || context == MySpaceBindingCreator.CX_SPACESHIP)
                    {
                        if (MyControllerHelper.IsControl(context, MyControlsSpace.USE, MyControlStateType.NEW_PRESSED))
                        {
                            // Key press
                            if (currentCameraController != null)
                            {
                                if (!currentCameraController.HandleUse())
                                {
                                    controlledObject.Use();
                                }
                            }
                            else
                            {
                                controlledObject.Use();
                            }
                        }
                        else if (MyControllerHelper.IsControl(context, MyControlsSpace.USE, MyControlStateType.PRESSED))
                        {
                            // Key not pressed this frame, holding from previous
                            controlledObject.UseContinues();
                        }
                        else if (MyControllerHelper.IsControl(context, MyControlsSpace.USE, MyControlStateType.NEW_RELEASED))
                        {
                            controlledObject.UseFinished();
                        }

                        //Temp fix until spectators are implemented as entities
                        //Prevents controlled object from getting input while spectator mode is enabled
                        if (!(MySession.Static.CameraController is MySpectatorCameraController && MySpectatorCameraController.Static.SpectatorCameraMovement == MySpectatorCameraMovementEnum.UserControlled))
                        {
                            if (MyControllerHelper.IsControl(context, MyControlsSpace.CROUCH, MyControlStateType.NEW_PRESSED))
                            {
                                controlledObject.Crouch();
                            }
                            if (MyControllerHelper.IsControl(context, MyControlsSpace.CROUCH, MyControlStateType.PRESSED))
                            {
                                controlledObject.Down();
                            }
                            if (MyControllerHelper.IsControl(context, MyControlsSpace.SPRINT, MyControlStateType.PRESSED))
                            {
                                controlledObject.Sprint();
                            }
                            if (MyControllerHelper.IsControl(context, MyControlsSpace.JUMP, MyControlStateType.NEW_PRESSED))
                            {
                                controlledObject.Jump();
                            }
                            if (MyControllerHelper.IsControl(context, MyControlsSpace.JUMP, MyControlStateType.PRESSED))
                            {
                                controlledObject.Up();
                            }
                            if (MyControllerHelper.IsControl(context, MyControlsSpace.SWITCH_WALK, MyControlStateType.NEW_PRESSED))
                            {
                                controlledObject.SwitchWalk();
                            }
                            if (MyControllerHelper.IsControl(context, MyControlsSpace.BROADCASTING, MyControlStateType.NEW_PRESSED))
                            {
                                controlledObject.SwitchBroadcasting();
                            }
                            if (MyControllerHelper.IsControl(context, MyControlsSpace.HELMET, MyControlStateType.NEW_PRESSED))
                            {
                                controlledObject.SwitchHelmet();
                            }
                        }

                        if (MyControllerHelper.IsControl(context, MyControlsSpace.DAMPING, MyControlStateType.NEW_PRESSED))
                        {
                            MyGuiAudio.PlaySound(MyGuiSounds.HudClick);
                            controlledObject.SwitchDamping();
                        }
                        if (MyControllerHelper.IsControl(context, MyControlsSpace.THRUSTS, MyControlStateType.NEW_PRESSED))
                        {
                            MyGuiAudio.PlaySound(MyGuiSounds.HudClick);
                            controlledObject.SwitchThrusts();
                        }
                        if (MyControllerHelper.IsControl(context, MyControlsSpace.HEADLIGHTS, MyControlStateType.NEW_PRESSED))
                        {
                            MyGuiAudio.PlaySound(MyGuiSounds.HudClick);
                            controlledObject.SwitchLights();
                        }
                        if (MyControllerHelper.IsControl(context, MyControlsSpace.TOGGLE_REACTORS, MyControlStateType.NEW_PRESSED))
                        {
                            MyGuiAudio.PlaySound(MyGuiSounds.HudClick);
                            controlledObject.SwitchReactors();
                        }
                        if (MyControllerHelper.IsControl(context, MyControlsSpace.LANDING_GEAR, MyControlStateType.NEW_PRESSED))
                        {
                            MyGuiAudio.PlaySound(MyGuiSounds.HudClick);
                            controlledObject.SwitchLeadingGears();
                        }
                        if (MyControllerHelper.IsControl(context, MyControlsSpace.SUICIDE, MyControlStateType.NEW_PRESSED))
                        {
                            controlledObject.Die();
                        }
                        if ((controlledObject as MyCockpit) != null && MyControllerHelper.IsControl(context, MyControlsSpace.CUBE_COLOR_CHANGE, MyControlStateType.NEW_PRESSED))
                        {
                            (controlledObject as MyCockpit).SwitchWeaponMode();
                        }
                    }
                }
                if (MyControllerHelper.IsControl(context, MyControlsSpace.TERMINAL, MyControlStateType.NEW_PRESSED) && MyGuiScreenGamePlay.ActiveGameplayScreen == null)
                {
                    MyGuiAudio.PlaySound(MyGuiSounds.HudClick);
                    controlledObject.ShowTerminal();
                }

                if (MyControllerHelper.IsControl(context, MyControlsSpace.INVENTORY, MyControlStateType.NEW_PRESSED) && MyGuiScreenGamePlay.ActiveGameplayScreen == null)
                {
                    MyGuiAudio.PlaySound(MyGuiSounds.HudClick);
                    controlledObject.ShowInventory();
                }

                if (MyControllerHelper.IsControl(context, MyControlsSpace.CONTROL_MENU, MyControlStateType.NEW_PRESSED) && MyGuiScreenGamePlay.ActiveGameplayScreen == null)
                {
                    MyGuiAudio.PlaySound(MyGuiSounds.HudClick);
                    m_controlMenu.OpenControlMenu(controlledObject);
                }

                if (!MyCompilationSymbols.RenderProfiling && MyControllerHelper.IsControl(context, MyControlsSpace.CHAT_SCREEN, MyControlStateType.NEW_PRESSED))
                {
                    if (MyGuiScreenChat.Static == null)
                    {
                        Vector2 chatPos = new Vector2(0.01f, 0.84f);
                        chatPos = MyGuiScreenHudBase.ConvertHudToNormalizedGuiPosition(ref chatPos);
                        MyGuiScreenChat chatScreen = new MyGuiScreenChat(chatPos);
                        MyGuiSandbox.AddScreen(chatScreen);
                    }
                }

                if (MyPerGameSettings.VoiceChatEnabled)
                {
                    if (MyControllerHelper.IsControl(context, MyControlsSpace.VOICE_CHAT, MyControlStateType.NEW_PRESSED))
                    {
                        MyVoiceChatSessionComponent.Static.StartRecording();
                    }
                    //else if (MyControllerHelper.IsControl(context, MyControlsSpace.VOICE_CHAT, MyControlStateType.NEW_RELEASED))
                    // TODO: If other key was pressed during VOIP, NEW_RELEASED will return false even if this key was pressed, is this correct? We don't store key states?
                    else if (MyVoiceChatSessionComponent.Static.IsRecording && !MyControllerHelper.IsControl(context, MyControlsSpace.VOICE_CHAT, MyControlStateType.PRESSED))
                    {
                        MyVoiceChatSessionComponent.Static.StopRecording();
                    }
                }
            }

            MoveAndRotatePlayerOrCamera();

            // Quick save or quick load.
            if (MyInput.Static.IsNewKeyPressed(MyKeys.F5))
            {
                if (!MySession.Static.IsScenario)
                {
                    MyGuiAudio.PlaySound(MyGuiSounds.HudMouseClick);
                    var currentSession = MySession.Static.CurrentPath;

                    if (MyInput.Static.IsAnyShiftKeyPressed())
                    {
                        if (MySession.Static.ClientCanSave || Sync.IsServer)
                        {
                            if (!MyAsyncSaving.InProgress)
                            {
                                var messageBox = MyGuiSandbox.CreateMessageBox(
                                    buttonType : MyMessageBoxButtonsType.YES_NO,
                                    messageText : MyTexts.Get(MySpaceTexts.MessageBoxTextAreYouSureYouWantToQuickSave),
                                    messageCaption : MyTexts.Get(MySpaceTexts.MessageBoxCaptionPleaseConfirm),
                                    callback : delegate(MyGuiScreenMessageBox.ResultEnum callbackReturn)
                                {
                                    if (callbackReturn == MyGuiScreenMessageBox.ResultEnum.YES)
                                    {
                                        MyAsyncSaving.Start(() => MySector.ResetEyeAdaptation = true);    //black screen after save
                                    }
                                });
                                messageBox.SkipTransition      = true;
                                messageBox.CloseBeforeCallback = true;
                                MyGuiSandbox.AddScreen(messageBox);
                            }
                        }
                        else
                        {
                            MyHud.Notifications.Add(MyNotificationSingletons.ClientCannotSave);
                        }
                    }
                    else if (Sync.IsServer)
                    {
                        ShowLoadMessageBox(currentSession);
                    }
                    else
                    {
                        // Is multiplayer client, reconnect
                        ShowReconnectMessageBox();
                    }
                }
            }

            //  Launch main menu
            if (MyInput.Static.IsNewKeyPressed(MyKeys.Escape) ||
                MyControllerHelper.IsControl(context, MyControlsGUI.MAIN_MENU, MyControlStateType.NEW_PRESSED))
            {
                MyGuiAudio.PlaySound(MyGuiSounds.HudMouseClick);

                //Allow changing video options from game in DX version
                MyGuiScreenMainMenu.AddMainMenu();
            }

            if (MyInput.Static.IsNewKeyPressed(MyKeys.F3))
            {
                if (Sync.MultiplayerActive)
                {
                    MyGuiAudio.PlaySound(MyGuiSounds.HudMouseClick);
                    MyGuiSandbox.AddScreen(new MyGuiScreenPlayers());
                }
                else
                {
                    MyHud.Notifications.Add(MyNotificationSingletons.MultiplayerDisabled);
                }
            }

            if (MyInput.Static.IsNewGameControlPressed(MyControlsSpace.BUILD_SCREEN) && MyGuiScreenGamePlay.ActiveGameplayScreen == null)
            {
                if (MyGuiScreenCubeBuilder.Static == null && (MySession.ControlledEntity is MyShipController || MySession.ControlledEntity is MyCharacter))
                {
                    int offset = 0;
                    if (MyInput.Static.IsAnyShiftKeyPressed())
                    {
                        offset += 6;
                    }
                    if (MyInput.Static.IsAnyCtrlKeyPressed())
                    {
                        offset += 12;
                    }
                    MyGuiAudio.PlaySound(MyGuiSounds.HudMouseClick);
                    MyGuiSandbox.AddScreen(
                        MyGuiScreenGamePlay.ActiveGameplayScreen = MyGuiSandbox.CreateScreen(MyPerGameSettings.GUI.ToolbarConfigScreen,
                                                                                             offset,
                                                                                             MySession.ControlledEntity as MyShipController)
                        );
                }
            }

            if (MyInput.Static.IsNewGameControlPressed(MyControlsSpace.PAUSE_GAME))
            {
                MySandboxGame.UserPauseToggle();
            }

            if (MySession.Static != null)
            {
                if (MyInput.Static.IsNewKeyPressed(MyKeys.F10))
                {
                    if (MyPerGameSettings.GUI.VoxelMapEditingScreen != null && MySession.Static.CreativeMode && MyInput.Static.IsAnyShiftKeyPressed())
                    { // Shift+F10
                        MyGuiSandbox.AddScreen(MyGuiSandbox.CreateScreen(MyPerGameSettings.GUI.VoxelMapEditingScreen));
                    }
                    else
                    { // F10
                        if (MyFakes.ENABLE_BATTLE_SYSTEM && MySession.Static.Battle)
                        {
                            if (MyPerGameSettings.GUI.BattleBlueprintScreen != null)
                            {
                                MyGuiSandbox.AddScreen(MyGuiSandbox.CreateScreen(MyPerGameSettings.GUI.BattleBlueprintScreen));
                            }
                            else
                            {
                                Debug.Fail("No battle blueprint screen");
                            }
                        }
                        else
                        {
                            MyGuiSandbox.AddScreen(new MyGuiBlueprintScreen(MyCubeBuilder.Static.Clipboard));
                        }
                    }
                }
            }

            // F11, mod debug
            if (MyInput.Static.IsNewKeyPressed(MyKeys.F11) && !MyInput.Static.IsAnyShiftKeyPressed() && !MyInput.Static.IsAnyCtrlKeyPressed())
            {
                MyDX9Gui.SwitchModDebugScreen();
            }
        }
Ejemplo n.º 10
0
        public void AsynchronousSaveWorld( )
        {
            if (m_isSaving)
            {
                ApplicationLog.BaseLog.Error("Tried to initiate a save while another is already in progress!");
                return;
            }

            m_isSaving = true;

            try
            {
                ApplicationLog.BaseLog.Info("Asynchronous save started");
                DateTime saveStartTime = DateTime.Now;
                Task.Run(() =>
                {
                    SandboxGameAssemblyWrapper.Instance.GameAction(() =>
                    {
                        MyAsyncSaving.Start(() =>
                        {
                            MySector.ResetEyeAdaptation = true;
                            ApplicationLog.BaseLog.Info("Asynchronous Save Setup Started: {0}ms",
                                                        (DateTime.Now - saveStartTime)
                                                        .TotalMilliseconds);
                        });
                    });

                    // Autosave can fail to complete sometimes; alert the admin when this happens
                    DateTime start            = DateTime.Now;
                    FastResourceLock saveLock = InternalGetResourceLock();
                    while (!saveLock.Owned)
                    {
                        if (DateTime.Now - start > TimeSpan.FromMilliseconds(20000))
                        {
                            ApplicationLog.BaseLog.Warn("Autosave failed to start!");
                            return;
                        }

                        Thread.Sleep(1);
                    }

                    while (saveLock.Owned)
                    {
                        if (DateTime.Now - start > TimeSpan.FromMilliseconds(120000))
                        {
                            ApplicationLog.BaseLog.Warn("Autosave has ran for 120 seconds--something is wrong! The save will most likely not complete!");
                            MyAPIGateway.Utilities.SendMessage("Warning: SESE Autosave failed! Alert the server admin!");
                            return;
                        }

                        Thread.Sleep(1);
                    }

                    ApplicationLog.BaseLog.Info($"Asynchronous Save Completed: {(DateTime.Now - saveStartTime).TotalMilliseconds}ms");
                    OnWorldSaved();
                    EntityEventManager.EntityEvent newEvent = new EntityEventManager.EntityEvent
                    {
                        type      = EntityEventManager.EntityEventType.OnSectorSaved,
                        timestamp = DateTime.Now,
                        entity    = null,
                        priority  = 0
                    };
                    EntityEventManager.Instance.AddEvent(newEvent);
                });
            }
            catch (Exception ex)
            {
                ApplicationLog.BaseLog.Error(ex, "Exception in asynchronous save.");
            }
            finally
            {
                m_isSaving = false;
            }

            /*
             * try
             * {
             *      DateTime saveStartTime = DateTime.Now;
             *
             *      // It looks like keen as an overloaded save function that returns the WorldResourceManager after setting up a save, and then
             *      // allows you to write to disk from a separate thread?  Why aren't they using this on normal saves?!
             *      bool result = false;
             *      String arg0 = null;
             *      Object[] parameters =
             *      {
             *              null,
             *              arg0,
             *      };
             *
             *      Type[] paramTypes =
             *      {
             *              SandboxGameAssemblyWrapper.Instance.GetAssemblyType(WorldResourceManagerNamespace, WorldResourceManagerClass).MakeByRefType(),
             *              typeof(string),
             *      };
             *
             *      // Run overloaded save function with extra an out parameter that is set to a WorldResourceManagerClass
             *      SandboxGameAssemblyWrapper.Instance.GameAction(() =>
             *      {
             *              result = (bool)BaseObject.InvokeEntityMethod(BackingObject, WorldManagerSaveWorldMethod, parameters, paramTypes);
             *      });
             *
             *
             *      // Write to disk on a different thread using the WorldResourceManagerClass in the parameter
             *      ThreadPool.QueueUserWorkItem(new WaitCallback((object state) =>
             *      {
             *              if (result)
             *              {
             *                      ApplicationLog.BaseLog.Info((string.Format("Asynchronous Save Setup Time: {0}ms", (DateTime.Now - saveStartTime).TotalMilliseconds));
             *                      saveStartTime = DateTime.Now;
             *                      result = (bool)BaseObject.InvokeEntityMethod(parameters[0], WorldManagerSaveSnapshot);
             *              }
             *              else
             *              {
             *                      ApplicationLog.BaseLog.Error("Failed to save world (1)");
             *                      return;
             *              }
             *
             *              if (result)
             *              {
             *                      ApplicationLog.BaseLog.Info((string.Format("Asynchronous Save Successful: {0}ms", (DateTime.Now - saveStartTime).TotalMilliseconds));
             *              }
             *              else
             *              {
             *                      ApplicationLog.BaseLog.Error("Failed to save world (2)");
             *                      return;
             *              }
             *
             *              EntityEventManager.EntityEvent newEvent = new EntityEventManager.EntityEvent();
             *              newEvent.type = EntityEventManager.EntityEventType.OnSectorSaved;
             *              newEvent.timestamp = DateTime.Now;
             *              newEvent.entity = null;
             *              newEvent.priority = 0;
             *              EntityEventManager.Instance.AddEvent(newEvent);
             *      }));
             * }
             * catch (Exception ex)
             * {
             *      ApplicationLog.BaseLog.Error(ex);
             * }
             * finally
             * {
             *      m_isSaving = false;
             * }
             */
        }
Ejemplo n.º 11
0
 private static void Save(string[] args)
 {
     MySandboxGame.Log.WriteLineAndConsole("Executing +save command");
     MyAsyncSaving.Start(null, null, false);
 }