public MyGuiScreenLoading(MyGuiScreenGamePlay screenToLoad, MyGuiScreenGamePlay screenToUnload, MyTexture2D textureFromConstructor)
            : base(Vector2.Zero, null, null)
        {
            MyLoadingPerformance.Instance.StartTiming();

            System.Diagnostics.Debug.Assert(Static == null);
            Static = this;

            m_screenToLoad         = screenToLoad;
            m_screenToUnload       = screenToUnload;
            m_closeOnEsc           = false;
            DrawMouseCursor        = false;
            m_loadInDrawFinished   = false;
            m_drawEvenWithoutFocus = true;
            m_currentQuoteOfTheDay = MyQuoteOfTheDay.GetRandomQuote();

            Vector2 loadingTextSize = MyGuiManager.GetNormalizedSize(MyGuiManager.GetFontMinerWarsBlue(),
                                                                     MyTextsWrapper.Get(MyTextsWrapperEnum.LoadingPleaseWait), MyGuiConstants.LOADING_PLEASE_WAIT_SCALE);

            m_rotatingWheelTexture = MyGuiManager.GetLoadingTexture();
            Controls.Add(new MyGuiControlRotatingWheel(this, MyGuiConstants.LOADING_PLEASE_WAIT_POSITION - new Vector2(0, 0.075f + loadingTextSize.Y),
                                                       MyGuiConstants.ROTATING_WHEEL_COLOR, MyGuiConstants.ROTATING_WHEEL_DEFAULT_SCALE, MyGuiDrawAlignEnum.HORISONTAL_CENTER_AND_VERTICAL_CENTER, m_rotatingWheelTexture));
            m_backgroundTextureFromConstructor = textureFromConstructor;

            m_loadFinished = false;

            if (m_screenToLoad != null)
            {
                MyMinerGame.IsGameReady = false;
            }
        }
        public MyGuiScreenLoading(MyGuiScreenGamePlay screenToLoad, MyGuiScreenGamePlay screenToUnload, MyTexture2D textureFromConstructor)
            : base(Vector2.Zero, null, null)
        {
            MyLoadingPerformance.Instance.StartTiming();

            System.Diagnostics.Debug.Assert(Static == null);
            Static = this;

            m_screenToLoad = screenToLoad;
            m_screenToUnload = screenToUnload;
            m_closeOnEsc = false;
            DrawMouseCursor = false;
            m_loadInDrawFinished = false;
            m_drawEvenWithoutFocus = true;
            m_currentQuoteOfTheDay = MyQuoteOfTheDay.GetRandomQuote();
            
            Vector2 loadingTextSize = MyGuiManager.GetNormalizedSize(MyGuiManager.GetFontMinerWarsBlue(),
                MyTextsWrapper.Get(MyTextsWrapperEnum.LoadingPleaseWait), MyGuiConstants.LOADING_PLEASE_WAIT_SCALE);
            m_rotatingWheelTexture = MyGuiManager.GetLoadingTexture();
            Controls.Add(new MyGuiControlRotatingWheel(this, MyGuiConstants.LOADING_PLEASE_WAIT_POSITION - new Vector2(0, 0.075f + loadingTextSize.Y),
                MyGuiConstants.ROTATING_WHEEL_COLOR, MyGuiConstants.ROTATING_WHEEL_DEFAULT_SCALE, MyGuiDrawAlignEnum.HORISONTAL_CENTER_AND_VERTICAL_CENTER, m_rotatingWheelTexture));
            m_backgroundTextureFromConstructor = textureFromConstructor;

            m_loadFinished = false;
            
            if (m_screenToLoad != null)
            {
                MyMinerGame.IsGameReady = false;
            }
        }
        public static MyGuiScreenStartSessionProgress CurrentScreen = null;    //  This is always filled with reference to actual instance of this scree. If there isn't, it's null.


        public MyGuiScreenStartSessionProgress(MyMwcStartSessionRequestTypeEnum sessionType, MyTextsWrapperEnum progressText, MyMwcSectorIdentifier?sectorIdentifier, MyGameplayDifficultyEnum difficulty, string checkpointName, MyGuiScreenBase closeAfter) :
            base(progressText, false)
        {
            // TODO: Not ready yet
            //Debug.Assert(sessionType != MyMwcStartSessionRequestTypeEnum.NEW_STORY && sessionType != MyMwcStartSessionRequestTypeEnum.LOAD_CHECKPOINT, "Invalid operation, call OndrejP");

            m_sectorIdentifier    = sectorIdentifier;
            m_sessionType         = sessionType;
            m_backgroundFadeColor = MyGuiConstants.SCREEN_BACKGROUND_FADE_BLANK_DARK_PROGRESS_SCREEN;
            m_closeAfter          = closeAfter;
            m_difficulty          = difficulty;
            m_checkpointName      = checkpointName;
            CurrentScreen         = this;

            OnSuccessEnter = new Action <MyGuiScreenGamePlayType, MyMwcStartSessionRequestTypeEnum, MyMwcObjectBuilder_Checkpoint>((screenType, sessType, checkpoint) =>
            {
                var newGameplayScreen = new MyGuiScreenGamePlay(screenType, null, checkpoint.CurrentSector, checkpoint.SectorObjectBuilder.Version, sessType);
                var loadScreen        = new MyGuiScreenLoading(newGameplayScreen, MyGuiScreenGamePlay.Static);

                if (sessType == MyMwcStartSessionRequestTypeEnum.NEW_STORY)
                {
                    loadScreen.AddEnterSectorResponse(checkpoint, MyMissionID.EAC_SURVEY_SITE);
                }
                else
                {
                    loadScreen.AddEnterSectorResponse(checkpoint, null);
                }

                MyGuiManager.AddScreen(loadScreen);
            });
        }
        public static MyGuiScreenStartSessionProgress CurrentScreen = null;    //  This is always filled with reference to actual instance of this scree. If there isn't, it's null.


        public MyGuiScreenStartSessionProgress(MyMwcStartSessionRequestTypeEnum sessionType,  MyTextsWrapperEnum progressText, MyMwcSectorIdentifier? sectorIdentifier, MyGameplayDifficultyEnum difficulty, string checkpointName, MyGuiScreenBase closeAfter) : 
            base(progressText, false)
        {
            // TODO: Not ready yet
            //Debug.Assert(sessionType != MyMwcStartSessionRequestTypeEnum.NEW_STORY && sessionType != MyMwcStartSessionRequestTypeEnum.LOAD_CHECKPOINT, "Invalid operation, call OndrejP");

            m_sectorIdentifier = sectorIdentifier;
            m_sessionType = sessionType;
            m_backgroundFadeColor = MyGuiConstants.SCREEN_BACKGROUND_FADE_BLANK_DARK_PROGRESS_SCREEN;
            m_closeAfter = closeAfter;
            m_difficulty = difficulty;
            m_checkpointName = checkpointName;
            CurrentScreen = this;

            OnSuccessEnter = new Action<MyGuiScreenGamePlayType, MyMwcStartSessionRequestTypeEnum, MyMwcObjectBuilder_Checkpoint>((screenType, sessType, checkpoint) =>
            {
                var newGameplayScreen = new MyGuiScreenGamePlay(screenType, null, checkpoint.CurrentSector, checkpoint.SectorObjectBuilder.Version, sessType);
                var loadScreen = new MyGuiScreenLoading(newGameplayScreen, MyGuiScreenGamePlay.Static);

                if (sessType == MyMwcStartSessionRequestTypeEnum.NEW_STORY)
                    loadScreen.AddEnterSectorResponse(checkpoint, MyMissionID.EAC_SURVEY_SITE);
                else
                    loadScreen.AddEnterSectorResponse(checkpoint, null);

                MyGuiManager.AddScreen(loadScreen);
            });
        }
        public override void UnloadContent()
        {
            AppCode.Game.Render.MyRender.GetRenderProfiler().StartProfilingBlock("MyGuiScreenLoading::UnloadContent");
            //  This is just for case that whole application is quiting after Alt+F4 or something
            //  Don't try to unload content in that thread or something - we don't know in what state it is. Just abort it.

            if (m_drawLoadingThread != null && m_drawLoadingThread.IsAlive == true)
            {
                m_backgroundThreadExit.Set();
                m_drawLoadingThread.Join();
            }

            if (m_backgroundScreenTexture != null)
            {
                MyTextureManager.UnloadTexture(m_backgroundScreenTexture);
            }
            if (m_backgroundTextureFromConstructor != null)
            {
                MyTextureManager.UnloadTexture(m_backgroundTextureFromConstructor);
            }
            if (m_backgroundScreenTexture != null)
            {
                MyTextureManager.UnloadTexture(m_rotatingWheelTexture);
            }
            if (m_currentSectorDescription != null && m_currentSectorDescription.Item2 != null && m_currentSectorDescription.Item2.Item3 != null)
            {
                MyTextureManager.UnloadTexture(m_currentSectorDescription.Item2.Item3);
            }


            if (m_screenToLoad != null && !m_loadFinished && m_loadInDrawFinished)
            {
                //  Call unload because there might be running precalc threads and we need to stop them
                //m_screenToLoad.UnloadObjects();
                m_screenToLoad.UnloadContent();
                m_screenToLoad.UnloadData();

                //m_screenToLoad.UnloadData();
                m_screenToLoad = null;
            }


            if (m_screenToLoad != null && !m_loadInDrawFinished)
            {
                m_screenToLoad.UnloadContent();
            }


            base.UnloadContent();

            System.Diagnostics.Debug.Assert(Static == this);
            Static = null;

            AppCode.Game.Render.MyRender.GetRenderProfiler().EndProfilingBlock();
        }
        public override void UnloadContent()
        {
            AppCode.Game.Render.MyRender.GetRenderProfiler().StartProfilingBlock("MyGuiScreenLoading::UnloadContent");
            //  This is just for case that whole application is quiting after Alt+F4 or something
            //  Don't try to unload content in that thread or something - we don't know in what state it is. Just abort it.

            if (m_drawLoadingThread != null && m_drawLoadingThread.IsAlive == true)
            {
                m_backgroundThreadExit.Set();
                m_drawLoadingThread.Join();
            }

            if (m_backgroundScreenTexture != null) MyTextureManager.UnloadTexture(m_backgroundScreenTexture);
            if (m_backgroundTextureFromConstructor!=null) MyTextureManager.UnloadTexture(m_backgroundTextureFromConstructor);
            if (m_backgroundScreenTexture!=null) MyTextureManager.UnloadTexture(m_rotatingWheelTexture);
            if (m_currentSectorDescription != null && m_currentSectorDescription.Item2 != null && m_currentSectorDescription.Item2.Item3 != null) MyTextureManager.UnloadTexture(m_currentSectorDescription.Item2.Item3);


            if (m_screenToLoad != null && !m_loadFinished && m_loadInDrawFinished)
            {
                //  Call unload because there might be running precalc threads and we need to stop them
                //m_screenToLoad.UnloadObjects();
                m_screenToLoad.UnloadContent();
                m_screenToLoad.UnloadData();
               
                //m_screenToLoad.UnloadData();
                m_screenToLoad = null;
            }

            
            if (m_screenToLoad != null && !m_loadInDrawFinished)
            {
                m_screenToLoad.UnloadContent();
            }
            

            base.UnloadContent();

            System.Diagnostics.Debug.Assert(Static == this);
            Static = null;

            AppCode.Game.Render.MyRender.GetRenderProfiler().EndProfilingBlock();
        }
        public void OnEditorClick(MyGuiControlButton sender)
        {
            if (MyClientServer.LoggedPlayer == null || MyClientServer.LoggedPlayer.GetCanAccessEditorForStory() || MyClientServer.LoggedPlayer.GetCanAccessEditorForMMO())
            {
                AddLoginScreen(new MyGuiScreenSelectEditor(this));
            }
            else if (!MySteam.IsActive && !MyClientServer.IsMwAccount) // Demo user...generate sector 0, 0, 0. User cant save.
            {
                MyGuiManager.CloseAllScreensNowExcept(MyGuiScreenGamePlay.Static);

                MySession.Static = new MySandboxSession();
                MySession.Static.Init();

                var sector = new MyMwcSectorIdentifier(MyMwcSectorTypeEnum.SANDBOX, MyPlayerLocal.OFFLINE_MODE_USERID, new CommonLIB.AppCode.Utils.MyMwcVector3Int(0, 0, 0), String.Empty);
                var newGameplayScreen = new MyGuiScreenGamePlay(MyGuiScreenGamePlayType.EDITOR_SANDBOX, null, sector, 0, MyMwcStartSessionRequestTypeEnum.EDITOR_SANDBOX);
                var loadScreen = new MyGuiScreenLoading(newGameplayScreen, MyGuiScreenGamePlay.Static);

                var checkpoint = new MyMwcObjectBuilder_Checkpoint();
                checkpoint.CurrentSector = sector;
                checkpoint.SectorObjectBuilder = new MyMwcObjectBuilder_Sector();
                checkpoint.SectorObjectBuilder.FromGenerator = true;
                checkpoint.SectorObjectBuilder.Position = sector.Position;
                checkpoint.SessionObjectBuilder = new MyMwcObjectBuilder_Session(MyGameplayDifficultyEnum.EASY);

                loadScreen.AddEnterSectorResponse(checkpoint, null);

                MyGuiManager.AddScreen(loadScreen);
            }
            else
            {
                MyMwcSectorTypeEnum sectorType = MyMwcClientServer.GetSectorTypeFromSessionType(MyMwcStartSessionRequestTypeEnum.EDITOR_SANDBOX);
                AddLoginScreen(
                    new MyGuiScreenLoadSectorIdentifiersProgress(sectorType, false, new MyGuiScreenEnterSectorMap(this, MyMwcStartSessionRequestTypeEnum.EDITOR_SANDBOX, MyTextsWrapperEnum.StartEditorInProgressPleaseWait, MyConfig.LastSandboxSector)));
            }
        }
        // Restarts gameplay (loads last checkpoint or reloads sandbox)
        // Be careful, this is used for Gameover screen too!
        public void Restart()
        {
            MyGuiManager.CloseAllScreensExcept(MyGuiScreenGamePlay.Static);

            if (MyGuiScreenGamePlay.Static.GetGameType() == MyGuiScreenGamePlayType.GAME_STORY)
            {
                MySession.StartLastCheckpoint();
            }
            else if (MyGuiScreenGamePlay.Static.GetGameType() == MyGuiScreenGamePlayType.GAME_SANDBOX)
            {
                var sectorIdentifier = MyGuiScreenGamePlay.Static.GetSectorIdentifier();
                MySession.StartSandbox(sectorIdentifier.Position, sectorIdentifier.UserId);
            }
            else if (MyGuiScreenGamePlay.Static.IsEditorActive())
            {
                // The "old way" in future should be on MySession
                CloseScreenNow();

                Action<MyMwcObjectBuilder_Checkpoint> enterSuccessAction = new Action<MyMwcObjectBuilder_Checkpoint>((checkpoint) =>
                {
                    var loadScreen = new MyGuiScreenLoading(new MyGuiScreenGamePlay(m_type, m_previousType, checkpoint.CurrentSector, checkpoint.SectorObjectBuilder.Version, m_sessionType.Value), MyGuiScreenGamePlay.Static);
                    loadScreen.AnnounceLeaveToServer = true;
                    loadScreen.LeaveSectorReason = MyMwcLeaveSectorReasonEnum.RELOAD;

                    loadScreen.AddEnterSectorResponse(checkpoint, null);
                    MyGuiManager.AddScreen(loadScreen);
                });
                MyMissions.Unload();
                MyGuiManager.AddScreen(new MyGuiScreenLoadCheckpointProgress(m_sectorIdentifier.SectorType, MyMwcSessionStateEnum.EDITOR, m_sectorIdentifier.UserId, m_sectorIdentifier.Position, null, enterSuccessAction));
            }
        }
        public override bool Draw(float backgroundFadeAlpha)
        {


            int drawBlock = -1;
            MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().StartProfilingBlock("MyGuiScreenGamePlay::Draw", ref drawBlock);

            MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().StartProfilingBlock("Autobuild test");

            AutobuildTest();


            //  We start/restart all batched objects in our sprite batch because in game-play screen we do a lot of stuff that's not compatible with it
            MyGuiManager.EndSpriteBatch();

            MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().StartNextBlock("Editor load");

            ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            //  Draw Editor model
            ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            if (IsEditorActive())
            {
                MyEditor.Static.LoadInDraw();
            }

            MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().StartNextBlock("Camera reset");

            ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            //  Draw forward
            ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            MyPerformanceCounter.PerCameraDraw.Reset();

#if HOMEKEY_RESET_ENVMAP
            // Home key to manually refresh environment map
            if (Keyboard.GetState().IsKeyDown(Keys.Home))
            {
                MyEnvironmentMap.Reset();
            }
#endif

            //While getting cell, there must not be any other thread running because this voxel can be loading at same time
            System.Diagnostics.Debug.Assert(!(MyEditor.Static != null && MyEditor.Static.IsBackgroundWorkThreadAlive() && MyRender.Enabled));

            MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().StartNextBlock("m_firstDrawCall == FIRST_TOTAL_DELAY");

            if (m_firstDrawCall == FIRST_TOTAL_DELAY)
            {
                MyMwcLog.WriteLine("First draw call - before render");

                MyRender.GetRenderProfiler().StartProfilingBlock("Load meteor wind");
                MyMeteorWind.LoadInDraw();
                MyRender.GetRenderProfiler().EndProfilingBlock();

                MyRender.GetRenderProfiler().StartProfilingBlock("Preload entities");
                //                MyTextureManager.DbgUpdateStats();
                MyTextureManager.OverrideLoadingMode = LoadingMode.Immediate;
                MyRender.PreloadEntitiesInRadius(MyRenderConstants.RenderQualityProfile.LodTransitionDistanceFar, MyGuiScreenGamePlay.Static.DrawLoadAnimation);
                MyRender.GetRenderProfiler().EndProfilingBlock();

                MyRender.GetRenderProfiler().StartProfilingBlock("Preload ship");
                MySession.PlayerShip.GetShipCockpit(); //Reload
                MySession.PlayerShip.GetShipCockpitGlass(); //Reload
                MyRender.GetRenderProfiler().EndProfilingBlock();

                if (IsEditorActive())
                {
                    MyRender.GetRenderProfiler().StartProfilingBlock("Prefab helper icons");
                    MyGuiObjectBuilderHelpers.UpdatePrefabHelperIcons();
                    MyRender.GetRenderProfiler().EndProfilingBlock();
                }

                bool foundCache = false;
                MyRender.GetRenderProfiler().StartProfilingBlock("MyLocalVoxelTrianglesCache.LoadAllVoxels");
                if (MyFakes.ENABLE_VOXEL_TRIANGLE_CACHING)
                {
                    foundCache = MyLocalVoxelTrianglesCache.LoadAllVoxels();
                }
                else
                {
                    foundCache = true;
                }
                MyRender.GetRenderProfiler().EndProfilingBlock();

                MyRender.GetRenderProfiler().StartProfilingBlock("MyVoxelMaps.RecalcVoxelMaps");
                MyVoxelMaps.RecalcVoxelMaps();
                MyRender.GetRenderProfiler().EndProfilingBlock();

                if (MyFakes.ENABLE_VOXEL_TRIANGLE_CACHING)
                {
                    if (!foundCache)
                    {
                        MyRender.GetRenderProfiler().StartProfilingBlock("MyLocalVoxelTrianglesCache.SaveAllVoxels");
                        MyLocalVoxelTrianglesCache.SaveAllVoxels();
                        MyRender.GetRenderProfiler().EndProfilingBlock();
                    }
                }

                MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().StartProfilingBlock("MyRender.PreloadTextures");
                MyVoxelMaterials.MarkAllAsUnused(); // Mark all as unused
                MyRender.PreloadTexturesInRadius(MyMwcSectorConstants.SECTOR_SIZE); // Used voxel textures will be marked as used
                MyVoxelMaterials.UnloadUnused(); // Unload all unused (static asteroid voxel textures won't be unused, because they are referenced)
                MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().EndProfilingBlock();

            }

            MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().StartNextBlock("MyEnvironmentMap");

            if (!MyRenderConstants.RenderQualityProfile.ForwardRender)
            {
                MyRender.GetRenderProfiler().StartProfilingBlock("MyEnvironmentMap.Update");
                MyEnvironmentMap.Update();
                MyRender.GetRenderProfiler().EndProfilingBlock();
            }

            MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().StartNextBlock("secondary camera");

            bool drawSecondaryCameraIndicators =
                MySession.PlayerShip != null &&
                IsGameActive() &&
                DrawHud &&
                !MyRenderConstants.RenderQualityProfile.ForwardRender &&
                (IsControlledPlayerShip || IsControlledDrone);

            bool shipSecondaryCamera = IsControlledPlayerShip && ControlledShip.Config.BackCamera.On;
            bool droneSecondaryCamera = IsControlledDrone && ControlledDrone.Config.BackCamera.On;

            bool drawSecondaryCamera =
                drawSecondaryCameraIndicators &&
                (shipSecondaryCamera || droneSecondaryCamera);

            if (drawSecondaryCamera)
            {
                MyRender.GetRenderProfiler().StartProfilingBlock("MySecondaryCamera.Render");
                MySecondaryCamera.Instance.Render();
                MyRender.GetRenderProfiler().EndProfilingBlock();
            }


            MyCamera.EnableForward();

            MyRender.EnableLightsRuntime = ((IsEditorActive() && MyEditor.EnableLightsInEditor) || !IsEditorActive()) && MyGuiScreenDebugRenderLights.EnableRenderLights;

            // for drone, use smaller near plane distance
            var useSecondaryRenderSetup = IsControlledDrone;
            if (useSecondaryRenderSetup)
            {
                m_secondarySetup.CallerID = MyRenderCallerEnum.Main;
                m_secondarySetup.Fov = MyCamera.FovWithZoom;
                m_secondarySetup.AspectRatio = MyCamera.AspectRatio;
                m_secondarySetup.ProjectionMatrix = Matrix.CreatePerspectiveFieldOfView(
                    m_secondarySetup.Fov.Value,
                    m_secondarySetup.AspectRatio.Value,
                    MyDroneConstants.NEAR_PLANE_DISTANCE,
                    MyCamera.FAR_PLANE_DISTANCE);
                MyRender.PushRenderSetup(m_secondarySetup);
            }

            MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().StartNextBlock("Main render");

            MyRender.Draw();

            if (useSecondaryRenderSetup)
            {
                MyRender.PopRenderSetup();
            }

            MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().StartNextBlock("FillDebugScreen");

            FillDebugScreen();

            DrawLoadsCount();


            ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            //  Draw secondary camera and its gui texts
            ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().StartProfilingBlock("DrawSecondaryCamera");
            if (drawSecondaryCamera)
            {
                DrawSecondaryCamera();
            }

            if (drawSecondaryCameraIndicators)
            {
                DrawSecondaryCameraDescriptions(drawSecondaryCamera);
            }
            MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().EndProfilingBlock();

            MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().StartNextBlock("Bloody remote");

            DrawBloodAndOxygen();

            DrawRemoteControlScreen();

            MyRender.GetRenderProfiler().StartProfilingBlock("DrawHUDAndEditor");
            DrawHUDAndEditor(DrawHud, drawSecondaryCamera);
            MyRender.GetRenderProfiler().EndProfilingBlock();

            ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            //  Please consider that drawing sprites changed render state, so it must be restored after all 2D rendering is done
            ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

            MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().StartNextBlock("Hud");


            if (IsGameActive())
            {
                //  Enable forward look again (for drawing GUI, texts...)
                MyCamera.EnableForward();
            }

            if (IsEditorActive())
            {
                if (MyConfig.EditorUseCameraCrosshair && MyEditorGizmo.IsRotationActive() == false)
                {
                    MyHud.DrawCameraCrosshair();
                }
            }
            //  Draw fade-in or fade-out (alpha 1 means that black rectangle will be totaly opaque and we won't see nothing from the game)
            float backgroundFadeAlphaFlyThrough = (!MyGuiScreenGamePlay.Static.IsGameActive() && !IsEditorActive() && MyTrailerLoad.IsEnabled()) ? MyTrailerLoad.GetBackgroundFadeAlpha() : GetBackgroundFadeAlpha();
            DrawBackgroundFade(backgroundFadeAlphaFlyThrough);

            //  We start/restart all batched objects in our sprite batch because in game-play screen we do a lot of stuff that's not compatible with it
            MyGuiManager.BeginSpriteBatch();

            MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().StartNextBlock("EditorControls");

            if ((IsEditorActive() || IsIngameEditorActive()) && !MyMinerGame.IsPaused())
            {
                MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().StartProfilingBlock("EditorControls.Draw");
                EditorControls.Draw();
                MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().EndProfilingBlock();
            }
            MyGuiManager.EndSpriteBatch();

            if (m_prepareTextureForSectorLoadingScreen && !m_isPreparedTextureForSectorLoadingScreen)
            {
                m_textureForSectorLoadingScreen = MyRender.GetBackBufferAsTexture();
                m_isPreparedTextureForSectorLoadingScreen = true;

                MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().StartProfilingBlock("MyGuiManager.DrawSpriteBatch");
                //  ResolveBackBuffer will remove what we rendered from backbuffer so we need to render it again otherwise there will be blink on screen
                MyGuiManager.BeginSpriteBatch();
                MyGuiManager.DrawSpriteBatch(m_textureForSectorLoadingScreen, Vector2.Zero, Color.White);
                MyGuiManager.EndSpriteBatch();
                MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().EndProfilingBlock();
            }

            MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().StartProfilingBlock("MyCamera.EnableForward");
            MyCamera.EnableForward();
            MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().EndProfilingBlock();


            MyGuiManager.BeginSpriteBatch();

            if (MyMinerGame.IsGameReady && m_loadingScreen != null)
            {
                MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().StartProfilingBlock("m_loadingScreen.UnloadContent");
                m_loadingScreen.UnloadContent();
                m_loadingScreen = null;
                MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().EndProfilingBlock();
            }

            MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().StartNextBlock("--m_firstDrawCall == FIRST_FADE_IN_DELAY");

            if (--m_firstDrawCall == FIRST_FADE_IN_DELAY)
            {
                MyMwcLog.WriteLine("First draw call - after render");
                MyTextureManager.DbgUpdateStats();
                MyTextureManager.OverrideLoadingMode = null;
                GC.Collect();
                MyMinerGame.IsGameReady = true;

                m_backgroundFadeColor = new Vector4(0, 0, 0, 1.0f);
                m_fadeAlpha = 1.0f;
                FadeIn(1 / ((float)FIRST_FADE_IN_DELAY * MyConstants.PHYSICS_STEPS_PER_SECOND));
                GameReady();
            }

            if (m_firstDrawCall == FIRST_GAME_SAFELY_LOADED_DELAY)
            {
                MyMwcLog.WriteLine("Draw call - game safely loaded");

                GameSafelyLoaded();
            }

            MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().StartNextBlock("m_firstDrawCall > FIRST_FADE_IN_DELAY");

            if (m_firstDrawCall > FIRST_GAME_SAFELY_LOADED_DELAY)
            {
                DrawLoading();
                MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().EndProfilingBlock();
                MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().EndProfilingBlock();
                return true;
            }
            else
                if (m_firstDrawCall > FIRST_FADE_IN_DELAY)
                {
                    MyMinerGame.Static.GraphicsDevice.Clear(ClearFlags.All, new ColorBGRA(0), 1, 0);
                }

            MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().StartNextBlock("m_firstDrawCall == FIRST_DELAY_SAFE_IN_GAME");

            if (m_firstDrawCall == FIRST_DELAY_SAFE_IN_GAME)
            {
                if (MyFakes.TEST_MULTIPLE_SAVE_LOAD && this.GetGameType() == MyGuiScreenGamePlayType.EDITOR_STORY)
                {
                    MultipleSaveLoadTest();
                }
            }

            //MyMinerGameDX.GraphicsDeviceManager.DbgDumpLoadedResources(true);
            //MyTextureManager.DbgDumpLoadedTexturesBetter(true);

            MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().StartNextBlock("MyFlashes.Draw");


            MyFlashes.Draw();


            if (m_firstDrawCall <= 0)
            {
                MyMinerGame.IsGameReady = true;
            }
            if (base.Draw(m_fadeAlpha) == false)
            {
                MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().EndProfilingBlock();
                MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().EndProfilingBlock();
                return false;
            }

            MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().StartNextBlock("MyFlashes.Draw");

            MyDebugDraw.Draw();
            MyEntities.DebugDrawStatistics();

            MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().StartNextBlock("Demo texts");


            if (DrawDemoEnd && IsGameActive() && MyGuiManager.GetScreensCount() == 1)
            {
                m_demoEndText.Clear();
                m_demoEndText.AppendLine("Mission Succesful!");
                m_demoEndText.AppendLine("Official Demo ends here.");
                MyGuiManager.DrawString(MyGuiManager.GetFontMinerWarsBlue(), m_demoEndText, new Vector2(0.5f, 0.5f), 3f, MyGuiDrawAlignEnum.HORISONTAL_CENTER_AND_VERTICAL_CENTER);
            }

            if (DrawCampaignEnd && IsGameActive() && MyGuiManager.GetScreensCount() == 1)
            {
                MyGuiManager.DrawString(MyGuiManager.GetFontMinerWarsGreen(), MyTextsWrapper.Get(MyTextsWrapperEnum.CampaignIsCompleted), new Vector2(0.5f, 0.5f), 3f, MyGuiDrawAlignEnum.HORISONTAL_CENTER_AND_VERTICAL_CENTER);
            }


            MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().EndProfilingBlock();

            MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().EndProfilingBlock(drawBlock);

            return true;
        }
        public static MyGuiScreenLoading ReloadGameplayScreen(MyMwcObjectBuilder_Checkpoint checkpoint, MyMwcStartSessionRequestTypeEnum? sessionType = null, MyGuiScreenGamePlayType? gameplayType = null, MyMissionID? startMission = null, MyMwcTravelTypeEnum? travelType = null)
        {
            if (MyMultiplayerGameplay.IsRunning)
                MyMultiplayerGameplay.Static.Suspend();

            if (checkpoint.SectorObjectBuilder != null)
            {
                MySession.Static.Is2DSector = MyMwcSectorIdentifier.Is25DSector(checkpoint.SectorObjectBuilder.Name);
            }

            Debug.Assert((gameplayType != null && sessionType != null) || MyGuiScreenGamePlay.Static != null, "Set gameplay type and session type, there's no previous gameplay screen");
            MyGuiScreenGamePlayType newGameplayType = gameplayType.HasValue ? gameplayType.Value : MyGuiScreenGamePlay.Static.GetGameType();
            MyMwcStartSessionRequestTypeEnum? newSessionType = sessionType.HasValue ? sessionType.Value : MyGuiScreenGamePlay.Static.GetSessionType();
            MyGuiScreenGamePlayType? previousGameplaytype = MyGuiScreenGamePlay.Static != null ? MyGuiScreenGamePlay.Static.GetPreviousGameType() : (MyGuiScreenGamePlayType?)null;
            MyMissionID? previousMissionToStart = MyGuiScreenGamePlay.Static != null ? MyGuiScreenGamePlay.Static.m_missionToStart : (MyMissionID?)null;

            var newGameplayScreen = new MyGuiScreenGamePlay(newGameplayType, previousGameplaytype, checkpoint.CurrentSector, checkpoint.SectorObjectBuilder.Version, newSessionType);
            newGameplayScreen.m_missionToStart = previousMissionToStart;
            if (travelType.HasValue)
                newGameplayScreen.m_travelReason = travelType.Value;


            var loadScreen = new MyGuiScreenLoading(newGameplayScreen, MyGuiScreenGamePlay.Static);
            loadScreen.AddEnterSectorResponse(checkpoint, startMission);

            /*
            if (MyConfig.NeedShowPerfWarning)
            {
                MyGuiScreenPerformanceWarning perfWarningScreen = new MyGuiScreenPerformanceWarning(loadScreen);

                perfWarningScreen.Closed += delegate
                {
                    MyGuiManager.AddScreen(loadScreen);
                };

                MyGuiManager.AddScreen(perfWarningScreen);
            }
            else*/
            {
                MyGuiManager.AddScreen(loadScreen);
            }

            return loadScreen;
        }
        //  This method is called every update - even if application has not focus
        //  Update world, do physics integration...
        public override bool Update(bool hasFocus)
        {
            int profBlock = -1;
            MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().StartProfilingBlock("GuiScreenGamePlay::Update", ref profBlock);

            if (MyMultiplayerGameplay.IsRunning)
            {
                MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().StartProfilingBlock("Multiplayer update");
                MyMultiplayerGameplay.Static.Update();
                MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().EndProfilingBlock();
            }

            if (MyFakes.GRAVITATION.HasValue)
                MyPhysics.physicsSystem.Gravitation = MyFakes.GRAVITATION.Value;

            if (MySession.Is25DSector)
            {
                MyPhysics.physicsSystem.Gravitation = new Vector3(0, -4000, 0);
            }

            if (MyFakes.MWBUILDER && !MyEditor.Static.IsActive())
            {
                //MyPhysics.physicsSystem.Gravitation = new Vector3(0, -2000, 0);
                MyPhysics.physicsSystem.Gravitation = new Vector3(0, -0, 0);
                /*
    MyVoxelMap voxelMap = MyVoxelMaps.GetVoxelMaps()[0];
    MyPhysics.physicsSystem.GravitationPoints.Clear();
    MyPhysics.physicsSystem.GravitationPoints.Add(new Tuple<BoundingSphere, float>(new BoundingSphere(voxelMap.WorldAABB.GetCenter(), voxelMap.WorldAABB.Size().Length()), 2000));
              */

                MyVoxelMap voxelMap = MyVoxelMaps.GetVoxelMaps()[0];
                float distance = Vector3.Distance(voxelMap.WorldAABB.GetCenter(), MyCamera.Position);
                float alpha = MathHelper.Clamp(distance / voxelMap.WorldAABB.Size().Length(), 0, 1);

                MySector.SunProperties.BackgroundColor = Vector3.Lerp(new Vector3(5, 5, 16), Vector3.One, alpha);

            }

            //MyPhysics.physicsSystem.Gravitation = new Vector3(0,0, 0);

            CheckChatboxMessagesTTL();

            if (m_playInventoryTransferSound && MyMinerGame.TotalGamePlayTimeInMilliseconds > m_inventoryTransferSoundPlayTime)
            {
                m_playInventoryTransferSound = false;
                if (m_inventoryPlaySound == null || !m_inventoryPlaySound.Value.IsPlaying)
                    m_inventoryPlaySound = MyAudio.AddCue2D(MySoundCuesEnum.HudInventoryTransfer);
                else
                    m_inventoryPlaySound = null;
            }


            if (m_invokeGameEditorSwitch)
                TrySwitchBetweenGameAndEditor();

#if RENDER_PROFILING
            MyRender.RenderObjectUpdatesCounter = 0;
#endif

            //  We do not want to do any update when switching between sectors
            if (m_state == MyGuiScreenState.CLOSING)
            {
                MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().EndProfilingBlock(profBlock);
                return false;
            }

            if (base.Update(hasFocus) == false)
            {
                MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().EndProfilingBlock(profBlock);
                return false;
            }

            if (m_startTimeInMilliseconds.HasValue == false)
            {
                m_startTimeInMilliseconds = MyMinerGame.TotalTimeInMilliseconds;
                //MyGuiSounds.PlayClick();
            }

            if (m_updateGPSReminderTimer > 0.5f)
            {
                m_updateGPSReminderTimer = 0;
                UpdateGPSReminder();
            }
            else
            {
                m_updateGPSReminderTimer += MyConstants.PHYSICS_STEP_SIZE_IN_SECONDS;
            }

            ShowOrHideNotification(MyConfig.NeedShowHelpScreen, ref m_needShowHelpNotification, MyTextsWrapperEnum.NotificationNeedShowHelpScreen, null);
            ShowOrHideNotification(!MyEditor.Static.IsActive() && !MyFakes.MWBUILDER && MyHud.GetClosestOreDistanceSquared() < 100 * 100 && (MySession.PlayerShip.Weapons.GetMountedDrill() == null || MySession.PlayerShip.Weapons.GetMountedDrill().CurrentState == MyDrillStateEnum.InsideShip), ref m_oreInRangeNotification, MyTextsWrapperEnum.OreNotification, MyGameControlEnums.HARVEST);
            ShowOrHideNotification(!MyEditor.Static.IsActive() && !MyFakes.MWBUILDER && MyHud.GetClosestOreDistanceSquared() < 100 * 100 && (MySession.PlayerShip != null && MySession.PlayerShip.Weapons.GetMountedDrill() != null && MySession.PlayerShip.Weapons.GetMountedDrill().CurrentState == MyDrillStateEnum.InsideShip), ref m_drillingInRangeNotification, MyTextsWrapperEnum.DrillNotification, MyGameControlEnums.DRILL);
            ShowOrHideNotification(!MyEditor.Static.IsActive() && !MyFakes.MWBUILDER && MySession.PlayerShip != null && MySession.PlayerShip.Weapons.GetMountedDrill() != null && MySession.PlayerShip.Weapons.GetMountedDrill().CurrentState != MyDrillStateEnum.InsideShip, ref m_pressMToDeactivateDrillNotification, MyTextsWrapperEnum.PressMToDeactivateDrill, MyGameControlEnums.DRILL);
            ShowOrHideNotification(!MyEditor.Static.IsActive() && !MyFakes.MWBUILDER && MySession.PlayerShip != null && MySession.PlayerShip.Weapons.GetMountedDrill() != null && MySession.PlayerShip.Weapons.GetMountedDrill().CurrentState == MyDrillStateEnum.Activated, ref m_holdFireToDrillNotification, MyTextsWrapperEnum.HoldFireToDrillNotification, MyGameControlEnums.FIRE_PRIMARY);


            if (m_fireDisableTimeout > 0)
            {
                m_fireDisableTimeout = m_fireDisableTimeout - MyConstants.PHYSICS_STEP_SIZE_IN_MILLISECONDS;
            }

            if (hasFocus == false)
            {
                //  We must reset this
                m_handleInputMouseKeysReleased = false;
            }

            if (m_firstUpdateCall)
            {
                if (MyGuiScreenLoading.Static != null)
                {
                    MyGuiScreenLoading.Static.UnloadContent();
                }

                m_loadingScreen = new MyGuiScreenLoading(null, null, MyGuiScreenLoading.LastBackgroundTexture);
                m_loadingScreen.LoadContent();
                m_firstUpdateCall = false;
                m_firstTimeLoaded = MyMinerGame.TotalTimeInMilliseconds;

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

                switch (m_type)
                {
                    case MyGuiScreenGamePlayType.GAME_STORY:
                        break;
                    case MyGuiScreenGamePlayType.EDITOR_SANDBOX:
                    case MyGuiScreenGamePlayType.EDITOR_MMO:
                    case MyGuiScreenGamePlayType.EDITOR_STORY:
                    case MyGuiScreenGamePlayType.INGAME_EDITOR:
                        FillEditorNotifications();
                        break;
                    default:
                        break;
                }


                if (OnGameLoaded != null)
                    OnGameLoaded(this, null);

                //  we may create GPS waypoints only after the first simulation pass
                if (MyFakes.ENABLE_GENERATED_WAYPOINTS_IN_EDITOR)
                {
                    MyWayPointGraph.CreateWaypointsAroundLargeStaticObjects();
                }
                else
                {
                    switch (m_type)
                    {
                        case MyGuiScreenGamePlayType.EDITOR_STORY:  // don't create them in the editor (use Shift+M)
                        case MyGuiScreenGamePlayType.EDITOR_MMO:
                        case MyGuiScreenGamePlayType.EDITOR_SANDBOX:
                            MyWayPointGraph.RemoveWaypointsAroundLargeStaticObjects();
                            MyWayPointGraph.SetVisibilityOfAllWaypoints(true);
                            break;
                        default:
                            MyWayPointGraph.CreateWaypointsAroundLargeStaticObjects();
                            MyWayPointGraph.SetVisibilityOfAllWaypoints(MyHud.ShowDebugWaypoints);
                            break;
                    }
                }
            }


            if (MyMinerGame.IsGameReady)
            {
                if (MyLoadingPerformance.Instance.IsTiming)
                {
                    MyLoadingPerformance.Instance.LoadingName = MyMissions.ActiveMission == null ? "No mission" : MyMissions.ActiveMission.Name.ToString();
                    MyLoadingPerformance.Instance.FinishTiming();
                }

                MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().StartProfilingBlock("Audio");

                if (MyAudio.GetMusicState() == MyMusicState.Stopped &&
                    MyAudio.GetMusicCue() == null &&
                    !MyAudio.HasAnyTransition() &&
                    MyMinerGame.TotalTimeInMilliseconds - m_firstTimeLoaded >= 1000)
                {
                    if (IsMainMenuActive())
                    {
                        MyAudio.ApplyTransition(MyMusicTransitionEnum.MainMenu);
                        MyAudio.AddCue2D(MySoundCuesEnum.MenuWelcome);
                    }
                    else if (IsCreditsActive())
                    {
                        MyAudio.ApplyTransition(MyMusicTransitionEnum.MainMenu);
                    }
                    else if (IsGameActive() || IsPureFlyThroughActive())
                    {
                        MyAudio.ApplyTransition(MyMusicTransitionEnum.CalmAtmosphere);
                    }
                }
                MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().EndProfilingBlock();

                MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().StartProfilingBlock("Editor");

                if (IsEditorActive() || IsIngameEditorActive())
                {
                    MyEditor.Static.Update();
                    EditorControls.Update();
                }
                MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().EndProfilingBlock();

                MyRadar.Update();
                MyFriendlyFire.Update();

                if (m_fadingOut)
                {
                    m_fadeAlpha += m_fadeSpeed;
                    if (m_fadeAlpha >= 1.0f)
                    {
                        m_fadeAlpha = 1.0f;
                        if (FadedOut != null)
                            FadedOut();
                        m_fadingOut = false;
                    }
                }
                else if (m_fadingIn)
                {
                    m_fadeAlpha -= m_fadeSpeed;
                    if (m_fadeAlpha <= 0.0f)
                    {
                        m_fadeAlpha = 0.0f;
                        if (FadedIn != null)
                            FadedIn();
                        m_fadingIn = false;
                    }
                }
            }

            MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().StartProfilingBlock("NonBackgroundThread");
            if (!MyEditor.Static.IsBackgroundWorkThreadAlive())
            {
                if (m_backgroudThreadWasWorking)
                {
                    MyRender.Enabled = true;
                }
                m_backgroudThreadWasWorking = false;

                if (MySession.PlayerShip != null)
                {
                    ProcessSectorBoundaries();
                }

                //  If we detect logged off player during active game (story or MMO, but not main-menu-fly-through), we close actual game and practicaly restart it all
                if (StartTimeoutClosing)
                {
                    //  We must shut-down any game that may be played right now - becase loggouted player is a weird state and we need to reset it all
                    MyGuiManager.BackToMainMenu();
                    MyGuiManager.CloseAllScreensExceptThisOneAndAllTopMost(this);
                    StartTimeoutClosing = false;
                }

                if (MyMinerGame.IsPaused())
                {
                    MyCamera.Zoom.PauseZoomCue();
                }
                else
                {

                    if (MyMinerGame.IsGameReady)
                    {
                        if (IsGameActive())
                        {
                            MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().StartProfilingBlock("Global events");
                            MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().StartProfilingBlock("MySunWind");
                            MySunWind.IsVisible = MyGuiScreenSolarSystemMap.Static == null;
                            MySunWind.Update();
                            MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().EndProfilingBlock();

                            MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().StartProfilingBlock("MyMeteorWind");
                            MyMeteorWind.Update();
                            MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().EndProfilingBlock();

                            MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().StartProfilingBlock("MyIceStorm");
                            MyIceStorm.Update();
                            MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().EndProfilingBlock();
                            MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().EndProfilingBlock();

                            MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().StartProfilingBlock("MyAttackFormations");
                            MyAttackFormations.Instance.Update();
                            MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().EndProfilingBlock();
                            //TODO
                            /*
                           if (MyFakes.ENABLE_SHOUT)
                           {
                               MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().StartProfilingBlock("MyShouts");
                               MyShouts.Update();
                               MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().EndProfilingBlock();
                           }  */
                        }

                        MyRoutefindingHelper.AdvanceRoutefinding();

                        MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().StartProfilingBlock("MyEntityDetectorsManager.Update");
                        MyEntityDetectorsManager.Update();
                        MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().EndProfilingBlock();

                        MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().StartProfilingBlock("MyEntities.UpdateBeforeIntegration");
                        UpdateBeforeSimulation();
                        MyEntities.UpdateBeforeSimulation();
                        MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().EndProfilingBlock();


                        MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().StartProfilingBlock("Dust+MyExplosions+MyDistantImpostors");
                        MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().StartProfilingBlock("UpdateAndCalculateDustColors");
                        UpdateAndCalculateDustColors();
                        MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().EndProfilingBlock();

                        MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().StartProfilingBlock("Explosions update");
                        MyExplosions.Update();
                        MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().EndProfilingBlock();
                        MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().StartProfilingBlock("Impostors update");
                        MyDistantImpostors.Update();
                        MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().EndProfilingBlock();
                        MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().EndProfilingBlock();


                        if (MyFakes.MWBUILDER)
                        {                          /*
                        MyVoxelMap voxelMap = MyVoxelMaps.GetVoxelMaps()[0];

                        voxelMap.InvalidateCache(new MyMwcVector3Int(0, 0, 0), new MyMwcVector3Int(1024, 1024, 1024));
                        MyVoxelMaps.RecalcVoxelMaps();     */
                        }



                        MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().StartProfilingBlock("MyPhysics-Simulate");
                        if (deltaphys <= 0)
                        {
                            if (PHYSICS_SIMULATION_SLOWDOWN)
                                deltaphys = 30;
                            else
                                deltaphys = 0;
                            //  Physics integration
                            // dont allow physics for editor - god mode 
                            switch (m_type)
                            {
                                case MyGuiScreenGamePlayType.EDITOR_STORY:
                                case MyGuiScreenGamePlayType.EDITOR_MMO:
                                case MyGuiScreenGamePlayType.EDITOR_SANDBOX:
                                    //MyPhysics.physicsSystem.Simulate(MyConstants.PHYSICS_STEP_SIZE_IN_SECONDS);
                                    MyPhysics.physicsSystem.Simulate(0.0f);
                                    break;
                                default:
                                    MyPhysics.physicsSystem.Simulate(MyConstants.PHYSICS_STEP_SIZE_IN_SECONDS);
                                    break;
                            }
                        }
                        else
                            deltaphys--;
                        MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().EndProfilingBlock();

                        MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().StartProfilingBlock("MyTrailerLoad, MyEntities-UAI, MySunWind, WpGen, MySession");
                        //  If this is trailer in load phase, we update attached object's positions to values from files
                        //  We must do it before 'after integration', otherwise velocity/speed won't be calculated with correct positions
                        MyTrailerLoad.Update();

                        if (IsGameActive() || IsIngameEditorActive())
                        {
                            MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().StartProfilingBlock("MySession.Update");
                            System.Diagnostics.Debug.Assert(MySession.Static != null, "Session cannot be null in the game");
                            MySession.Static.Update();
                            MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().EndProfilingBlock();
                        }

                        MyEnemyTargeting.Update();

                        //Do it after MySession.Static.Update(); because they move objects there, and we shoot here
                        MyEntities.UpdateAfterSimulation();

                        MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().StartProfilingBlock("MyProjectiles");
                        //Be careful, projectiles must be updated AFTER physics to get correct velocity results!
                        //Also must be after UpdateAfterIntegration to have fired bullets
                        MyProjectiles.Update();
                        MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().EndProfilingBlock();


                        //Update sun
                        MyRender.Sun.Direction = -MyGuiScreenGamePlay.Static.GetDirectionToSunNormalized();
                        MyRender.Sun.Color = MySunWind.IsActive ? MySunWind.GetSunColor() : new Vector4(MySector.SunProperties.SunDiffuse, 1.0f);
                        MyRender.Sun.BackColor = MySector.SunProperties.BackSunDiffuse;
                        MyRender.Sun.BackIntensity = MySector.SunProperties.BackSunIntensity;
                        MyRender.Sun.SpecularColor = MySector.SunProperties.SunSpecular;
                        MyRender.Sun.Intensity = MySector.SunProperties.SunIntensity * (MySession.Is25DSector ? 2.5f : 1);
                        MyRender.AmbientColor = MySector.SunProperties.AmbientColor;
                        MyRender.AmbientMultiplier = MySector.SunProperties.AmbientMultiplier;
                        MyRender.EnvAmbientIntensity = MySector.SunProperties.EnvironmentAmbientIntensity;


                        MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().EndProfilingBlock();
                    }
                }
                ////////////////////////////////////////////////////////////////////////////////////////////////////////////
                //  From where will be camera looking? (needs to be called after physics integration - because for view matrix we need to know current position of player's ship)
                ////////////////////////////////////////////////////////////////////////////////////////////////////////////

                MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().StartProfilingBlock("Camera");
                MyCamera.Update();

                MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().StartProfilingBlock("Update spectator");

                if ((CameraAttachedTo == MyCameraAttachedToEnum.PlayerMinerShip) && (MySession.PlayerShip == null))
                {
                    CameraAttachedTo = MyCameraAttachedToEnum.Spectator;
                }

                switch (CameraAttachedTo)
                {
                    case MyCameraAttachedToEnum.Spectator:
                        MyCamera.SetViewMatrix(MySpectator.GetViewMatrix());
                        break;

                    case MyCameraAttachedToEnum.PlayerMinerShip:
                        MyCamera.SetViewMatrix(MySession.PlayerShip.GetViewMatrix());
                        break;

                    case MyCameraAttachedToEnum.BotMinerShip:
                        if (Static.ShipForSimpleTesting != null)
                        {
                            MyCamera.SetViewMatrix(MyGuiScreenGamePlay.Static.ShipForSimpleTesting.GetViewMatrix());
                        }
                        break;

                    case MyCameraAttachedToEnum.PlayerMinerShip_ThirdPersonFollowing:
                        MySpectator.Position = MySession.PlayerShip.GetPosition() + ThirdPersonCameraDelta;
                        MySpectator.Target = MySession.PlayerShip.GetPosition();
                        MyCamera.SetViewMatrix(MySpectator.GetViewMatrix());
                        break;

                    case MyCameraAttachedToEnum.PlayerMinerShip_ThirdPersonDynamic:
                        {
                            MySmallShip playerShip = MySession.PlayerShip;

                            if (MySession.Is25DSector)
                            {

                                Vector3 forward = playerShip.GetWorldRotation().Forward;
                                forward.Y = 0;
                                forward.Normalize();
                                //Vector3 right = Vector3.Normalize(playerShip.GetWorldRotation().Right.Project(Vector3.Right));
                                Vector3 right = Vector3.Right;
                                Vector3 up = Vector3.Up;
                                right = Vector3.Cross(up, forward);

                                MyThirdPersonSpectator.TargetOrientation = Matrix.CreateWorld(Vector3.Zero, forward, up);

                                //MyThirdPersonSpectator.TargetOrientation = Matrix.Identity;
                            }
                            else
                                MyThirdPersonSpectator.TargetOrientation = playerShip.GetWorldRotation();

                            MyThirdPersonSpectator.Target = playerShip.GetPosition();

                            MyThirdPersonSpectator.Update();
                            if (!MySession.Is25DSector)
                            {
                                MyThirdPersonSpectator.HandleIntersection(
                                    playerShip, true, playerShip.GetHeadPosition(), playerShip.GetHeadDirection());
                            }

                            MyCamera.SetViewMatrix(MyThirdPersonSpectator.GetViewMatrix(
                                MyCamera.FieldOfView,
                                MyCamera.Zoom.GetZoomLevel(),
                                true, playerShip.GetHeadPosition(), playerShip.GetHeadDirection())
                                );
                        }
                        break;

                    case MyCameraAttachedToEnum.PlayerMinerShip_ThirdPersonStatic:
                        MyCamera.SetViewMatrix(MySpectator.GetViewMatrix());
                        break;

                    case MyCameraAttachedToEnum.Drone:
                        Debug.Assert(IsControlledDrone);
                        MyCamera.SetViewMatrix(ControlledDrone.GetViewMatrix());
                        break;
                    case MyCameraAttachedToEnum.Camera:
                        Debug.Assert(ControlledCamera != null);
                        MyCamera.SetViewMatrix(ControlledCamera.GetViewMatrix());
                        //MyCamera.ProjectionMatrix = (ControlledCamera.GetProjectionMatrix());
                        break;

                    case MyCameraAttachedToEnum.LargeWeapon:
                        Debug.Assert(ControlledLargeWeapon != null);
                        MyCamera.SetViewMatrix(ControlledLargeWeapon.GetViewMatrix());
                        break;
                }

                MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().EndProfilingBlock();

                MyRender.PrepareEntitiesForDrawStart();

                if (MyMinerGame.IsGameReady)
                {
                    MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().StartProfilingBlock("Update playership");

                    // Update spectator reflector properties
                    if (MySession.PlayerShip != null)
                    {
                        MyRender.DrawSpectatorReflector = CameraAttachedTo == MyCameraAttachedToEnum.Spectator;

                        // Update player light properties
                        MyRender.PlayerLight = MySession.PlayerShip.Light;
                        MyRender.SpectatorReflector = MySession.PlayerShip.Light;
                        MyRender.DrawPlayerLightShadow = CameraAttachedTo != MyCameraAttachedToEnum.PlayerMinerShip;


#if !RENDER_PROFILING
                        //We dont want to be bothered by gameplay stuff in editor or profiling
                        if ((m_sessionType == MyMwcStartSessionRequestTypeEnum.EDITOR_STORY) ||
                            (m_sessionType == MyMwcStartSessionRequestTypeEnum.EDITOR_SANDBOX) ||
                            (m_sessionType == MyMwcStartSessionRequestTypeEnum.EDITOR_MMO))
#endif
                        {
                            MySession.PlayerShip.Fuel = MySession.PlayerShip.MaxFuel;
                            MySession.PlayerShip.Oxygen = MySession.PlayerShip.MaxOxygen;
                            MySession.PlayerShip.AddHealth(MySession.PlayerShip.MaxHealth);
                            MySession.PlayerShip.ArmorHealth = MySession.PlayerShip.MaxArmorHealth;
                            MySession.PlayerShip.Weight = MySession.PlayerShip.ShipTypeProperties.Physics.Mass;
                            MySession.Static.Player.RestoreHealth();

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

                        if (IsCheatEnabled(MyGameplayCheatsEnum.INFINITE_AMMO))
                        {
                            foreach (Inventory.MyInventoryItem item in MySession.PlayerShip.Weapons.AmmoInventoryItems.GetAmmoInventoryItems())
                            {
                                item.Amount = item.MaxAmount;
                            }
                        }
                        if (IsCheatEnabled(MyGameplayCheatsEnum.INFINITE_FUEL))
                        {
                            MySession.PlayerShip.Fuel = MySession.PlayerShip.MaxFuel;
                        }
                        if (IsCheatEnabled(MyGameplayCheatsEnum.INFINITE_OXYGEN))
                        {
                            MySession.PlayerShip.Oxygen = MySession.PlayerShip.MaxOxygen;
                        }

                        if ((m_quickZoomOut || m_quickZoomWasUsed) && MyCamera.Zoom.GetZoomLevel() == 1.0f)
                        {
                            m_quickZoomOut = false;
                            m_quickZoomWasUsed = false;
                        }
                    }
                    MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().EndProfilingBlock();
                }

                //ProcessSectorBoundaries();

                ////////////////////////////////////////////////////////////////////////////////////////////////////////////
                //  Update camera forward and sound after view matrix is updated, because you need actual forward and up vectors
                ////////////////////////////////////////////////////////////////////////////////////////////////////////////

                MyCamera.EnableForward();
                MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().EndProfilingBlock();

                MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().StartProfilingBlock("MyAudio.ReverbControl");

                //  Update reverb coeficient and whole sound engine. This needs to be called!!!
                //MyFpsManager.AddToFrameDebugText("MySounds.ReverbControl: " + MyUtils.GetFormatedFloat(MySounds.ReverbControl, 5));
                MyAudio.ReverbControl = MyVoxelMaps.GetReverb(MyCamera.Position);
                MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().EndProfilingBlock();

                MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().StartProfilingBlock("MyLights.Update");
                MyLights.Update();
                MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().EndProfilingBlock();

                MyDebrisField.Update();

            }
            else
            {
                m_backgroudThreadWasWorking = true;
            }
            MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().EndProfilingBlock();


            if (MyMinerGame.IsGameReady)
            {
                MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().StartProfilingBlock("Trailer+UpdateMenu+Hud");

                if (MyMwcFinalBuildConstants.ENABLE_TRAILER_SAVE == true/* && GetGameType() != MyGuiScreenGamePlayType.GAME_SANDBOX*/)
                {
                    MyTrailerSave.UpdatePositionsAndOrientations();
                    MyTrailerSave.IncreaseActiveTick();
                }

                if (IsGameActive())
                {
                    m_selectAmmoMenu.Update();
                    m_wheelControlMenu.Update();
                }

                MyHudNotification.Update();

                if (IsGameActive()) // enable cursor drawing if we have ammo selection opened
                {
                    DrawMouseCursor = (m_selectAmmoMenu.IsEnabled && IsSelectAmmoVisible());
                }


                if (MyFakes.TEST_MULTIPLE_LOAD_UNLOAD && m_loadMultiple)
                {
                    m_loadMultiple = false;
                    int count = m_multipleLoadsCount;

                    /*
                    string username = MyConfig.Username;
                    string password = MyConfig.Password;

                    int modelMeshes = MyPerformanceCounter.PerAppLifetime.MyModelsMeshesCount;
                    int modelVertices = MyPerformanceCounter.PerAppLifetime.MyModelsVertexesCount;
                    int modelTriangles = MyPerformanceCounter.PerAppLifetime.MyModelsTrianglesCount;

                    MyGuiManager.AddScreen(new MyGuiScreenLoginProgress(username, password,
                                                                  new MyGuiScreenStartQuickLaunch(
                                                                      MyMwcQuickLaunchType.NEW_STORY, MyTextsWrapperEnum.StartGameInProgressPleaseWait), null));
                    */

                    MyScriptWrapper.TravelToMission(MyFakes.TEST_MULTIPLE_LOAD_UNLOAD_MISSION);


                    return false;
                }


                MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().EndProfilingBlock();
            }


            MinerWars.AppCode.Game.Render.MyRender.GetRenderProfiler().EndProfilingBlock(profBlock);




            if (MyFakes.TEST_MISSION_GAMEPLAY && MyMinerGame.IsGameReady)
            {
                m_missionGameplayTestDelay -= MyConstants.PHYSICS_STEP_SIZE_IN_MILLISECONDS;
                if (m_missionGameplayTestDelay <= 0)
                {
                    m_missionGameplayTestDelay = MyFakes.TEST_MISSION_GAMEPLAY_DURATION;

                    if (m_missionGameplayKillsRemaining > 0)
                    {
                        m_missionGameplayKillsRemaining--;
                        MySession.PlayerShip.DoDamage(0, 10000, 0, MyDamageType.Explosion, MyAmmoType.Explosive, null);
                        MyGuiScreenGamePlay.Static.Restart();
                        return false;
                    }

                    if (MyMissions.ActiveMission == null)
                    {
                        MyMissions.RefreshAvailableMissions();
                        var availableMissions = MyMissions.GetAvailableMissions();
                        if (availableMissions.Count > 0)
                        {
                            MyMission mission = null;
                            foreach (MyMission m in availableMissions)
                            {
                                if (m.RequiredMissions.Contains(m_lastMissionID))
                                {
                                    mission = m;
                                    break;
                                }
                            }

                            if (mission != null)
                            {
                                MyScriptWrapper.TravelToMission(mission.ID);
                            }
                        }
                        else
                        { //no next missions => we have reached the end of singleplayer game
                        }
                    }
                    else
                    {
                        m_lastMissionID = MyMissions.ActiveMission.ID;
                        MyObjective activeObjective = MyMissions.ActiveMission.ActiveObjectives[0];
                        m_lastObjective = activeObjective;

                        if (m_missionGameplayKillsRemaining == 0 && (m_lastObjective == null || m_lastObjective.SaveOnSuccess))
                        {
                            m_missionGameplayKillsRemaining = MyFakes.TEST_MISSION_GAMEPLAY_AUTO_KILLS;
                        }

                        MyMissionGameplayStats statistics = new MyMissionGameplayStats
                        {
                            FPS = MyFpsManager.GetFps(),
                            FrameTimeAvg = (float)MyFpsManager.FrameTimeAvg,
                            FrameTimeMax = (int)MyFpsManager.FrameTimeMax,
                            FrameTimeMin = (int)MyFpsManager.FrameTimeMin,

                            GC = GC.GetTotalMemory(false),
                            WorkingSet = Environment.WorkingSet,

                            // TODO: Videomem
                            VideoMemAllocated = 1.0f, //MyProgram.GetResourcesSizeInMB(),
                            VideoMemAvailable = MyMinerGame.Static.GraphicsDevice.AvailableTextureMemory / (1024.0f * 1024.0f)
                        };

                        Dictionary<MyMissionID, MyMissionGameplayStats> missionStats;
                        m_missionGameplayStats.TryGetValue(MyMissions.ActiveMission.ID, out missionStats);
                        if (missionStats == null)
                        {
                            missionStats = new Dictionary<MyMissionID, MyMissionGameplayStats>();
                            m_missionGameplayStats.Add(MyMissions.ActiveMission.ID, missionStats);
                        }

                        if (missionStats.ContainsKey(activeObjective.ID))
                        {
                            missionStats.Remove(activeObjective.ID);
                        }

                        missionStats.Add(activeObjective.ID, statistics);


                        //Store them each time because of possible crash
                        StoreMissionStats();

                        if (activeObjective.Location != null && activeObjective.Location.Entity != null)
                        {
                            Vector3 objectivePosition = activeObjective.Location.Entity.GetPosition();
                            MySession.PlayerShip.SetPosition(objectivePosition + -20 * Vector3.Forward);
                        }
                        else
                        {
                            if (activeObjective.MissionEntityIDs.Count > 0)
                            {
                                MyEntity ent = MyEntities.GetEntityByIdOrNull(new MyEntityIdentifier(activeObjective.MissionEntityIDs[0]));
                                if (ent != null)
                                {
                                    Vector3 objectivePosition = ent.GetPosition();
                                    MySession.PlayerShip.SetPosition(objectivePosition + -20 * Vector3.Forward);
                                }
                            }
                        }

                        MyObjective.SkipSubmission = true;
                    }
                }
                return false;
            }

            // detect if controlled large weapon or camera are in working state (Enabled and IsElectrified)
            if (ControlledLargeWeapon != null && !ControlledLargeWeapon.IsWorking() && !DetachingForbidden)
            {
                CameraAttachedTo = MyCameraAttachedToEnum.PlayerMinerShip;
                ReleaseControlOfLargeWeapon();
            }
            if (ControlledCamera != null && !ControlledCamera.IsWorking())
            {
                ReleaseControlOfCamera();
            }

            /*
            m_backgroundWorkerCanRun = false;
            while (m_backgroundWorkerRunning)
            {
            }
              */
            return true;
        }
        void ValidateAllMissionsStartingFrom(int index)
        {
            var allMissions = MyMissions.Missions.Values.OfType<MyMission>().ToList();
            if (index >= allMissions.Count) return;

            var mission = allMissions[index];
            MyMissionID missionId = mission.ID;
            // each mission is automatically validated after start
            MyGuiManager.CloseAllScreensExcept(MyGuiScreenGamePlay.Static);

            var startSessionScreen = new MyGuiScreenStartSessionProgress(MyMwcStartSessionRequestTypeEnum.NEW_STORY,
                MyTextsWrapperEnum.StartGameInProgressPleaseWait, null, MyGameplayDifficultyEnum.EASY, null, null);

            startSessionScreen.OnSuccessEnter = new Action<MyGuiScreenGamePlayType, MyMwcStartSessionRequestTypeEnum, MyMwcObjectBuilder_Checkpoint>((screenType, sessionType, checkpoint) =>
            {
                Action<MyMwcObjectBuilder_Sector, Vector3> enterSuccessAction = new Action<MyMwcObjectBuilder_Sector, Vector3>((sector, newPosition) =>
                {
                    MyMwcVector3Int sectorPosition;
                    sectorPosition = sector.Position;

                    MyMwcSectorIdentifier newSectorIdentifier = new MyMwcSectorIdentifier(MyMwcSectorTypeEnum.STORY, MyClientServer.LoggedPlayer.GetUserId(), sectorPosition, null);
                    var newScreen = new MyGuiScreenGamePlay(MyGuiScreenGamePlayType.GAME_STORY, null, newSectorIdentifier, sector.Version, MyMwcStartSessionRequestTypeEnum.LOAD_CHECKPOINT);
                    var loadScreen = new MyGuiScreenLoading(newScreen, MyGuiScreenGamePlay.Static);
                    newScreen.OnGameReady += new ScreenHandler((screen) =>
                    {
                        ((MyMission)MyMissions.GetMissionByID(missionId)).Accept();
                        ValidateAllMissionsStartingFrom(index + 1);  // validate the next mission
                    });

                    loadScreen.AnnounceLeaveToServer = true;
                    loadScreen.LeaveSectorReason = MyMwcLeaveSectorReasonEnum.TRAVEL;

                    // Current sector and sector object builder has changed
                    checkpoint.ActiveMissionID = -1; // Manually deactivate mission
                    checkpoint.PlayerObjectBuilder.ShipObjectBuilder.PositionAndOrientation.Position = newPosition;
                    checkpoint.EventLogObjectBuilder.Clear(); // Or just clear mission start/finish

                    // Make prereq missions completed
                    foreach (var prereq in mission.RequiredMissions)
                    {
                        var start = new MyEventLogEntry() { EventType = EventTypeEnum.MissionStarted, EventTypeID = (int)prereq }.GetObjectBuilder();
                        var end = new MyEventLogEntry() { EventType = EventTypeEnum.MissionFinished, EventTypeID = (int)prereq }.GetObjectBuilder();
                        checkpoint.EventLogObjectBuilder.Add(start);
                        checkpoint.EventLogObjectBuilder.Add(end);
                    }

                    checkpoint.SectorObjectBuilder = sector;
                    checkpoint.CurrentSector.Position = sector.Position;
                    loadScreen.AddEnterSectorResponse(checkpoint, missionId);

                    MyGuiManager.AddScreen(loadScreen);

                    if (MyMinerGame.IsPaused())
                        MyMinerGame.SwitchPause();
                });

                //  Load neighbouring sector 
                MyGuiManager.AddScreen(new MyGuiScreenEnterSectorProgress(MyMwcTravelTypeEnum.SOLAR, mission.Location.Sector, Vector3.Zero, enterSuccessAction));

                //var newGameplayScreen = new MyGuiScreenGamePlay(screenType, null, checkpoint.CurrentSector, sessionType);
                //var loadScreen = new MyGuiScreenLoading(newGameplayScreen, MyGuiScreenGamePlay.Static);

                //loadScreen.AddEnterSectorResponse(checkpoint);
                //MyGuiManager.AddScreen(loadScreen);
            });

            MyGuiManager.AddScreen(startSessionScreen);
        }
        void ValidateAllMissionsStartingFrom(int index)
        {
            var allMissions = MyMissions.Missions.Values.OfType <MyMission>().ToList();

            if (index >= allMissions.Count)
            {
                return;
            }

            var         mission   = allMissions[index];
            MyMissionID missionId = mission.ID;

            // each mission is automatically validated after start
            MyGuiManager.CloseAllScreensExcept(MyGuiScreenGamePlay.Static);

            var startSessionScreen = new MyGuiScreenStartSessionProgress(MyMwcStartSessionRequestTypeEnum.NEW_STORY,
                                                                         MyTextsWrapperEnum.StartGameInProgressPleaseWait, null, MyGameplayDifficultyEnum.EASY, null, null);

            startSessionScreen.OnSuccessEnter = new Action <MyGuiScreenGamePlayType, MyMwcStartSessionRequestTypeEnum, MyMwcObjectBuilder_Checkpoint>((screenType, sessionType, checkpoint) =>
            {
                Action <MyMwcObjectBuilder_Sector, Vector3> enterSuccessAction = new Action <MyMwcObjectBuilder_Sector, Vector3>((sector, newPosition) =>
                {
                    MyMwcVector3Int sectorPosition;
                    sectorPosition = sector.Position;

                    MyMwcSectorIdentifier newSectorIdentifier = new MyMwcSectorIdentifier(MyMwcSectorTypeEnum.STORY, MyClientServer.LoggedPlayer.GetUserId(), sectorPosition, null);
                    var newScreen          = new MyGuiScreenGamePlay(MyGuiScreenGamePlayType.GAME_STORY, null, newSectorIdentifier, sector.Version, MyMwcStartSessionRequestTypeEnum.LOAD_CHECKPOINT);
                    var loadScreen         = new MyGuiScreenLoading(newScreen, MyGuiScreenGamePlay.Static);
                    newScreen.OnGameReady += new ScreenHandler((screen) =>
                    {
                        ((MyMission)MyMissions.GetMissionByID(missionId)).Accept();
                        ValidateAllMissionsStartingFrom(index + 1);  // validate the next mission
                    });

                    loadScreen.AnnounceLeaveToServer = true;
                    loadScreen.LeaveSectorReason     = MyMwcLeaveSectorReasonEnum.TRAVEL;

                    // Current sector and sector object builder has changed
                    checkpoint.ActiveMissionID = -1;          // Manually deactivate mission
                    checkpoint.PlayerObjectBuilder.ShipObjectBuilder.PositionAndOrientation.Position = newPosition;
                    checkpoint.EventLogObjectBuilder.Clear(); // Or just clear mission start/finish

                    // Make prereq missions completed
                    foreach (var prereq in mission.RequiredMissions)
                    {
                        var start = new MyEventLogEntry()
                        {
                            EventType = EventTypeEnum.MissionStarted, EventTypeID = (int)prereq
                        }.GetObjectBuilder();
                        var end = new MyEventLogEntry()
                        {
                            EventType = EventTypeEnum.MissionFinished, EventTypeID = (int)prereq
                        }.GetObjectBuilder();
                        checkpoint.EventLogObjectBuilder.Add(start);
                        checkpoint.EventLogObjectBuilder.Add(end);
                    }

                    checkpoint.SectorObjectBuilder    = sector;
                    checkpoint.CurrentSector.Position = sector.Position;
                    loadScreen.AddEnterSectorResponse(checkpoint, missionId);

                    MyGuiManager.AddScreen(loadScreen);

                    if (MyMinerGame.IsPaused())
                    {
                        MyMinerGame.SwitchPause();
                    }
                });

                //  Load neighbouring sector
                MyGuiManager.AddScreen(new MyGuiScreenEnterSectorProgress(MyMwcTravelTypeEnum.SOLAR, mission.Location.Sector, Vector3.Zero, enterSuccessAction));

                //var newGameplayScreen = new MyGuiScreenGamePlay(screenType, null, checkpoint.CurrentSector, sessionType);
                //var loadScreen = new MyGuiScreenLoading(newGameplayScreen, MyGuiScreenGamePlay.Static);

                //loadScreen.AddEnterSectorResponse(checkpoint);
                //MyGuiManager.AddScreen(loadScreen);
            });

            MyGuiManager.AddScreen(startSessionScreen);
        }