public static void HandleInput(MyGuiInput input)
        {
            if (input.IsAnyAltPress())
            {
                for (int i = 0; i <= 9; i++)
                {
                    var key = (Keys)((int)Keys.NumPad0 + i);
                    if (input.IsNewKeyPress(key))
                    {
                        PressedKey(key, input.IsAnyCtrlKeyPressed());
                    }
                }

                if (input.IsNewKeyPress(Keys.Add))
                    PressedKey(Keys.Add);

                if (input.IsNewKeyPress(Keys.Subtract))
                    PressedKey(Keys.Subtract);

                if (input.IsNewKeyPress(Keys.Enter))
                    PressedKey(Keys.Enter);

                if (input.IsNewKeyPress(Keys.Delete))
                    PressedKey(Keys.Delete);

                if (input.IsKeyPress(Keys.PageDown))
                    MyRenderProfiler.PreviousFrame();

                if (input.IsKeyPress(Keys.PageUp))
                    MyRenderProfiler.NextFrame();

                if (input.IsKeyPress(Keys.Multiply))
                    PressedKey(Keys.Multiply);

                if (input.IsKeyPress(Keys.Divide))
                    PressedKey(Keys.Divide);

                if ((((input.IsKeyPress(Keys.PageDown)) ||
                    (input.IsKeyPress(Keys.PageUp))) && input.IsAnyCtrlKeyPressed())
                    ||
                    (input.IsKeyPress(Keys.Multiply) || input.IsKeyPress(Keys.Divide))
                    )

                {
                    System.Threading.Thread.Sleep(100);
                }
            }
        }
        //  This method is called every update (but only if application has focus)
        public override void HandleUnhandledInput(MyGuiInput input, bool receivedFocusInThisUpdate)
        {
            //  This is protection against situation when user clicks on CONTINUE in menu, but don't release the button quickly, so in gameplay screen
            //  it continues with shoting. So in this case he must release buttons and then press again if he want to shot.
            if (m_handleInputMouseKeysReleased == false)
            {
                if ((input.IsLeftMouseReleased()) && (input.IsRightMouseReleased()))
                {
                    m_handleInputMouseKeysReleased = true;
                }
            }

            //Set if ammo select menu or config menu is enable
            m_selectAmmoMenu.IsEnabled = !m_wheelControlMenu.Visible && IsControlledPlayerShip;
            m_wheelControlMenu.IsEnable = !m_selectAmmoMenu.Visible && IsControlledPlayerShip;

            if (IsControlledPlayerShip && !m_selectAmmoMenu.IsEnabled && !m_wheelControlMenu.IsEnable)
            {
                m_selectAmmoMenu.IsEnabled = true;
            }

            //  Launch main menu
            if (!m_wheelControlMenu.Visible && !IsSelectAmmoVisible() && input.IsNewKeyPress(Keys.Escape) && !(IsEditorActive() && (EditorControls.TryExitSelected() || EditorControls.TryExitSelectionMode())))
            {
                MyAudio.AddCue2D(MySoundCuesEnum.GuiMouseClick);

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

                DrawHud = false;

                MySystemTimer.SetMinimalResolution();
            }


            MyHudSectorBorder.SwitchToDraw();

            // Switch from player ship to ingame editor and back
            if (IsGameActive() || IsEditorActive())
            {
                if (!input.IsAnyAltPress())
                {
                    if ((input.IsNewKeyPress(Keys.NumPad0) || input.IsNewKeyPress(Keys.D0)) && (GetSessionType() == MyMwcStartSessionRequestTypeEnum.EDITOR_STORY || GetSessionType() == MyMwcStartSessionRequestTypeEnum.EDITOR_SANDBOX || GetSessionType() == MyMwcStartSessionRequestTypeEnum.EDITOR_MMO))
                    {
                        ReturnControlToPlayerShip();
                        m_invokeGameEditorSwitch = true;
                    }
                }
            }

            if (CameraAttachedTo == MyCameraAttachedToEnum.PlayerMinerShip_ThirdPersonFollowing)
            {
                if (input.PreviousMouseScrollWheelValue() < input.MouseScrollWheelValue())
                {
                    ThirdPersonCameraDelta /= 1.1f;
                }
                else if (input.PreviousMouseScrollWheelValue() > input.MouseScrollWheelValue())
                {
                    ThirdPersonCameraDelta *= 1.1f;
                }
            }

            if (CameraAttachedTo == MyCameraAttachedToEnum.Spectator)
            {
                if (input.PreviousMouseScrollWheelValue() < input.MouseScrollWheelValue())
                {
                    MySpectator.SpeedMode = Math.Min(MySpectator.SpeedMode * 1.5f, MyEditorConstants.MAX_EDITOR_CAMERA_MOVE_MULTIPLIER);
                }
                else if (input.PreviousMouseScrollWheelValue() > input.MouseScrollWheelValue())
                {
                    MySpectator.SpeedMode = Math.Max(MySpectator.SpeedMode / 1.5f, MyEditorConstants.MIN_EDITOR_CAMERA_MOVE_MULTIPLIER);
                }
            }

            if (CameraAttachedTo == MyCameraAttachedToEnum.PlayerMinerShip_ThirdPersonDynamic &&
                !m_wheelControlMenu.Visible && !IsSelectAmmoVisible())  // don't zoom if wheel or ammo menu is visible
            {
                float distance = MyThirdPersonSpectator.LookAt.Length();
                float currentDistance = (MyThirdPersonSpectator.Target - MyThirdPersonSpectator.DesiredPosition).Length();
                float newDistance = 0;

                if (input.PreviousMouseScrollWheelValue() < input.MouseScrollWheelValue())
                {
                    newDistance = currentDistance / 1.2f;
                }
                else if (input.PreviousMouseScrollWheelValue() > input.MouseScrollWheelValue())
                {
                    newDistance = distance * 1.2f;
                }

                if (newDistance > 0)
                {
                    // Limit distance from ship
                    newDistance = MathHelper.Clamp(newDistance, MyThirdPersonSpectator.GetMinDistance(), MyThirdPersonSpectator.MAX_DISTANCE);
                    MyThirdPersonSpectator.LookAt *= newDistance / distance;
                }

                //MyThirdPersonSpectator.LookAt = new Vector3(0, 130, 65);
            }

            #region Universal developer keys

            if (MyGuiInput.ENABLE_DEVELOPER_KEYS)
            {
                if (input.IsNewKeyPress(Keys.Multiply))
                {
                    //MyHudNotification.AddNotification(new MyHudNotification.MyNotification("Searching for most complex region..." , 3000));
                    //int[] res = MyEntities.getMostComplexCameraView(128);
                    //MyHudNotification.AddNotification(new MyHudNotification.MyNotification("X " + res[0] + " Y" + res[1] + " Z" + res[2], 3000));
                    //MyEntities.getMostComplexCameraView(128);
                }
                //if (MyFakes.ENABLE_MULTIPLAYER && input.IsAnyShiftKeyPressed() && input.IsNewKeyPress(Keys.PageUp))
                //{
                //    MyMultiplayer.HostGame(null);
                //    MyMultiplayer.Static.OnNotification = new Action<MyTextsWrapperEnum, object[]>(Static_OnNotification);
                //}

                if (MyMwcFinalBuildConstants.IS_DEVELOP && input.IsNewKeyPress(Keys.F5) && input.IsAnyCtrlKeyPressed())
                {
                    MySession.Static.SaveLastCheckpoint(false);
                }

                //  Show sector border
                if (MyMwcFinalBuildConstants.IS_DEVELOP && input.IsNewKeyPress(Keys.U))
                {
                    if (MyFakes.MWBUILDER)
                    {
                        if (input.IsAnyShiftKeyPressed())
                        {
                            MyEditorGrid.SwitchGridOrientation();
                        }
                        else
                        {
                            MyEditorGrid.IsGridActive = !MyEditorGrid.IsGridActive;
                        }
                    }
                    else
                    {
                        MyHudSectorBorder.SwitchSectorBorderVisibility();
                    }
                }

                if (MyMwcFinalBuildConstants.ENABLE_TRAILER_SAVE && (MyGuiScreenGamePlay.Static.IsGameActive() || MyGuiScreenGamePlay.Static.IsEditorActive())) // Trailer controls
                {
                    //if (input.IsKeyPress(Keys.NumPad5) && input.IsAnyShiftKeyPressed()) // SHIFT + Num5 - Set trailer start position
                    //{
                    //    MyHudNotification.AddNotification(new MyHudNotification.MyNotification("Trailer start set", 5));
                    //    trailerStartPosition = MySession.PlayerShip.WorldMatrix;
                    //}

                    if (input.IsNewKeyPress(Keys.NumPad5) && !input.IsAnyShiftKeyPressed()) // Num5 - Restart & record...
                    {
                        RestartTrailer(false, false);
                    }

                    if (input.IsNewKeyPress(Keys.NumPad7) && !input.IsAnyShiftKeyPressed()) // Num7 - Restart & teleport & record...
                    {
                        RestartTrailer(false, true);
                        //var translation = Matrix.CreateTranslation(MySession.PlayerShip.WorldMatrix.Translation + MyMwcUtils.Normalize(MySession.PlayerShip.WorldMatrix.Backward) * 10);
                        //MySession.PlayerShip.WorldMatrix *= translation;
                    }

                    if (input.IsNewKeyPress(Keys.NumPad9) && !input.IsAnyShiftKeyPressed()) // Num9 - Restart save & record...
                    {
                        RestartTrailer(true, true);
                    }
                }

                if (input.IsNewKeyPress(Keys.S) && input.IsAnyAltKeyPressed() && input.IsAnyCtrlKeyPressed())
                {
                    MyEditor.SaveSelectedVoxelMap(input.IsAnyShiftKeyPressed());
                }

                if (input.IsNewKeyPress(Keys.Delete) && input.IsAnyCtrlKeyPressed())
                {
                    if (MyMissions.ActiveMission != null)
                    {
                        MyObjective.SkipSubmission = true;
                    }
                }

                if (input.IsNewKeyPress(Keys.End) && input.IsAnyCtrlKeyPressed())
                {
                    if (MyMissions.ActiveMission != null && MyMissions.ActiveMission.ActiveObjectives.Count > 0)
                    {
                        var entityId = MyMissions.ActiveMission.ActiveObjectives[0].Location.LocationEntityIdentifier.LocationEntityId;
                        MyEntity entity;
                        if (entityId.HasValue && MyEntities.TryGetEntityById(entityId.ToEntityId().Value, out entity))
                        {
                            MySession.PlayerShip.SetPosition(entity.GetPosition());
                        }
                    }
                    else
                    {
                        MyEntity entity;
                        //if (MyEntities.TryGetEntityByName(MyMissionBase.MyMissionLocation.MADELYN_HANGAR, out entity))
                        if (MyEntities.TryGetEntityByName("Madelyn", out entity))
                        {
                            MySession.PlayerShip.SetPosition(entity.GetPosition());
                        }
                    }
                }

                if (input.IsNewKeyPress(Keys.OemTilde) && input.IsAnyCtrlKeyPressed())
                {
                    var ship = MySession.Static.Player.Ship as MySmallShip;
                    ship.DoDamage(1000, 1000, 0, MyDamageType.Explosion, MyAmmoType.Unknown, null);
                    MySession.Static.Player.AddHealth(-MySession.Static.Player.Health, null);
                }

                if ((input.IsNewKeyPress(Keys.OemBackslash) || input.IsNewKeyPress(Keys.OemPipe)) && input.IsAnyShiftKeyPressed())
                {
                    MyLine line = new MyLine(MyCamera.Position, MyCamera.Position + MyCamera.ForwardVector * 25000, false);
                    var intersection = MyEntities.GetIntersectionWithLine(ref line, MySession.Static.Player.Ship, null, true);
                    if (intersection.HasValue)
                    {
                        var target = intersection.Value.IntersectionPointInWorldSpace;
                        target -= MyCamera.ForwardVector * MySession.Static.Player.Ship.LocalVolume.Radius * 20;
                        MySession.Static.Player.Ship.SetPosition(target);
                    }
                }

                if (input.IsNewKeyPress(Keys.NumLock))
                {
                    var player = MySession.Static.Player;

                    player.RestoreHealth();

                    var ship = MySession.Static.Player.Ship as MySmallShip;
                    if (ship != null)
                    {
                        ship.AddHealth(ship.MaxHealth);
                        ship.ArmorHealth = ship.MaxArmorHealth;

                        ship.Oxygen = ship.MaxOxygen;
                        ship.Fuel = ship.MaxFuel;
                        ship.AfterburnerStatus = 1;

                        foreach (Inventory.MyInventoryItem item in ship.Weapons.AmmoInventoryItems.GetAmmoInventoryItems())
                        {
                            item.Amount = item.MaxAmount;
                        }
                    }
                }

                if (input.IsAnyControlPress() && input.IsAnyShiftPress() && input.IsNewKeyPress(Keys.F8))
                {
                    MyGuiPreviewRenderer renderer = MyGuiManager.GetPreviewRenderer();
                    renderer.CreatePreviewsToFiles(@"C:\Temp", MyHudConstants.PREFAB_PREVIEW_SIZE);
                }

                if (input.IsNewKeyPress(Keys.Space) && input.IsAnyCtrlKeyPressed())
                {
                    if (CameraAttachedTo == MyCameraAttachedToEnum.Spectator)
                    {
                        // we try to move ship to the spot, then we check if it colides if yes we move it back.
                        //
                        Vector3 oldPos = MySession.PlayerShip.GetPosition();
                        MySession.PlayerShip.SetPosition(MySpectator.Position);

                        //Move player ship to camera position
                        MyEntities.CollisionsElements.Clear();
                        MinerWars.AppCode.Game.Physics.MyPhysicsBody rBody = MySession.PlayerShip.Physics;
                        if (rBody.GetRBElementList().Count > 0)
                        {
                            // we expect only one rigid body (box)
                            MyEntities.GetCollisionListForElement(rBody.GetRBElementList().First());
                            BoundingSphere bsphere = MySession.PlayerShip.WorldVolume;

                            if (MyEntities.CollisionsElements.Count > 0 || MyVoxelMaps.GetOverlappingWithSphere(ref bsphere) != null)
                            {

                                MySession.PlayerShip.SetPosition(oldPos);
                                //maybe warning here or sound is enough? 
                                MyAudio.AddCue2D(MySoundCuesEnum.GuiEditorObjectMoveInvalid);
                            }

                        }
                        else
                            Debug.Assert(false);// no physical box in player ship
                    }
                }

                if (input.IsNewKeyPress(Keys.Space) && input.IsAnyShiftKeyPressed())
                {
                    if (CameraAttachedTo == MyCameraAttachedToEnum.Spectator)
                    {
                        MySmallShip playerShip = MySession.PlayerShip;

                        //Move Spectator to player ship position                        
                        MySpectator.Position = playerShip.GetPosition() +
                            ThirdPersonCameraDelta * playerShip.GetWorldRotation().Up +
                            ThirdPersonCameraDelta * -playerShip.GetWorldRotation().Forward;
                        MySpectator.Target = playerShip.GetPosition();
                    }
                }

                //  Save check point - allowed only for story editors
                // DISABLED, now done automatically
                //if (IsGameActive() && input.IsKeyPress(Keys.RightShift) && input.IsNewKeyPress(Keys.F2) &&
                //    MyClientServer.LoggedPlayer != null && MyClientServer.LoggedPlayer.GetCanAccessEditorForStory())
                //{
                //    MyGuiManager.AddScreen(new MyGuiScreenSaveCheckpoint());
                //}

                if (!MyModelsStatisticsConstants.GET_MODEL_STATISTICS_AUTOMATICALLY && input.IsNewKeyPress(Keys.F10) && input.IsAnyShiftKeyPressed())
                {
                    MyModels.LogUsageInformation();
                }
                if (!MyModelsStatisticsConstants.GET_MODEL_STATISTICS_AUTOMATICALLY && input.IsNewKeyPress(Keys.F10) && input.IsAnyAltKeyPressed())
                {
                    MyModels.CheckAllModels();
                    //MyModels.MergeLogFiles();
                }

                /*if (input.IsNewKeyPress(Keys.F10) && input.IsAnyCtrlKeyPressed() && !MyModelsStatisticsConstants.GET_MODEL_STATISTICS_AUTOMATICALLY)
                {
                    MyModelsStatisticsConstants.GET_MODEL_STATISTICS_AUTOMATICALLY = true;
                    if (MyModelsStatisticsConstants.MISSIONS_TO_GET_MODEL_STATISTICS_FROM.Length == 0)
                    {
                        int i = 0;
                        MyModelsStatisticsConstants.MISSIONS_TO_GET_MODEL_STATISTICS_FROM = new Missions.MyMissionID[Missions.MyMissions.Missions.Count];
                        foreach (var mission in MyMissions.Missions.Values.OfType<MyMission>().OrderBy(x => x.Name.ToString()))
                        {
                            if (i >= 12)
                                MyModelsStatisticsConstants.MISSIONS_TO_GET_MODEL_STATISTICS_FROM[i] = mission.ID;
                            i++;
                        }
                    }
                    GUI.MyGuiScreenMainMenu.StartMission(MyModelsStatisticsConstants.MISSIONS_TO_GET_MODEL_STATISTICS_FROM[0]);
                }*/

                // Voxel import
                if (MyFakes.VOXEL_IMPORT && input.IsNewKeyPress(Keys.PageUp))
                {
                    if (!input.IsAnyShiftKeyPressed())
                    {
                        MyVoxelMap voxelMap = new MyVoxelMap();
                        //{
                        //    // TODO: merge
                        //    //VoxelMaterial = MyMwcVoxelMaterialsEnum.Stone_01,
                        //    Size = MyFakes.VOXEL_IMPORT_SIZE
                        //};
                        voxelMap.Init(Vector3.Zero, MyFakes.VOXEL_IMPORT_SIZE, MyMwcVoxelMaterialsEnum.Stone_01);

                        MyModel model = new MyModel(MyFakes.VOXEL_IMPORT_MODEL, MyMeshDrawTechnique.MESH, MyModelsEnum.ExplosionDebrisVoxel);
                        model.LoadData();

                        MyVoxelImport.Run(voxelMap, model, MyVoxelImportOptions.KeepAspectRatio);
                        voxelMap.SaveVoxelContents(Path.Combine(MyMinerGame.Static.RootDirectory, "VoxelMaps", MyVoxelFiles.ExportFile + ".vox"));

                        // Reload sector
                        MyGuiScreenGamePlay.Static.Restart();
                    }
                    else
                    {
                        int[] sizes = new int[] { 64, 128, 256, 512 };

                        List<MyMwcVector3Int> voxelSizes = new List<MyMwcVector3Int>();

                        for (int x = 0; x < sizes.Length; x++)
                        {
                            int lo = Math.Max(x - 1, 0);
                            int hi = Math.Min(x + 2, sizes.Length);

                            for (int y = lo; y < hi; y++)
                            {
                                for (int z = lo; z < hi; z++)
                                {
                                    voxelSizes.Add(new MyMwcVector3Int(sizes[x], sizes[y], sizes[z]));
                                }
                            }
                        }

                        foreach (var size in voxelSizes)
                        {
                            MyVoxelMap voxelMap = new MyVoxelMap();
                            voxelMap.Init(Vector3.Zero, size, MyMwcVoxelMaterialsEnum.Stone_01);

                            MyVoxelImport.Fill(voxelMap);
                            voxelMap.SaveVoxelContents(Path.Combine(MyMinerGame.Static.RootDirectory, "VoxelMaps", String.Format("Cube_{0}x{1}x{2}.vox", size.X, size.Y, size.Z)));
                            MyEntities.Remove(voxelMap);
                            voxelMap.MarkForClose();
                            GC.Collect();
                        }

                        // Reload sector
                        MyGuiScreenGamePlay.Static.Restart();
                    }
                }


                if (input.IsNewKeyPress(Keys.L) && input.IsAnyCtrlKeyPressed() && input.IsAnyShiftKeyPressed())
                {
                    if (MyMissions.ActiveMission != null && MyMissions.ActiveMission.ActiveObjectives.Count > 0 && MyMissions.ActiveMission.ActiveObjectives[0].Location != null && MyMissions.ActiveMission.ActiveObjectives[0].Location.Entity != null)
                    {
                        MySpectator.Position = MyMissions.ActiveMission.ActiveObjectives[0].Location.Entity.GetPosition();

                    }
                }

                //  Start sun wind
                if (input.IsNewKeyPress(Keys.F3))
                {
                    //Multiplayer_EnterGame(new MyEventEnterGame() { PlayerInfo = new MyPlayerInfo() { DisplayName = "Test" } });
                    //MyDialogues.Play(Audio.Dialogues.MyDialogueEnum.TEST);
                    MyGlobalEvents.StartGlobalEvent(MyGlobalEventEnum.SunWind);
                    //MyGuiManager.AddScreen(new MyGuiScreenMission(MyMissions.ActiveMission));
                    //MySession.PlayerShip.DoDamage(0, 1000000, 0, MyDamageType.Unknown, MyAmmoType.Unknown, null);
                    //MyInventory.GenerateDebugInventoryItemsInfo();
                    //MyAmmoConstants.GenerateDebugAmmoTypeInfo();
                    if (MyFakes.ENABLE_DEBUG_INFLUENCE_SPHERES_SOUNDS)
                    {
                        if (input.IsKeyPress(Keys.LeftAlt))
                        {
                            MyInfluenceSphere.UpdateMaxVolume(false);
                        }
                        else if (input.IsKeyPress(Keys.RightAlt))
                        {
                            MyInfluenceSphere.UpdateMaxVolume(true);
                        }
                        else
                        {
                            MyInfluenceSphere.SwitchToNextSound(!input.IsAnyShiftKeyPressed());
                        }
                    }
                }

                //Set camera to player
                if (input.IsNewKeyPress(Keys.F6))
                {
                    TryChangeCameraAttachedTo(MyCameraAttachedToEnum.PlayerMinerShip);
                }

                //Set camera to following third person
                if (input.IsNewKeyPress(Keys.F7))
                {
                    TryChangeCameraAttachedTo(MyCameraAttachedToEnum.PlayerMinerShip_ThirdPersonFollowing);
                }

                //Set camera to spectator
                if (input.IsNewKeyPress(Keys.F8))//&& TryChangeCameraAttachedTo(MyCameraAttachedToEnum.Spectator))
                {
                    CameraAttachedTo = MyCameraAttachedToEnum.Spectator;
                    if (input.IsAnyCtrlKeyPressed())
                    {
                        MySpectator.Position = MySession.PlayerShip.GetPosition() + ThirdPersonCameraDelta;
                        MySpectator.Target = MySession.PlayerShip.GetPosition();
                    }
                }

                //Set camera to static third person
                if (input.IsNewKeyPress(Keys.F9) && TryChangeCameraAttachedTo(MyCameraAttachedToEnum.PlayerMinerShip_ThirdPersonStatic))
                {
                    if (input.IsAnyCtrlKeyPressed())
                    {
                        MySpectator.Position = MySession.PlayerShip.GetPosition() + ThirdPersonCameraDelta;
                        MySpectator.Target = MySession.PlayerShip.GetPosition();
                    }
                }

                if (input.IsNewKeyPress(Keys.F10) /*&& input.IsAnyCtrlKeyPressed()*/ && TryChangeCameraAttachedTo(MyCameraAttachedToEnum.BotMinerShip))
                {
                    //Find nearest bot and attach him
                    BoundingFrustum boundingFrustum = MyCamera.GetBoundingFrustum();
                    List<MyEntity> entities = new List<MyEntity>();
                    MyEntities.GetAllIntersectionWithBoundingFrustum_UNOPTIMIZED(ref boundingFrustum, entities);
                    MySmallShipBot closestBot = null;
                    foreach (MyEntity entity in entities)
                    {
                        if (entity is MySmallShipBot)
                        {
                            if (closestBot == null)
                            {
                                closestBot = entity as MySmallShipBot;
                                continue;
                            }

                            if (Vector3.Distance(MyCamera.Position, entity.GetPosition()) < Vector3.Distance(MyCamera.Position, closestBot.GetPosition()))
                            {
                                closestBot = entity as MySmallShipBot;
                            }
                        }
                    }
                    MyGuiScreenGamePlay.Static.ShipForSimpleTesting = closestBot;
                }
            }

            #endregion

            #region Game/editor keys

            if ((IsGameActive() || IsEditorActive()) && !MyEditorBase.IsEditorActive)
            {
                //  Turn reflector on/off
                if (input.IsNewGameControlPressed(MyGameControlEnums.HEADLIGHTS))
                {
                    if (IsControlledPlayerShip)
                    {
                        MySession.PlayerShip.Config.ReflectorLight.ChangeValueUp();
                    }

                    if (IsControlledDrone)
                    {
                        ControlledDrone.Config.ReflectorLight.ChangeValueUp();
                    }
                }

                //  Move and rotate player or camera
                MoveAndRotatePlayerOrCamera(input);
            }

            #endregion

            #region Game keys that work only when player is alive

            if (IsGameActive() && IsFlyThroughActive() == false && MySession.Static != null && MySession.Static.Player != null && !MySession.Static.Player.IsDead())
            {
                //  Open inventory
                if (input.IsNewGameControlPressed(MyGameControlEnums.INVENTORY))
                {
                    if (IsControlledPlayerShip && !MySession.PlayerShip.IsDead() && !MySession.PlayerShip.IsPilotDead())
                    {
                        MyGuiScreenInventoryType inventoryType;
                        if (IsTypeEditorGodMode(m_previousType) &&
                            MySession.PlayerShip.TradeDetector.GetNearestEntity() == null ||
                            Static.IsCheatEnabled(MyGameplayCheatsEnum.UNLIMITED_TRADING))
                        {
                            inventoryType = MyGuiScreenInventoryType.GodEditor;
                        }
                        else
                        {
                            inventoryType = MyGuiScreenInventoryType.Game;
                        }
                        if (!MyMultiplayerGameplay.IsRunning)
                        {
                            var inventoryScreen = MyGuiScreenInventoryManagerForGame.OpenInventory(inventoryType);
                            MyGuiManager.AddScreen(inventoryScreen);
                        }
                        else
                        {
                            OpenInventoryMultiplayer(inventoryType);
                        }
                    }
                }

                // Target locking
                if (input.IsNewGameControlPressed(MyGameControlEnums.PREV_TARGET))
                    MyEnemyTargeting.SwitchNextTarget(false);
                if (input.IsNewGameControlPressed(MyGameControlEnums.NEXT_TARGET))
                    MyEnemyTargeting.SwitchNextTarget(true);

                // Bot follow / hold position
                if (input.IsNewGameControlPressed(MyGameControlEnums.CHANGE_DRONE_MODE))
                {
                    if (IsControlledDrone)
                        ControlledDrone.HoldPosition = !ControlledDrone.HoldPosition;
                }

                if (input.IsNewGameControlPressed(MyGameControlEnums.QUICK_ZOOM)
                    && !MyCamera.Zoom.IsZooming()
                    && MyCamera.Zoom.GetZoomLevel() < 1.0f && !m_wheelControlMenu.Visible)
                {
                    m_quickZoomOut = true;
                    MyCamera.Zoom.SetZoom(MyCameraZoomOperationType.ZoomOut);
                }

                if (!m_quickZoomOut)
                {
                    if (input.IsGameControlPressed(MyGameControlEnums.QUICK_ZOOM))
                    {
                        MyCamera.Zoom.SetZoom(MyCameraZoomOperationType.ZoomIn);
                        m_quickZoomWasUsed = true;
                    }
                    else if (m_quickZoomWasUsed)
                    {
                        MyCamera.Zoom.SetZoom(MyCameraZoomOperationType.ZoomOut);
                    }
                }

                if (input.IsNewGameControlPressed(MyGameControlEnums.ZOOM_IN) ||
                    input.IsNewGameControlPressed(MyGameControlEnums.ZOOM_OUT))
                {
                    m_quickZoomOut = false;
                }

                if (!input.IsGameControlPressed(MyGameControlEnums.ZOOM_IN))
                {
                    if (input.IsGameControlPressed(MyGameControlEnums.ZOOM_OUT))
                    {
                        MyCamera.Zoom.SetZoom(MyCameraZoomOperationType.ZoomOut);
                        m_quickZoomWasUsed = false;
                    }
                    else if (!m_quickZoomWasUsed && !m_quickZoomOut)
                    {
                        MyCamera.Zoom.SetZoom(MyCameraZoomOperationType.NoZoom);
                    }
                }
                else if (input.IsGameControlPressed(MyGameControlEnums.ZOOM_IN))
                {
                    MyCamera.Zoom.SetZoom(MyCameraZoomOperationType.ZoomIn);
                    m_quickZoomWasUsed = false;
                }

                // Drone manipulation
                if (input.IsGameControlPressed(MyGameControlEnums.DRONE_DEPLOY))
                    DroneDeployKeyPressed();
                if (input.IsGameControlPressed(MyGameControlEnums.DRONE_CONTROL))
                    DroneControlKeyPressed();

                // Roll callbacks (movement is handled in MoveAndRotatePlayerOrCamera)
                if (input.IsNewGameControlPressed(MyGameControlEnums.ROLL_LEFT))
                {
                    OnRollLeftPressed();
                    MyScriptWrapper.RollLeftPressed();
                }
                if (input.IsNewGameControlPressed(MyGameControlEnums.ROLL_RIGHT))
                {
                    OnRollRightPressed();
                    MyScriptWrapper.RollRightPressed();
                }

                // Turn deceleration on/off
                if (input.IsNewGameControlPressed(MyGameControlEnums.MOVEMENT_SLOWDOWN))
                {
                    if (IsControlledPlayerShip && MySession.PlayerShip.Config.Engine.On)
                        MySession.PlayerShip.Config.MovementSlowdown.ChangeValueUp();
                }

                // Change headlight distance
                if (input.IsNewGameControlPressed(MyGameControlEnums.HEADLIGTHS_DISTANCE))
                {
                    if (IsControlledPlayerShip)
                        MySession.PlayerShip.Config.ReflectorLongRange.ChangeValueUp();
                }

                // Turn auto-leveling on/off
                if (input.IsNewGameControlPressed(MyGameControlEnums.AUTO_LEVEL))
                {
                    if (IsControlledPlayerShip && MySession.PlayerShip.Config.Engine.On)
                        MySession.PlayerShip.Config.AutoLeveling.ChangeValueUp();
                }

                // Turn secondary camera on/off
                if (MyFakes.ENABLE_BACK_CAMERA && !DisableBackCamera)
                {
                    if (input.IsNewGameControlPressed(MyGameControlEnums.REAR_CAM))
                    {
                        if (IsControlledPlayerShip)
                            ControlledShip.Config.BackCamera.ChangeValueUp();
                        if (IsControlledDrone)
                            ControlledDrone.Config.BackCamera.ChangeValueUp();
                    }
                }
                else
                {
                    MySession.PlayerShip.Config.BackCamera.SetOff();

                    if (IsControlledDrone)
                        ControlledDrone.Config.BackCamera.SetOff();
                }

                // Switch view - cockpit on/off, third person
                if (input.IsNewGameControlPressed(MyGameControlEnums.VIEW_MODE))
                {
                    if (IsControlledPlayerShip)
                        MySession.PlayerShip.Config.ViewMode.ChangeValueUp();
                }

                // Secondary camera and remote camera controls
                if (input.IsNewGameControlPressed(MyGameControlEnums.PREVIOUS_CAMERA))
                {
                    if (IsControlledPlayerShip)
                        MySession.PlayerShip.SelectPreviousSecondaryCamera();
                }

                if (input.IsNewGameControlPressed(MyGameControlEnums.NEXT_CAMERA))
                {
                    if (IsControlledPlayerShip)
                        MySession.PlayerShip.SelectNextSecondaryCamera();
                }

                HandleRemoteCameraInput(input);

                // Show GPS
                if (input.IsNewGameControlPressed(MyGameControlEnums.GPS) || (MyFakes.GPS_ALWAYS_ON && Math.Abs(MyHud.LastGPS - MyMinerGame.TotalGamePlayTimeInMilliseconds) > 500))
                {
                    MyHud.ShowGPSPathToNextObjective(true);
                    if (!m_showGPSNotification.IsDisappeared())
                        m_showGPSNotification.Disappear();
                }

                // Harvesting and drilling
                if (input.IsNewGameControlPressed(MyGameControlEnums.HARVEST))
                {
                    if (IsControlledPlayerShip && MySession.PlayerShip.IsEngineWorking() && MySession.PlayerShip.Fuel > 0)
                        MySession.PlayerShip.Weapons.FireHarvester();
                }

                if (input.IsGameControlPressed(MyGameControlEnums.DRILL))
                {
                    if (IsControlledPlayerShip && MySession.PlayerShip.IsEngineWorking() && MySession.PlayerShip.Fuel > 0)
                        MySession.PlayerShip.Weapons.FireDrill();
                }
            }

            #endregion

            #region Game keys that work only when player is alive and action menu is closed (e.g. keys that open a new menu)

            if (IsGameActive() && !m_wheelControlMenu.Visible && IsFlyThroughActive() == false && MySession.Static != null && MySession.Static.Player != null && !MySession.Static.Player.IsDead())
            {
                // Travel
                if (input.IsNewGameControlPressed(MyGameControlEnums.TRAVEL))
                {
                    bool canTravel = true;

                    if (m_type == MyGuiScreenGamePlayType.GAME_SANDBOX)
                    {
                        if (MyGuiScreenGamePlay.Static.GetPreviousGameType() != MyGuiScreenGamePlayType.EDITOR_STORY)
                            canTravel = false;
                    }
                    else if (m_type == MyGuiScreenGamePlayType.GAME_STORY || m_type == MyGuiScreenGamePlayType.GAME_MMO)
                    {
                        if (MySession.PlayerShip.GetNearMotherShipContainer() == null)
                            canTravel = false;
                        else
                            canTravel = CanTravel;
                    }

                    bool canSave = MyClientServer.LoggedPlayer.GetCanSave();
                    canTravel |= MyFakes.ENABLE_SOLAR_MAP;
                    canTravel &= canSave;

                    if (canTravel)
                    {
                        MyMwcSectorIdentifier sector = m_sectorIdentifier;
                        this.HideScreen();
                        MyGuiManager.AddScreen(new MyGuiScreenSolarSystemMap(this, sector));
                    }
                    else if (m_type == MyGuiScreenGamePlayType.GAME_STORY || m_type == MyGuiScreenGamePlayType.GAME_MMO)
                    {
                        if (!canSave)
                            MyGuiManager.AddScreen(new MyGuiScreenMessageBox(MyMessageBoxType.ERROR, MyTextsWrapperEnum.DemoUserCannotTravel, MyTextsWrapperEnum.SolarSystemMap, MyTextsWrapperEnum.Ok, null));
                        else if (CanTravel)
                            MyHudNotification.AddNotification(m_notificationYouHaveToBeNearMothership);
                        else
                            MyHudNotification.AddNotification(m_notificationUnableToLeaveSectorMission);
                    }
                }

                // Use / Hack / Take
                if (input.IsNewGameControlPressed(MyGameControlEnums.USE))
                {
                    bool isHandled = false;
                    // first handled are notifications
                    if (MyHudNotification.HasNotification(MyHudNotification.GetCurrentScreen()))
                        isHandled = MyHudNotification.HandleInput(input);

                    // second handled is take all event
                    if (!isHandled)
                        isHandled = TakeAllItems();

                    // third handled is hacking etc
                    if (!isHandled)
                    {
                        MySmallShip hacker = ControlledDrone ?? MySession.PlayerShip;
                        IMyUseableEntity detectedEntityToUse = hacker.UseableEntityDetector.GetNearestEntity() as IMyUseableEntity;

                        if (ControlledLargeWeapon != null && TryChangeCameraAttachedTo(MyCameraAttachedToEnum.PlayerMinerShip))
                            ReleaseControlOfLargeWeapon();

                        if (ControlledCamera != null)
                            ReleaseControlOfCamera();
                        else if (detectedEntityToUse != null)
                        {
                            MySmallShipInteractionActionEnum detectedAction = (MySmallShipInteractionActionEnum)hacker.UseableEntityDetector.GetNearestEntityCriterias();
                            if (detectedAction == MySmallShipInteractionActionEnum.Use)
                                detectedEntityToUse.Use(hacker);
                            else if (detectedAction == MySmallShipInteractionActionEnum.Hack)
                                hacker.HackingTool.Hack(detectedEntityToUse);
                        }
                        else
                            MyScriptWrapper.UseKeyPressed();
                    }
                }
                       /*  Journal removed
                // Journal
                if (input.IsNewGameControlPressed(MyGameControlEnums.MISSION_DIALOG) && (GetGameType() == MyGuiScreenGamePlayType.GAME_STORY || GetGameType() == MyGuiScreenGamePlayType.GAME_MMO))
                {
                    if (!MyMissions.RequestMissionDialog())
                        MyGuiManager.AddScreen(new MyGuiScreenJournal(MySession.Static.EventLog));
                }        */

                // Chat, multiplayer statistics
                // TODO: prevent dev keys universally, not based on the default mapping
#if !RENDER_PROFILING
                if (MyGuiManager.IsScreenTopMostNonDebug(this))
                {
                    if (input.IsNewGameControlPressed(MyGameControlEnums.CHAT)/* && MyMultiplayerGameplay.IsRunning && (MyMultiplayerGameplay.IsSandBox() || (MyMultiplayerGameplay.IsStory() && MyMultiplayerGameplay.OtherPlayersConnected))*/) //only in deathmatch (all the time) or coop (at least one other player)
                    {
                        MyGuiManager.AddScreen(new MyGuiScreenGameChat(input.IsAnyShiftKeyPressed()));
                    }
                    if (input.IsNewGameControlPressed(MyGameControlEnums.SCORE) && MyMultiplayerGameplay.IsRunning && (MyMultiplayerGameplay.IsSandBox() || (MyMultiplayerGameplay.IsStory() && MyMultiplayerGameplay.OtherPlayersConnected))) //only in deathmatch (all the time) or coop (at least one other player)
                    {
                        MyGuiManager.AddScreen(new MyGuiScreenGameScore());
                    }
                }
#endif
                // Shooting
                // we can be dead in this moment

                if (MyFakes.CUBE_EDITOR && MySession.PlayerShip != null && input.IsNewGameControlPressed(MyGameControlEnums.QUICK_ZOOM))
                    MySession.PlayerShip.CubeBuilder.BuilderActive = !MySession.PlayerShip.CubeBuilder.BuilderActive;

                if (MySession.PlayerShip != null && MySession.PlayerShip.CubeBuilder.BuilderActive)
                {
                    if (input.IsNewGameControlPressed(MyGameControlEnums.FIRE_PRIMARY))
                        MySession.PlayerShip.CubeBuilder.Add();
                    if (input.IsNewGameControlPressed(MyGameControlEnums.FIRE_SECONDARY))
                        MySession.PlayerShip.CubeBuilder.Remove();
                }
                else if (m_handleInputMouseKeysReleased &&
                    (!IsSelectAmmoVisible()) &&
                    (!m_wheelControlMenu.Visible) &&
                    MySession.PlayerShip != null &&
                    !MySession.PlayerShip.IsDead() &&
                    IsFireKeyEnabled())
                {
                    switch (CameraAttachedTo)
                    {
                        case MyCameraAttachedToEnum.PlayerMinerShip_ThirdPersonDynamic:
                        case MyCameraAttachedToEnum.Spectator:
                        case MyCameraAttachedToEnum.PlayerMinerShip_ThirdPersonStatic:
                        case MyCameraAttachedToEnum.PlayerMinerShip_ThirdPersonFollowing:
                        case MyCameraAttachedToEnum.PlayerMinerShip:
                            if (!input.IsAnyCtrlKeyPressed() || CameraAttachedTo == MyCameraAttachedToEnum.PlayerMinerShip)
                            {
                                MySmallShip playerShip = MySession.PlayerShip;

                                if (playerShip.IsEngineWorking())
                                {
                                    if (input.IsGameControlPressed(MyGameControlEnums.FIRE_PRIMARY)) playerShip.Weapons.Fire(MyMwcObjectBuilder_FireKeyEnum.Primary);
                                    if (input.IsGameControlPressed(MyGameControlEnums.FIRE_SECONDARY))
                                    {
                                        // TODO: prevent dev keys universally, not based on the default mapping
#if !GPU_PROFILING
                                        playerShip.Weapons.Fire(MyMwcObjectBuilder_FireKeyEnum.Secondary);
#endif
                                    }
                                    if (input.IsGameControlPressed(MyGameControlEnums.FIRE_THIRD)) playerShip.Weapons.Fire(MyMwcObjectBuilder_FireKeyEnum.Third);
                                    if (input.IsGameControlPressed(MyGameControlEnums.FIRE_FOURTH)) playerShip.Weapons.Fire(MyMwcObjectBuilder_FireKeyEnum.Fourth);
                                    if (input.IsGameControlPressed(MyGameControlEnums.FIRE_FIFTH)) playerShip.Weapons.Fire(MyMwcObjectBuilder_FireKeyEnum.Fifth);
                                    if (input.IsNewGameControlPressed(MyGameControlEnums.WEAPON_SPECIAL)) playerShip.InvokeAmmoSpecialFunction();
                                    if (input.IsGameControlPressed(MyGameControlEnums.FIRE_HOLOGRAM_FRONT)) playerShip.Weapons.Fire(MyMwcObjectBuilder_FireKeyEnum.HologramFront);
                                    if (input.IsGameControlPressed(MyGameControlEnums.FIRE_HOLOGRAM_BACK)) playerShip.Weapons.Fire(MyMwcObjectBuilder_FireKeyEnum.HologramBack);
                                    if (input.IsGameControlPressed(MyGameControlEnums.FIRE_BASIC_MINE_FRONT)) playerShip.Weapons.Fire(MyMwcObjectBuilder_FireKeyEnum.BasicMineFront);
                                    if (input.IsGameControlPressed(MyGameControlEnums.FIRE_BASIC_MINE_BACK)) playerShip.Weapons.Fire(MyMwcObjectBuilder_FireKeyEnum.BasicMineBack);
                                    if (input.IsGameControlPressed(MyGameControlEnums.FIRE_SMART_MINE_FRONT)) playerShip.Weapons.Fire(MyMwcObjectBuilder_FireKeyEnum.SmartMineFront);
                                    if (input.IsGameControlPressed(MyGameControlEnums.FIRE_SMART_MINE_BACK)) playerShip.Weapons.Fire(MyMwcObjectBuilder_FireKeyEnum.SmartMineBack);
                                    if (input.IsGameControlPressed(MyGameControlEnums.FIRE_FLASH_BOMB_FRONT)) playerShip.Weapons.Fire(MyMwcObjectBuilder_FireKeyEnum.FlashBombFront);
                                    if (input.IsGameControlPressed(MyGameControlEnums.FIRE_FLASH_BOMB_BACK)) playerShip.Weapons.Fire(MyMwcObjectBuilder_FireKeyEnum.FlashBombBack);
                                    if (input.IsGameControlPressed(MyGameControlEnums.FIRE_DECOY_FLARE_FRONT)) playerShip.Weapons.Fire(MyMwcObjectBuilder_FireKeyEnum.DecoyFlareFront);
                                    if (input.IsGameControlPressed(MyGameControlEnums.FIRE_DECOY_FLARE_BACK)) playerShip.Weapons.Fire(MyMwcObjectBuilder_FireKeyEnum.DecoyFlareBack);
                                    if (input.IsGameControlPressed(MyGameControlEnums.FIRE_SMOKE_BOMB_FRONT)) playerShip.Weapons.Fire(MyMwcObjectBuilder_FireKeyEnum.SmokeBombFront);
                                    if (input.IsGameControlPressed(MyGameControlEnums.FIRE_SMOKE_BOMB_BACK)) playerShip.Weapons.Fire(MyMwcObjectBuilder_FireKeyEnum.SmokeBombBack);
                                }
                            }
                            break;
                        case MyCameraAttachedToEnum.Drone:
                            if (input.IsGameControlPressed(MyGameControlEnums.FIRE_PRIMARY) ||
                                input.IsGameControlPressed(MyGameControlEnums.FIRE_SECONDARY) ||
                                input.IsGameControlPressed(MyGameControlEnums.FIRE_THIRD) ||
                                input.IsGameControlPressed(MyGameControlEnums.FIRE_FOURTH) ||
                                input.IsGameControlPressed(MyGameControlEnums.FIRE_FIFTH))
                            {
                                ControlledDrone.Fire();
                                DisableFireKey(new TimeSpan(0, 0, 1));
                            }
                            break;
                        case MyCameraAttachedToEnum.LargeWeapon:
                            if (input.IsGameControlPressed(MyGameControlEnums.FIRE_PRIMARY) ||
                                input.IsGameControlPressed(MyGameControlEnums.FIRE_SECONDARY) ||
                                input.IsGameControlPressed(MyGameControlEnums.FIRE_THIRD) ||
                                input.IsGameControlPressed(MyGameControlEnums.FIRE_FOURTH) ||
                                input.IsGameControlPressed(MyGameControlEnums.FIRE_FIFTH))
                            {
                                ControlledLargeWeapon.Fire();
                            }
                            else
                            {
                                ControlledLargeWeapon.StopFire();
                            }
                            break;
                    }
                }
            }

            #endregion

            #region Game keys that work all the time (even when player is dead)

            if (IsGameActive())
            {
                // Open cheat screen
                if (input.IsNewKeyPress(Keys.F1) && input.IsAnyCtrlKeyPressed())
                {
                    MyGuiManager.AddScreen(new MyGuiScreenCheats());
                }

                // Open help screen
                if (input.IsNewKeyPress(Keys.F1) && !input.IsAnyCtrlKeyPressed())
                {
                    MyGuiManager.AddScreen(new MyGuiScreenHelp());
                }

                if (IsControlledPlayerShip)
                {
                    m_selectAmmoMenu.HandleInput(input, true, true, receivedFocusInThisUpdate);
                    m_wheelControlMenu.HandleInput(input, true, true, receivedFocusInThisUpdate);
                }

                // DrawMouseCursor = m_wheelControlMenu.Visible;

                /*  //duplicated in if IsGameReady
           if (IsGameActive()) // enable cursor drawing if we have ammo selection opened
           {
               DrawMouseCursor = m_selectAmmoMenu.IsEnabled && m_selectAmmoMenu.Visible;
           } */

                MyDebugConsole.GetInstance().Update(MyDebugSystem.Game, input);
            }

            #endregion

            #region Editor keys

            if (IsEditorActive())
            {
                // Open ship customization screen
                if (input.IsNewGameControlPressed(MyGameControlEnums.INVENTORY) && !input.IsAnyCtrlKeyPressed())
                {
                    if (MyFakes.SHOW_NEW_INVENTORY_SCREEN)
                    {
                        MyGuiScreenInventoryType inventoryType = !IsIngameEditorActive() || Static.IsCheatEnabled(MyGameplayCheatsEnum.UNLIMITED_TRADING)
                                                                        ? MyGuiScreenInventoryType.GodEditor
                                                                        : MyGuiScreenInventoryType.InGameEditor;
                        MyGuiManager.AddScreen(MyGuiScreenInventoryManagerForGame.OpenInventory(inventoryType));
                    }
                }

                MyEditor.Static.HandleInput(input, !AnyControlContainsMouse());
                MyDebugConsole.GetInstance().Update(MyDebugSystem.Editor, input);
            }

            #endregion
        }