Exemple #1
0
        private void DrawSplashScreen(SpriteBatch spriteBatch)
        {
            if (videoPlayer == null)
            {
                videoPlayer = new VideoPlayer();
                videoPlayer.Play(splashScreenVideo);
                videoPlayer.Volume = GameMain.Config.SoundVolume;
            }
            else
            {
                Texture2D videoTexture = null;

                if (videoPlayer.State == MediaState.Stopped)
                {
                    videoPlayer.Dispose();
                    videoPlayer = null;

                    splashScreenVideo.Dispose();
                    splashScreenVideo = null;
                }
                else
                {
                    videoTexture = videoPlayer.GetTexture();

                    spriteBatch.Begin();
                    spriteBatch.Draw(videoTexture, new Rectangle(0, 0, GameMain.GraphicsWidth, GameMain.GraphicsHeight), Color.White);
                    spriteBatch.End();

                    if (PlayerInput.KeyHit(Keys.Space) || PlayerInput.KeyHit(Keys.Enter) || PlayerInput.LeftButtonDown())
                    {
                        videoPlayer.Stop();
                    }
                }
            }
        }
Exemple #2
0
        public bool IsHit()
        {
            switch (MouseButton)
            {
            case null:
                return(PlayerInput.KeyHit(Key));

            case 0:
                return(PlayerInput.LeftButtonClicked());

            case 1:
                return(PlayerInput.RightButtonClicked());

            case 2:
                return(PlayerInput.MidButtonClicked());

            case 3:
                return(PlayerInput.Mouse4ButtonClicked());

            case 4:
                return(PlayerInput.Mouse5ButtonClicked());

            case 5:
                return(PlayerInput.MouseWheelUpClicked());

            case 6:
                return(PlayerInput.MouseWheelDownClicked());
            }

            return(false);
        }
        public override void UpdateWhilePaused(float deltaTime)
        {
            if (CoroutineManager.IsCoroutineRunning("LevelTransition") || CoroutineManager.IsCoroutineRunning("SubmarineTransition") || gameOver)
            {
                return;
            }

            if (PlayerInput.RightButtonClicked() ||
                PlayerInput.KeyHit(Microsoft.Xna.Framework.Input.Keys.Escape))
            {
                ShowCampaignUI = false;
                if (GUIMessageBox.VisibleBox?.UserData is RoundSummary roundSummary &&
                    roundSummary.ContinueButton != null &&
                    roundSummary.ContinueButton.Visible)
                {
                    GUIMessageBox.MessageBoxes.Remove(GUIMessageBox.VisibleBox);
                }
            }

            if (CrewManager.ChatBox != null)
            {
                CrewManager.ChatBox.Update(deltaTime);
            }

            CrewManager.UpdateReports();
        }
Exemple #4
0
        partial void UpdateProjSpecific(float deltaTime)
        {
            if (GUI.DisableHUD)
            {
                return;
            }

            if (GameMode.IsRunning)
            {
                if (tabMenu == null)
                {
                    if (PlayerInput.KeyHit(InputType.InfoTab) && GUI.KeyboardDispatcher.Subscriber is GUITextBox == false)
                    {
                        ToggleTabMenu();
                    }
                }
                else
                {
                    tabMenu.Update();

                    if (PlayerInput.KeyHit(InputType.InfoTab) && GUI.KeyboardDispatcher.Subscriber is GUITextBox == false)
                    {
                        ToggleTabMenu();
                    }
                }
            }
            else
            {
                if (tabMenu != null)
                {
                    ToggleTabMenu();
                }
            }

            if (GameMain.NetworkMember != null)
            {
                if (GameMain.NetLobbyScreen?.HeadSelectionList != null)
                {
                    if (PlayerInput.PrimaryMouseButtonDown() && !GUI.IsMouseOn(GameMain.NetLobbyScreen.HeadSelectionList))
                    {
                        if (GameMain.NetLobbyScreen.HeadSelectionList != null)
                        {
                            GameMain.NetLobbyScreen.HeadSelectionList.Visible = false;
                        }
                    }
                }
                if (GameMain.NetLobbyScreen?.JobSelectionFrame != null)
                {
                    if (PlayerInput.PrimaryMouseButtonDown() && !GUI.IsMouseOn(GameMain.NetLobbyScreen.JobSelectionFrame))
                    {
                        GameMain.NetLobbyScreen.JobList.Deselect();
                        if (GameMain.NetLobbyScreen.JobSelectionFrame != null)
                        {
                            GameMain.NetLobbyScreen.JobSelectionFrame.Visible = false;
                        }
                    }
                }
            }
        }
Exemple #5
0
        public static void Update(GameMain game, float deltaTime)
        {
            lock (queuedMessages)
            {
                while (queuedMessages.Count > 0)
                {
                    AddMessage(queuedMessages.Dequeue());
                }
            }

            if (activeQuestionText != null &&
                (listBox.children.Count == 0 || listBox.children[listBox.children.Count - 1] != activeQuestionText))
            {
                listBox.children.Remove(activeQuestionText);
                listBox.children.Add(activeQuestionText);
            }

            if (PlayerInput.KeyHit(Keys.F3))
            {
                isOpen = !isOpen;
                if (isOpen)
                {
                    textBox.Select();
                    AddToGUIUpdateList();
                }
                else
                {
                    GUIComponent.ForceMouseOn(null);
                    textBox.Deselect();
                }
            }

            if (isOpen)
            {
                frame.Update(deltaTime);

                Character.DisableControls = true;

                if (PlayerInput.KeyHit(Keys.Up))
                {
                    textBox.Text = SelectMessage(-1);
                }
                else if (PlayerInput.KeyHit(Keys.Down))
                {
                    textBox.Text = SelectMessage(1);
                }
                else if (PlayerInput.KeyHit(Keys.Tab))
                {
                    textBox.Text = AutoComplete(textBox.Text);
                }

                if (PlayerInput.KeyHit(Keys.Enter))
                {
                    ExecuteCommand(textBox.Text);
                    textBox.Text = "";
                }
            }
        }
Exemple #6
0
        public void Update(float deltaTime)
        {
            if (!Selected)
            {
                return;
            }

            if (widgets.Values.Any(w => w.IsSelected))
            {
                return;
            }

            if (PlayerInput.PrimaryMouseButtonDown() && !disableMove && IsMouseOn())
            {
                isDragging = true;
            }

            if (isDragging)
            {
                Camera cam = Screen.Selected.Cam;
                if (PlayerInput.MouseSpeed != Vector2.Zero)
                {
                    Vector2 mouseSpeed = PlayerInput.MouseSpeed;
                    if (DrawTarget == DrawTargetType.World)
                    {
                        mouseSpeed /= cam.Zoom;
                    }

                    Position += mouseSpeed;
                    UpdateRectangle();
                }
            }

            if (PlayerInput.KeyDown(Keys.OemPlus) || PlayerInput.KeyDown(Keys.Up))
            {
                Opacity += 0.01f;
            }

            if (PlayerInput.KeyDown(Keys.OemMinus) || PlayerInput.KeyDown(Keys.Down))
            {
                Opacity -= 0.01f;
            }

            if (PlayerInput.KeyHit(Keys.D0))
            {
                Opacity = 1f;
            }

            Opacity = Math.Clamp(Opacity, 0, 1f);

            if (!PlayerInput.PrimaryMouseButtonHeld())
            {
                isDragging = false;
            }
        }
Exemple #7
0
        public void DebugDrawHUD(SpriteBatch spriteBatch, int y)
        {
            GUI.DrawString(spriteBatch, new Vector2(10, y), "EventManager", Color.White, Color.Black * 0.6f, 0, GUI.SmallFont);
            GUI.DrawString(spriteBatch, new Vector2(15, y + 20), "Event cooldown: " + eventCoolDown, Color.White, Color.Black * 0.6f, 0, GUI.SmallFont);
            GUI.DrawString(spriteBatch, new Vector2(15, y + 35), "Current intensity: " + (int)(currentIntensity * 100), Color.Lerp(Color.White, Color.Red, currentIntensity), Color.Black * 0.6f, 0, GUI.SmallFont);
            GUI.DrawString(spriteBatch, new Vector2(15, y + 50), "Target intensity: " + (int)(targetIntensity * 100), Color.Lerp(Color.White, Color.Red, targetIntensity), Color.Black * 0.6f, 0, GUI.SmallFont);

            GUI.DrawString(spriteBatch, new Vector2(15, y + 65), "AvgHealth: " + (int)(avgCrewHealth * 100), Color.Lerp(Color.Red, Color.Green, avgCrewHealth), Color.Black * 0.6f, 0, GUI.SmallFont);
            GUI.DrawString(spriteBatch, new Vector2(15, y + 80), "AvgHullIntegrity: " + (int)(avgHullIntegrity * 100), Color.Lerp(Color.Red, Color.Green, avgHullIntegrity), Color.Black * 0.6f, 0, GUI.SmallFont);
            GUI.DrawString(spriteBatch, new Vector2(15, y + 95), "FloodingAmount: " + (int)(floodingAmount * 100), Color.Lerp(Color.Green, Color.Red, floodingAmount), Color.Black * 0.6f, 0, GUI.SmallFont);
            GUI.DrawString(spriteBatch, new Vector2(15, y + 110), "FireAmount: " + (int)(fireAmount * 100), Color.Lerp(Color.Green, Color.Red, fireAmount), Color.Black * 0.6f, 0, GUI.SmallFont);
            GUI.DrawString(spriteBatch, new Vector2(15, y + 125), "EnemyDanger: " + (int)(enemyDanger * 100), Color.Lerp(Color.Green, Color.Red, enemyDanger), Color.Black * 0.6f, 0, GUI.SmallFont);

#if DEBUG
            if (PlayerInput.KeyDown(Microsoft.Xna.Framework.Input.Keys.LeftAlt) &&
                PlayerInput.KeyHit(Microsoft.Xna.Framework.Input.Keys.T))
            {
                eventCoolDown = 1.0f;
            }
#endif

            if (intensityGraph == null)
            {
                intensityGraph       = new Graph();
                targetIntensityGraph = new Graph();
            }

            intensityGraphUpdateInterval = 5.0f;
            if (Timing.TotalTime > lastIntensityUpdate + intensityGraphUpdateInterval)
            {
                intensityGraph.Update(currentIntensity);
                targetIntensityGraph.Update(targetIntensity);
                lastIntensityUpdate = (float)Timing.TotalTime;
            }

            Rectangle graphRect = new Rectangle(15, y + 150, 150, 50);

            GUI.DrawRectangle(spriteBatch, graphRect, Color.Black * 0.5f, true);
            intensityGraph.Draw(spriteBatch, graphRect, 1.0f, 0.0f, Color.Lerp(Color.White, Color.Red, currentIntensity));
            targetIntensityGraph.Draw(spriteBatch, graphRect, 1.0f, 0.0f, Color.Lerp(Color.White, Color.Red, targetIntensity) * 0.5f);

            GUI.DrawLine(spriteBatch,
                         new Vector2(graphRect.Right, graphRect.Y + graphRect.Height * (1.0f - eventThreshold)),
                         new Vector2(graphRect.Right + 5, graphRect.Y + graphRect.Height * (1.0f - eventThreshold)), Color.Orange, 0, 1);

            y = graphRect.Bottom + 20;
            foreach (ScriptedEventSet eventSet in selectedEventSets)
            {
                GUI.DrawString(spriteBatch, new Vector2(graphRect.X, y),
                               "- new event after " + (int)(eventSet.MinDistanceTraveled * 100.0f) + "% or " + (int)(eventSet.MinMissionTime / 60.0f) + "min passed",
                               Color.White * 0.8f, null, 0, GUI.SmallFont);
                y += 15;
            }
        }
Exemple #8
0
        public override void Update(float deltaTime)
        {
            base.Update(deltaTime);

            if (PlayerInput.KeyHit(Microsoft.Xna.Framework.Input.Keys.Escape))
            {
                GUIMessageBox.MessageBoxes.RemoveAll(mb => mb.UserData is RoundSummary);
            }

            if (ShowCampaignUI || ForceMapUI)
            {
                CampaignUI?.Update(deltaTime);
            }
        }
Exemple #9
0
        public static Vector2 GetNudgeAmount(bool doHold = true)
        {
            Vector2 nudgeAmount = Vector2.Zero;

            if (doHold)
            {
                int up    = PlayerInput.KeyDown(Keys.Up) ? 1 : 0,
                    down  = PlayerInput.KeyDown(Keys.Down) ? -1 : 0,
                    left  = PlayerInput.KeyDown(Keys.Left) ? -1 : 0,
                    right = PlayerInput.KeyDown(Keys.Right) ? 1 : 0;

                int xKeysDown = (left + right);
                int yKeysDown = (up + down);

                if (xKeysDown != 0 || yKeysDown != 0)
                {
                    keyDelay += (float)Timing.Step;
                }
                else
                {
                    keyDelay = 0;
                }


                if (keyDelay >= 0.5f)
                {
                    nudgeAmount.Y = yKeysDown;
                    nudgeAmount.X = xKeysDown;
                }
            }

            if (PlayerInput.KeyHit(Keys.Up))
            {
                nudgeAmount.Y = 1f;
            }
            if (PlayerInput.KeyHit(Keys.Down))
            {
                nudgeAmount.Y = -1f;
            }
            if (PlayerInput.KeyHit(Keys.Left))
            {
                nudgeAmount.X = -1f;
            }
            if (PlayerInput.KeyHit(Keys.Right))
            {
                nudgeAmount.X = 1f;
            }

            return(nudgeAmount);
        }
Exemple #10
0
        private void DrawSplashScreen(SpriteBatch spriteBatch)
        {
            bool vsync = GameMain.Config.VSyncEnabled;

            if (videoPlayer == null)
            {
                // Enforce the vsync so that the video player doesn't eat all the vram
                if (!GameMain.Config.VSyncEnabled)
                {
                    GameMain.Config.VSyncEnabled = true;
                    GameMain.Instance.ApplyGraphicsSettings();
                }
                videoPlayer = new VideoPlayer();
                videoPlayer.Play(splashScreenVideo);
                videoPlayer.Volume = GameMain.Config.SoundVolume;
            }
            else
            {
                Texture2D videoTexture = null;

                if (videoPlayer.State == MediaState.Stopped)
                {
                    videoPlayer.Dispose();
                    videoPlayer = null;

                    splashScreenVideo.Dispose();
                    splashScreenVideo = null;
                    // If the vsync was enforced, restore the user preference
                    if (GameMain.Config.VSyncEnabled != vsync)
                    {
                        GameMain.Config.VSyncEnabled = vsync;
                        GameMain.Instance.ApplyGraphicsSettings();
                    }
                }
                else
                {
                    videoTexture = videoPlayer.GetTexture();

                    spriteBatch.Begin();
                    spriteBatch.Draw(videoTexture, new Rectangle(0, 0, GameMain.GraphicsWidth, GameMain.GraphicsHeight), Color.White);
                    spriteBatch.End();

                    if (PlayerInput.KeyHit(Keys.Space) || PlayerInput.KeyHit(Keys.Enter) || PlayerInput.LeftButtonDown())
                    {
                        videoPlayer.Stop();
                    }
                }
            }
        }
Exemple #11
0
        public bool IsHit()
        {
            if (mouseButton == null)
            {
                return(PlayerInput.KeyHit(keyBinding));
            }
            else if (mouseButton == 0)
            {
                return(PlayerInput.LeftButtonClicked());
            }
            else if (mouseButton == 1)
            {
                return(PlayerInput.RightButtonClicked());
            }

            return(false);
        }
        public void Update()
        {
            if (ContentRefreshRequired)
            {
                RefreshSubmarineDisplay(true);
            }

            // Input
            if (PlayerInput.KeyHit(Keys.Left))
            {
                SelectSubmarine(subsToShow.IndexOf(selectedSubmarine), -1);
            }
            else if (PlayerInput.KeyHit(Keys.Right))
            {
                SelectSubmarine(subsToShow.IndexOf(selectedSubmarine), 1);
            }
        }
Exemple #13
0
        public static void Update(GameMain game, float deltaTime)
        {
            if (PlayerInput.KeyHit(Keys.F3))
            {
                isOpen = !isOpen;
                if (isOpen)
                {
                    textBox.Select();
                    AddToGUIUpdateList();
                }
                else
                {
                    GUIComponent.ForceMouseOn(null);
                    textBox.Deselect();
                }

                //keyboardDispatcher.Subscriber = (isOpen) ? textBox : null;
            }

            if (isOpen)
            {
                frame.Update(deltaTime);

                Character.DisableControls = true;

                if (PlayerInput.KeyHit(Keys.Up))
                {
                    SelectMessage(-1);
                }
                else if (PlayerInput.KeyHit(Keys.Down))
                {
                    SelectMessage(1);
                }

                //textBox.Update(deltaTime);

                if (PlayerInput.KeyDown(Keys.Enter) && textBox.Text != "")
                {
                    ExecuteCommand(textBox.Text, game);
                    textBox.Text = "";

                    //selectedIndex = messages.Count;
                }
            }
        }
Exemple #14
0
        private void DrawSplashScreen(SpriteBatch spriteBatch, GraphicsDevice graphics)
        {
            if (currSplashScreen == null && PendingSplashScreens.Count == 0)
            {
                return;
            }

            if (currSplashScreen == null)
            {
                var    newSplashScreen = PendingSplashScreens.Dequeue();
                string fileName        = newSplashScreen.First;
                Point  resolution      = newSplashScreen.Second;
                try
                {
                    currSplashScreen           = new Video(graphics, GameMain.SoundManager, fileName, (uint)resolution.X, (uint)resolution.Y);
                    currSplashScreen.AudioGain = newSplashScreen.Third;
                    videoStartTime             = DateTime.Now;
                }
                catch (Exception e)
                {
                    GameMain.Config.EnableSplashScreen = false;
                    DebugConsole.ThrowError("Playing the splash screen \"" + fileName + "\" failed.", e);
                    PendingSplashScreens.Clear();
                    currSplashScreen = null;
                }
            }

            if (currSplashScreen.IsPlaying)
            {
                spriteBatch.Begin();
                spriteBatch.Draw(currSplashScreen.GetTexture(), new Rectangle(0, 0, GameMain.GraphicsWidth, GameMain.GraphicsHeight), Color.White);
                spriteBatch.End();

                if (GameMain.WindowActive && (PlayerInput.KeyHit(Keys.Space) || PlayerInput.KeyHit(Keys.Enter) || PlayerInput.LeftButtonDown()))
                {
                    currSplashScreen.Dispose(); currSplashScreen = null;
                }
            }
            else if (DateTime.Now > videoStartTime + new TimeSpan(0, 0, 0, 0, milliseconds: 500))
            {
                currSplashScreen.Dispose(); currSplashScreen = null;
            }
        }
Exemple #15
0
        partial void UpdateProjSpecific(float deltaTime)
        {
            if (GUI.DisableHUD)
            {
                return;
            }

            if (tabMenu == null)
            {
                if (PlayerInput.KeyHit(InputType.InfoTab) && !(GUI.KeyboardDispatcher.Subscriber is GUITextBox))
                {
                    ToggleTabMenu();
                }
            }
            else
            {
                tabMenu.Update();
                if ((PlayerInput.KeyHit(InputType.InfoTab) || PlayerInput.KeyHit(Microsoft.Xna.Framework.Input.Keys.Escape)) &&
                    !(GUI.KeyboardDispatcher.Subscriber is GUITextBox))
                {
                    ToggleTabMenu();
                }
            }

            UpdateTalentNotificationIndicator(talentPointNotification);

            if (GameMain.NetworkMember != null)
            {
                GameMain.NetLobbyScreen?.CharacterAppearanceCustomizationMenu?.Update();
                if (GameMain.NetLobbyScreen?.JobSelectionFrame != null)
                {
                    if (GameMain.NetLobbyScreen.JobSelectionFrame != null && PlayerInput.PrimaryMouseButtonDown() && !GUI.IsMouseOn(GameMain.NetLobbyScreen.JobSelectionFrame))
                    {
                        GameMain.NetLobbyScreen.JobList.Deselect();
                        GameMain.NetLobbyScreen.JobSelectionFrame.Visible = false;
                    }
                }
            }

            HintManager.Update();
        }
Exemple #16
0
        private void DrawSplashScreen(SpriteBatch spriteBatch)
        {
            if (SplashScreen != null)
            {
                if (SplashScreen.IsPlaying)
                {
                    spriteBatch.Begin();
                    spriteBatch.Draw(SplashScreen.GetTexture(), new Rectangle(0, 0, GameMain.GraphicsWidth, GameMain.GraphicsHeight), Color.White);
                    spriteBatch.End();

                    if (PlayerInput.KeyHit(Keys.Space) || PlayerInput.KeyHit(Keys.Enter) || PlayerInput.LeftButtonDown())
                    {
                        SplashScreen.Dispose(); SplashScreen = null;
                    }
                }
                else
                {
                    SplashScreen.Dispose(); SplashScreen = null;
                }
            }
        }
Exemple #17
0
        public void Update()
        {
            if (currentVideo == null)
            {
                return;
            }

            if (PlayerInput.KeyHit(Keys.Enter) || PlayerInput.KeyHit(Keys.Escape))
            {
                DisposeVideo(null, null);
                return;
            }

            if (currentVideo.IsPlaying)
            {
                return;
            }

            currentVideo.Dispose();
            currentVideo = null;
            currentVideo = CreateVideo(scaledVideoResolution);
        }
Exemple #18
0
        public bool IsHit()
        {
            switch (MouseButton)
            {
            case MouseButton.None:
                return(PlayerInput.KeyHit(Key));

            case MouseButton.PrimaryMouse:
                return(PlayerInput.PrimaryMouseButtonClicked());

            case MouseButton.SecondaryMouse:
                return(PlayerInput.SecondaryMouseButtonClicked());

            case MouseButton.LeftMouse:
                return(PlayerInput.LeftButtonClicked());

            case MouseButton.RightMouse:
                return(PlayerInput.RightButtonClicked());

            case MouseButton.MiddleMouse:
                return(PlayerInput.MidButtonClicked());

            case MouseButton.MouseButton4:
                return(PlayerInput.Mouse4ButtonClicked());

            case MouseButton.MouseButton5:
                return(PlayerInput.Mouse5ButtonClicked());

            case MouseButton.MouseWheelUp:
                return(PlayerInput.MouseWheelUpClicked());

            case MouseButton.MouseWheelDown:
                return(PlayerInput.MouseWheelDownClicked());
            }

            return(false);
        }
        public static bool CloseHUD(Rectangle rect)
        {
            // Always close when hitting escape
            if (PlayerInput.KeyHit(Microsoft.Xna.Framework.Input.Keys.Escape))
            {
                return(true);
            }

            //don't close when the cursor is on a UI element
            if (GUI.MouseOn != null)
            {
                return(false);
            }

            //don't close when hovering over an inventory element
            if (Inventory.IsMouseOnInventory())
            {
                return(false);
            }

            bool input = PlayerInput.LeftButtonDown() || PlayerInput.RightButtonClicked();

            return(input && !rect.Contains(PlayerInput.MousePosition));
        }
        public override void Update(float deltaTime, Camera cam, bool isSubInventory = false)
        {
            if (!AccessibleWhenAlive && !character.IsDead)
            {
                syncItemsDelay = Math.Max(syncItemsDelay - deltaTime, 0.0f);
                return;
            }

            base.Update(deltaTime, cam);

            bool hoverOnInventory = GUI.MouseOn == null &&
                                    ((selectedSlot != null && selectedSlot.IsSubSlot) || (draggingItem != null && (draggingSlot == null || !draggingSlot.MouseOn())));

            if (CharacterHealth.OpenHealthWindow != null)
            {
                hoverOnInventory = true;
            }

            if (layout == Layout.Default && hideButton.Visible)
            {
                hideButton.AddToGUIUpdateList();
                hideButton.UpdateManually(deltaTime, alsoChildren: true);

                hidePersonalSlotsState = hidePersonalSlots ?
                                         Math.Min(hidePersonalSlotsState + deltaTime * 5.0f, 1.0f) :
                                         Math.Max(hidePersonalSlotsState - deltaTime * 5.0f, 0.0f);

                for (int i = 0; i < slots.Length; i++)
                {
                    if (!PersonalSlots.HasFlag(SlotTypes[i]))
                    {
                        continue;
                    }
                    if (HidePersonalSlots)
                    {
                        if (selectedSlot?.Slot == slots[i])
                        {
                            selectedSlot = null;
                        }
                        highlightedSubInventorySlots.RemoveWhere(s => s.Slot == slots[i]);
                    }
                    slots[i].DrawOffset = Vector2.Lerp(Vector2.Zero, new Vector2(personalSlotArea.Width, 0.0f), hidePersonalSlotsState);
                }
            }

            if (hoverOnInventory)
            {
                HideTimer = 0.5f;
            }
            if (HideTimer > 0.0f)
            {
                HideTimer -= deltaTime;
            }

            for (int i = 0; i < capacity; i++)
            {
                if (Items[i] != null && Items[i] != draggingItem && Character.Controlled?.Inventory == this &&
                    GUI.KeyboardDispatcher.Subscriber == null &&
                    slots[i].QuickUseKey != Keys.None && PlayerInput.KeyHit(slots[i].QuickUseKey))
                {
                    QuickUseItem(Items[i], true, false, true);
                }
            }

            //force personal slots open if an item is running out of battery/fuel/oxygen/etc
            if (hidePersonalSlots)
            {
                for (int i = 0; i < slots.Length; i++)
                {
                    if (Items[i]?.OwnInventory != null && Items[i].OwnInventory.Capacity == 1 && PersonalSlots.HasFlag(SlotTypes[i]))
                    {
                        if (Items[i].OwnInventory.Items[0] != null &&
                            Items[i].OwnInventory.Items[0].Condition > 0.0f &&
                            Items[i].OwnInventory.Items[0].Condition / Items[i].OwnInventory.Items[0].MaxCondition < 0.15f)
                        {
                            hidePersonalSlots = false;
                        }
                    }
                }
            }

            List <SlotReference> hideSubInventories = new List <SlotReference>();

            foreach (var highlightedSubInventorySlot in highlightedSubInventorySlots)
            {
                if (highlightedSubInventorySlot.ParentInventory == this)
                {
                    UpdateSubInventory(deltaTime, highlightedSubInventorySlot.SlotIndex, cam);
                }

                Rectangle hoverArea = GetSubInventoryHoverArea(highlightedSubInventorySlot);
                if (highlightedSubInventorySlot.Inventory?.slots == null || (!hoverArea.Contains(PlayerInput.MousePosition)))
                {
                    hideSubInventories.Add(highlightedSubInventorySlot);
                }
                else
                {
                    highlightedSubInventorySlot.Inventory.HideTimer = 1.0f;
                }
            }

            if (doubleClickedItem != null)
            {
                QuickUseItem(doubleClickedItem, true, true, true);
            }

            //activate the subinventory of the currently selected slot
            if (selectedSlot?.ParentInventory == this)
            {
                var subInventory = GetSubInventory(selectedSlot.SlotIndex);
                if (subInventory != null)
                {
                    selectedSlot.Inventory = subInventory;
                    if (!highlightedSubInventorySlots.Any(s => s.Inventory == subInventory))
                    {
                        var slot = selectedSlot;
                        highlightedSubInventorySlots.Add(selectedSlot);
                        UpdateSubInventory(deltaTime, selectedSlot.SlotIndex, cam);

                        //hide previously opened subinventories if this one overlaps with them
                        Rectangle hoverArea = GetSubInventoryHoverArea(slot);
                        foreach (SlotReference highlightedSubInventorySlot in highlightedSubInventorySlots)
                        {
                            if (highlightedSubInventorySlot == slot)
                            {
                                continue;
                            }
                            if (hoverArea.Intersects(GetSubInventoryHoverArea(highlightedSubInventorySlot)))
                            {
                                hideSubInventories.Add(highlightedSubInventorySlot);
                                highlightedSubInventorySlot.Inventory.HideTimer = 0.0f;
                            }
                        }
                    }
                }
            }

            foreach (var subInventorySlot in hideSubInventories)
            {
                if (subInventorySlot.Inventory == null)
                {
                    continue;
                }
                subInventorySlot.Inventory.HideTimer -= deltaTime;
                if (subInventorySlot.Inventory.HideTimer <= 0.0f)
                {
                    highlightedSubInventorySlots.Remove(subInventorySlot);
                }
            }

            for (int i = 0; i < capacity; i++)
            {
                if (Items[i] != null && Items[i].AllowedSlots.Any(a => a != InvSlotType.Any))
                {
                    slots[i].EquipButtonState = slots[i].EquipButtonRect.Contains(PlayerInput.MousePosition) ?
                                                GUIComponent.ComponentState.Hover : GUIComponent.ComponentState.None;
                    if (PlayerInput.LeftButtonHeld() && PlayerInput.RightButtonHeld())
                    {
                        slots[i].EquipButtonState = GUIComponent.ComponentState.None;
                    }

                    if (slots[i].EquipButtonState != GUIComponent.ComponentState.Hover)
                    {
                        slots[i].QuickUseTimer = Math.Max(0.0f, slots[i].QuickUseTimer - deltaTime * 5.0f);
                        continue;
                    }

                    var quickUseAction = GetQuickUseAction(Items[i], allowEquip: true, allowInventorySwap: false, allowApplyTreatment: false);
                    slots[i].QuickUseButtonToolTip = quickUseAction == QuickUseAction.None ?
                                                     "" : TextManager.Get("QuickUseAction." + quickUseAction.ToString());

                    //equipped item that can't be put in the inventory, use delayed dropping
                    if (quickUseAction == QuickUseAction.Drop)
                    {
                        slots[i].QuickUseButtonToolTip =
                            TextManager.Get("QuickUseAction.HoldToUnequip", returnNull: true) ??
                            (GameMain.Config.Language == "English" ?  "Hold to unequip" : TextManager.Get("QuickUseAction.Unequip"));

                        if (PlayerInput.LeftButtonHeld())
                        {
                            slots[i].QuickUseTimer = Math.Max(0.1f, slots[i].QuickUseTimer + deltaTime);
                            if (slots[i].QuickUseTimer >= 1.0f)
                            {
                                Items[i].Drop(Character.Controlled);
                                GUI.PlayUISound(GUISoundType.DropItem);
                            }
                        }
                        else
                        {
                            slots[i].QuickUseTimer = Math.Max(0.0f, slots[i].QuickUseTimer - deltaTime * 5.0f);
                        }
                    }
                    else
                    {
                        if (PlayerInput.LeftButtonDown())
                        {
                            slots[i].EquipButtonState = GUIComponent.ComponentState.Pressed;
                        }
                        if (PlayerInput.LeftButtonClicked())
                        {
                            QuickUseItem(Items[i], allowEquip: true, allowInventorySwap: false, allowApplyTreatment: false);
                        }
                    }
                }
            }


            //cancel dragging if too far away from the container of the dragged item
            if (draggingItem != null)
            {
                var rootContainer = draggingItem.GetRootContainer();
                var rootInventory = draggingItem.ParentInventory;

                if (rootContainer != null)
                {
                    rootInventory = rootContainer.ParentInventory ?? rootContainer.GetComponent <ItemContainer>().Inventory;
                }

                if (rootInventory != null &&
                    rootInventory.Owner != Character.Controlled &&
                    rootInventory.Owner != Character.Controlled.SelectedConstruction &&
                    rootInventory.Owner != Character.Controlled.SelectedCharacter)
                {
                    //allow interacting if the container is linked to the item the character is interacting with
                    if (!(rootContainer != null &&
                          rootContainer.DisplaySideBySideWhenLinked &&
                          Character.Controlled.SelectedConstruction != null &&
                          rootContainer.linkedTo.Contains(Character.Controlled.SelectedConstruction)))
                    {
                        draggingItem = null;
                    }
                }
            }

            doubleClickedItem = null;
        }
 public override void Update(double deltaTime)
 {
     base.Update(deltaTime);
     Widget.EnableMultiSelect  = PlayerInput.KeyDown(Keys.LeftControl);
     spriteList.SelectMultiple = Widget.EnableMultiSelect;
     // Select rects with the mouse
     if (Widget.selectedWidgets.None() || Widget.EnableMultiSelect)
     {
         if (selectedTexture != null)
         {
             foreach (Sprite sprite in loadedSprites)
             {
                 if (sprite.Texture != selectedTexture)
                 {
                     continue;
                 }
                 if (PlayerInput.LeftButtonClicked())
                 {
                     var scaledRect = new Rectangle(textureRect.Location + sprite.SourceRect.Location.Multiply(zoom), sprite.SourceRect.Size.Multiply(zoom));
                     if (scaledRect.Contains(PlayerInput.MousePosition))
                     {
                         spriteList.Select(sprite, autoScroll: false);
                         UpdateScrollBar(spriteList);
                         UpdateScrollBar(textureList);
                     }
                 }
             }
         }
     }
     if (GUI.MouseOn == null)
     {
         if (PlayerInput.ScrollWheelSpeed != 0)
         {
             zoom = MathHelper.Clamp(zoom + PlayerInput.ScrollWheelSpeed * (float)deltaTime * 0.05f * zoom, minZoom, maxZoom);
             zoomBar.BarScroll = GetBarScrollValue();
         }
         widgets.Values.ForEach(w => w.Update((float)deltaTime));
         if (PlayerInput.MidButtonHeld())
         {
             // "Camera" Pan
             Vector2 moveSpeed = PlayerInput.MouseSpeed * (float)deltaTime * 100.0f;
             viewAreaOffset += moveSpeed.ToPoint();
         }
     }
     if (PlayerInput.KeyHit(Keys.Left))
     {
         foreach (var sprite in selectedSprites)
         {
             var newRect = sprite.SourceRect;
             newRect.X--;
             UpdateSourceRect(sprite, newRect);
         }
     }
     if (PlayerInput.KeyHit(Keys.Right))
     {
         foreach (var sprite in selectedSprites)
         {
             var newRect = sprite.SourceRect;
             newRect.X++;
             UpdateSourceRect(sprite, newRect);
         }
     }
     if (PlayerInput.KeyHit(Keys.Down))
     {
         foreach (var sprite in selectedSprites)
         {
             var newRect = sprite.SourceRect;
             newRect.Y++;
             UpdateSourceRect(sprite, newRect);
         }
     }
     if (PlayerInput.KeyHit(Keys.Up))
     {
         foreach (var sprite in selectedSprites)
         {
             var newRect = sprite.SourceRect;
             newRect.Y--;
             UpdateSourceRect(sprite, newRect);
         }
     }
 }
        public override void Update(float deltaTime)
        {
            if (CoroutineManager.IsCoroutineRunning("LevelTransition") || Level.Loaded == null)
            {
                return;
            }

            if (ShowCampaignUI || ForceMapUI)
            {
                if (CampaignUI == null)
                {
                    InitCampaignUI();
                }
                Character.DisableControls = true;
            }

            base.Update(deltaTime);

            if (PlayerInput.SecondaryMouseButtonClicked() ||
                PlayerInput.KeyHit(Microsoft.Xna.Framework.Input.Keys.Escape))
            {
                ShowCampaignUI = false;
                if (GUIMessageBox.VisibleBox?.UserData is RoundSummary roundSummary &&
                    roundSummary.ContinueButton != null &&
                    roundSummary.ContinueButton.Visible)
                {
                    GUIMessageBox.MessageBoxes.Remove(GUIMessageBox.VisibleBox);
                }
            }

            if (!GUI.DisableHUD && !GUI.DisableUpperHUD)
            {
                endRoundButton.UpdateManually(deltaTime);
                ReadyCheckButton?.UpdateManually(deltaTime);
                if (CoroutineManager.IsCoroutineRunning("LevelTransition") || ForceMapUI)
                {
                    return;
                }
            }

            if (Level.Loaded.Type == LevelData.LevelType.Outpost)
            {
                if (wasDocked)
                {
                    var  connectedSubs = Submarine.MainSub.GetConnectedSubs();
                    bool isDocked      = Level.Loaded.StartOutpost != null && connectedSubs.Contains(Level.Loaded.StartOutpost);
                    if (!isDocked)
                    {
                        //undocked from outpost, need to choose a destination
                        ForceMapUI = true;
                        if (CampaignUI == null)
                        {
                            InitCampaignUI();
                        }
                        CampaignUI.SelectTab(InteractionType.Map);
                    }
                }
                else
                {
                    //wasn't initially docked (sub doesn't have a docking port?)
                    // -> choose a destination when the sub is far enough from the start outpost
                    if (!Submarine.MainSub.AtStartPosition)
                    {
                        ForceMapUI = true;
                        if (CampaignUI == null)
                        {
                            InitCampaignUI();
                        }
                        CampaignUI.SelectTab(InteractionType.Map);
                    }
                }

                if (CampaignUI == null)
                {
                    InitCampaignUI();
                }
            }
            else
            {
                var transitionType = GetAvailableTransition(out _, out _);
                if (transitionType == TransitionType.None && CampaignUI?.SelectedTab == InteractionType.Map)
                {
                    ShowCampaignUI = false;
                }
            }
        }
        public override void Update(double deltaTime)
        {
            if (GameMain.GraphicsWidth != screenResolution.X || GameMain.GraphicsHeight != screenResolution.Y)
            {
                CreateGUI();
            }

            Cam.MoveCamera((float)deltaTime, true, true);
            Vector2 mousePos = Cam.ScreenToWorld(PlayerInput.MousePosition);

            mousePos.Y = -mousePos.Y;

            foreach (EditorNode node in nodeList)
            {
                if (PlayerInput.PrimaryMouseButtonDown())
                {
                    NodeConnection?connection = node.GetConnectionOnMouse(mousePos);
                    if (connection != null && connection.Type.NodeSide == NodeConnectionType.Side.Right)
                    {
                        if (connection.Type != NodeConnectionType.Out)
                        {
                            if (connection.ConnectedTo.Any())
                            {
                                return;
                            }
                        }

                        DraggedConnection = connection;
                    }
                }

                // ReSharper disable once AssignmentInConditionalExpression
                if (node.IsHighlighted = node.HeaderRectangle.Contains(mousePos))
                {
                    if (PlayerInput.PrimaryMouseButtonDown())
                    {
                        // Ctrl + clicking the headers add them to the "selection" that allows us to drag multiple nodes at once
                        if (PlayerInput.IsCtrlDown())
                        {
                            if (selectedNodes.Contains(node))
                            {
                                selectedNodes.Remove(node);
                            }
                            else
                            {
                                selectedNodes.Add(node);
                            }

                            node.IsSelected = selectedNodes.Contains(node);
                            break;
                        }

                        draggedNode = node;
                        dragOffset  = draggedNode.Position - mousePos;
                        foreach (EditorNode selectedNode in selectedNodes)
                        {
                            if (!markedNodes.ContainsKey(selectedNode))
                            {
                                markedNodes.Add(selectedNode, selectedNode.Position - mousePos);
                            }
                        }
                    }
                }

                if (PlayerInput.SecondaryMouseButtonClicked())
                {
                    NodeConnection?connection = node.GetConnectionOnMouse(mousePos);
                    if (node.GetDrawRectangle().Contains(mousePos) || connection != null)
                    {
                        CreateContextMenu(node, node.GetConnectionOnMouse(mousePos));
                        break;
                    }
                }
            }

            if (PlayerInput.SecondaryMouseButtonClicked())
            {
                foreach (var selectedNode in selectedNodes)
                {
                    selectedNode.IsSelected = false;
                }

                selectedNodes.Clear();
            }

            if (draggedNode != null)
            {
                if (!PlayerInput.PrimaryMouseButtonHeld())
                {
                    draggedNode = null;
                    markedNodes.Clear();
                }
                else
                {
                    Vector2 offsetChange = Vector2.Zero;
                    draggedNode.IsHighlighted = true;
                    draggedNode.Position      = mousePos + dragOffset;

                    if (PlayerInput.KeyHit(Keys.Up))
                    {
                        offsetChange.Y--;
                    }

                    if (PlayerInput.KeyHit(Keys.Down))
                    {
                        offsetChange.Y++;
                    }

                    if (PlayerInput.KeyHit(Keys.Left))
                    {
                        offsetChange.X--;
                    }

                    if (PlayerInput.KeyHit(Keys.Right))
                    {
                        offsetChange.X++;
                    }

                    dragOffset += offsetChange;

                    foreach (var(editorNode, offset) in markedNodes.Where(pair => pair.Key != draggedNode))
                    {
                        editorNode.Position = mousePos + offset;
                    }

                    if (offsetChange != Vector2.Zero)
                    {
                        foreach (var(key, value) in markedNodes.ToList())
                        {
                            markedNodes[key] = value + offsetChange;
                        }
                    }
                }
            }

            if (DraggedConnection != null)
            {
                if (!PlayerInput.PrimaryMouseButtonHeld())
                {
                    foreach (EditorNode node in nodeList)
                    {
                        var nodeOnMouse = node.GetConnectionOnMouse(mousePos);
                        if (nodeOnMouse != null && nodeOnMouse != DraggedConnection && nodeOnMouse.Type.NodeSide == NodeConnectionType.Side.Left)
                        {
                            if (!DraggedConnection.CanConnect(nodeOnMouse))
                            {
                                continue;
                            }

                            nodeOnMouse.ClearConnections();
                            DraggedConnection.Parent.Connect(DraggedConnection, nodeOnMouse);
                            break;
                        }
                    }

                    DraggedConnection = null;
                }
                else
                {
                    DraggingPosition = mousePos;
                }
            }
            else
            {
                DraggingPosition = Vector2.Zero;
            }

            if (contextMenu != null)
            {
                Rectangle expandedRect = contextMenu.Rect;
                expandedRect.Inflate(20, 20);
                if (!expandedRect.Contains(PlayerInput.MousePosition))
                {
                    contextMenu = null;
                }
            }

            if (PlayerInput.MidButtonHeld())
            {
                Vector2 moveSpeed = PlayerInput.MouseSpeed * (float)deltaTime * 60.0f / Cam.Zoom;
                moveSpeed.X   = -moveSpeed.X;
                Cam.Position += moveSpeed;
            }

            base.Update(deltaTime);
        }
Exemple #24
0
        public static void UpdateEditor(Camera cam)
        {
            if (highlightedListBox != null)
            {
                highlightedListBox.UpdateManually((float)Timing.Step);
            }

            if (editingHUD != null)
            {
                if (selectedList.Count == 0 || editingHUD.UserData != selectedList[0])
                {
                    foreach (GUIComponent component in editingHUD.Children)
                    {
                        var textBox = component as GUITextBox;
                        if (textBox == null)
                        {
                            continue;
                        }
                        textBox.Deselect();
                    }
                    editingHUD = null;
                }
            }

            if (selectedList.Count == 0)
            {
                return;
            }

            if (selectedList.Count == 1)
            {
                selectedList[0].UpdateEditing(cam);
                if (selectedList[0].ResizeHorizontal || selectedList[0].ResizeVertical)
                {
                    selectedList[0].UpdateResizing(cam);
                }
            }

            if ((PlayerInput.KeyDown(Keys.LeftControl) || PlayerInput.KeyDown(Keys.RightControl)))
            {
                //TODO: a UI button for flipping entities
                if (PlayerInput.KeyHit(Keys.N))
                {
                    float minX = selectedList[0].WorldRect.X, maxX = selectedList[0].WorldRect.Right;
                    for (int i = 0; i < selectedList.Count; i++)
                    {
                        minX = Math.Min(minX, selectedList[i].WorldRect.X);
                        maxX = Math.Max(maxX, selectedList[i].WorldRect.Right);
                    }

                    float centerX = (minX + maxX) / 2.0f;
                    foreach (MapEntity me in selectedList)
                    {
                        me.FlipX(false);
                        me.Move(new Vector2((centerX - me.WorldPosition.X) * 2.0f, 0.0f));
                    }
                }
                else if (PlayerInput.KeyHit(Keys.M))
                {
                    float minY = selectedList[0].WorldRect.Y - selectedList[0].WorldRect.Height, maxY = selectedList[0].WorldRect.Y;
                    for (int i = 0; i < selectedList.Count; i++)
                    {
                        minY = Math.Min(minY, selectedList[i].WorldRect.Y - selectedList[i].WorldRect.Height);
                        maxY = Math.Max(maxY, selectedList[i].WorldRect.Y);
                    }

                    float centerY = (minY + maxY) / 2.0f;
                    foreach (MapEntity me in selectedList)
                    {
                        me.FlipY(false);
                        me.Move(new Vector2(0.0f, (centerY - me.WorldPosition.Y) * 2.0f));
                    }
                }
            }
        }
Exemple #25
0
        /// <summary>
        /// Update the selection logic in submarine editor
        /// </summary>
        public static void UpdateSelecting(Camera cam)
        {
            if (resizing)
            {
                if (selectedList.Count == 0)
                {
                    resizing = false;
                }
                return;
            }

            foreach (MapEntity e in mapEntityList)
            {
                e.isHighlighted = false;
            }

            if (DisableSelect)
            {
                DisableSelect = false;
                return;
            }

            if (GUI.MouseOn != null || !PlayerInput.MouseInsideWindow)
            {
                if (highlightedListBox == null ||
                    (GUI.MouseOn != highlightedListBox && !highlightedListBox.IsParentOf(GUI.MouseOn)))
                {
                    UpdateHighlightedListBox(null);
                    return;
                }
            }

            if (MapEntityPrefab.Selected != null)
            {
                selectionPos = Vector2.Zero;
                selectedList.Clear();
                return;
            }

            if (PlayerInput.KeyDown(Keys.Delete))
            {
                selectedList.ForEach(e => e.Remove());
                selectedList.Clear();
            }

            if (PlayerInput.KeyDown(Keys.LeftControl) || PlayerInput.KeyDown(Keys.RightControl))
            {
                if (PlayerInput.KeyHit(Keys.C))
                {
                    CopyEntities(selectedList);
                }
                else if (PlayerInput.KeyHit(Keys.X))
                {
                    CopyEntities(selectedList);

                    selectedList.ForEach(e => e.Remove());
                    selectedList.Clear();
                }
                else if (copiedList.Count > 0 && PlayerInput.KeyHit(Keys.V))
                {
                    List <MapEntity> prevEntities = new List <MapEntity>(mapEntityList);
                    Clone(copiedList);

                    var clones = mapEntityList.Except(prevEntities).ToList();

                    Vector2 center = Vector2.Zero;
                    clones.ForEach(c => center += c.WorldPosition);
                    center = Submarine.VectorToWorldGrid(center / clones.Count);

                    Vector2 moveAmount = Submarine.VectorToWorldGrid(cam.WorldViewCenter - center);

                    selectedList = new List <MapEntity>(clones);
                    foreach (MapEntity clone in selectedList)
                    {
                        clone.Move(moveAmount);
                        clone.Submarine = Submarine.MainSub;
                    }
                }
                else if (PlayerInput.KeyHit(Keys.G))
                {
                    if (selectedList.Any())
                    {
                        if (SelectionGroups.ContainsKey(selectedList.Last()))
                        {
                            // Ungroup all selected
                            selectedList.ForEach(e => SelectionGroups.Remove(e));
                        }
                        else
                        {
                            foreach (var entity in selectedList)
                            {
                                // Remove the old group, if any
                                SelectionGroups.Remove(entity);
                                // Create a group that can be accessed with any member
                                SelectionGroups.Add(entity, selectedList);
                            }
                        }
                    }
                }
                else if (PlayerInput.KeyHit(Keys.Z))
                {
                    SetPreviousRects(e => e.rectMemento.Undo());
                }
                else if (PlayerInput.KeyHit(Keys.R))
                {
                    SetPreviousRects(e => e.rectMemento.Redo());
                }
                void SetPreviousRects(Func <MapEntity, Rectangle> memoryMethod)
                {
                    foreach (var e in SelectedList)
                    {
                        if (e.rectMemento != null)
                        {
                            Point diff = memoryMethod(e).Location - e.Rect.Location;
                            // We have to call the move method, because there's a lot more than just storing the rect (in some cases)
                            // We also have to reassign the rect, because the move method does not set the width and height. They might have changed too.
                            // The Rect property is virtual and it's overridden for structs. Setting the rect via the property should automatically recreate the sections for resizable structures.
                            e.Move(diff.ToVector2());
                            e.Rect = e.rectMemento.Current;
                        }
                    }
                }
            }

            Vector2 position = cam.ScreenToWorld(PlayerInput.MousePosition);

            MapEntity highLightedEntity = null;

            if (startMovingPos == Vector2.Zero)
            {
                List <MapEntity> highlightedEntities = new List <MapEntity>();
                if (highlightedListBox != null && highlightedListBox.IsParentOf(GUI.MouseOn))
                {
                    highLightedEntity = GUI.MouseOn.UserData as MapEntity;
                }
                else
                {
                    foreach (MapEntity e in mapEntityList)
                    {
                        if (!e.SelectableInEditor)
                        {
                            continue;
                        }

                        if (e.IsMouseOn(position))
                        {
                            int i = 0;
                            while (i < highlightedEntities.Count &&
                                   e.Sprite != null &&
                                   (highlightedEntities[i].Sprite == null || highlightedEntities[i].SpriteDepth < e.SpriteDepth))
                            {
                                i++;
                            }

                            highlightedEntities.Insert(i, e);

                            if (i == 0)
                            {
                                highLightedEntity = e;
                            }
                        }
                    }

                    if (PlayerInput.MouseSpeed.LengthSquared() > 10)
                    {
                        highlightTimer = 0.0f;
                    }
                    else
                    {
                        bool mouseNearHighlightBox = false;

                        if (highlightedListBox != null)
                        {
                            Rectangle expandedRect = highlightedListBox.Rect;
                            expandedRect.Inflate(20, 20);
                            mouseNearHighlightBox = expandedRect.Contains(PlayerInput.MousePosition);
                            if (!mouseNearHighlightBox)
                            {
                                highlightedListBox = null;
                            }
                        }

                        highlightTimer += (float)Timing.Step;
                        if (highlightTimer > 1.0f)
                        {
                            if (!mouseNearHighlightBox)
                            {
                                UpdateHighlightedListBox(highlightedEntities);
                                highlightTimer = 0.0f;
                            }
                        }
                    }
                }

                if (highLightedEntity != null)
                {
                    highLightedEntity.isHighlighted = true;
                }
            }

            Vector2 nudgeAmount = Vector2.Zero;

            if (PlayerInput.KeyHit(Keys.Up))
            {
                nudgeAmount.Y = 1f;
            }
            if (PlayerInput.KeyHit(Keys.Down))
            {
                nudgeAmount.Y = -1f;
            }
            if (PlayerInput.KeyHit(Keys.Left))
            {
                nudgeAmount.X = -1f;
            }
            if (PlayerInput.KeyHit(Keys.Right))
            {
                nudgeAmount.X = 1f;
            }
            if (nudgeAmount != Vector2.Zero)
            {
                foreach (MapEntity entityToNudge in selectedList)
                {
                    entityToNudge.Move(nudgeAmount);
                }
            }

            //started moving selected entities
            if (startMovingPos != Vector2.Zero)
            {
                if (PlayerInput.LeftButtonReleased())
                {
                    //mouse released -> move the entities to the new position of the mouse

                    Vector2 moveAmount = position - startMovingPos;
                    moveAmount.X = (float)(moveAmount.X > 0.0f ? Math.Floor(moveAmount.X / Submarine.GridSize.X) : Math.Ceiling(moveAmount.X / Submarine.GridSize.X)) * Submarine.GridSize.X;
                    moveAmount.Y = (float)(moveAmount.Y > 0.0f ? Math.Floor(moveAmount.Y / Submarine.GridSize.Y) : Math.Ceiling(moveAmount.Y / Submarine.GridSize.Y)) * Submarine.GridSize.Y;
                    if (Math.Abs(moveAmount.X) >= Submarine.GridSize.X || Math.Abs(moveAmount.Y) >= Submarine.GridSize.Y)
                    {
                        moveAmount = Submarine.VectorToWorldGrid(moveAmount);
                        //clone
                        if (PlayerInput.KeyDown(Keys.LeftControl) || PlayerInput.KeyDown(Keys.RightControl))
                        {
                            var clones = Clone(selectedList);
                            selectedList = clones;
                            selectedList.ForEach(c => c.Move(moveAmount));
                        }
                        else // move
                        {
                            foreach (MapEntity e in selectedList)
                            {
                                if (e.rectMemento == null)
                                {
                                    e.rectMemento = new Memento <Rectangle>();
                                    e.rectMemento.Store(e.Rect);
                                }
                                e.Move(moveAmount);
                                e.rectMemento.Store(e.Rect);
                            }
                        }
                    }
                    startMovingPos = Vector2.Zero;
                }
            }
            //started dragging a "selection rectangle"
            else if (selectionPos != Vector2.Zero)
            {
                selectionSize.X = position.X - selectionPos.X;
                selectionSize.Y = selectionPos.Y - position.Y;

                List <MapEntity> newSelection = new List <MapEntity>();// FindSelectedEntities(selectionPos, selectionSize);
                if (Math.Abs(selectionSize.X) > Submarine.GridSize.X || Math.Abs(selectionSize.Y) > Submarine.GridSize.Y)
                {
                    newSelection = FindSelectedEntities(selectionPos, selectionSize);
                }
                else
                {
                    if (highLightedEntity != null)
                    {
                        if (SelectionGroups.TryGetValue(highLightedEntity, out List <MapEntity> group))
                        {
                            newSelection.AddRange(group);
                        }
                        else
                        {
                            newSelection.Add(highLightedEntity);
                        }
                    }
                }

                if (PlayerInput.LeftButtonReleased())
                {
                    if (PlayerInput.KeyDown(Keys.LeftControl) ||
                        PlayerInput.KeyDown(Keys.RightControl))
                    {
                        foreach (MapEntity e in newSelection)
                        {
                            if (selectedList.Contains(e))
                            {
                                selectedList.Remove(e);
                            }
                            else
                            {
                                selectedList.Add(e);
                            }
                        }
                    }
                    else
                    {
                        selectedList = newSelection;
                    }

                    //select wire if both items it's connected to are selected
                    var selectedItems = selectedList.Where(e => e is Item).Cast <Item>().ToList();
                    foreach (Item item in selectedItems)
                    {
                        if (item.Connections == null)
                        {
                            continue;
                        }
                        foreach (Connection c in item.Connections)
                        {
                            foreach (Wire w in c.Wires)
                            {
                                if (w == null || selectedList.Contains(w.Item))
                                {
                                    continue;
                                }

                                if (w.OtherConnection(c) != null && selectedList.Contains(w.OtherConnection(c).Item))
                                {
                                    selectedList.Add(w.Item);
                                }
                            }
                        }
                    }

                    selectionPos  = Vector2.Zero;
                    selectionSize = Vector2.Zero;
                }
            }
            //default, not doing anything specific yet
            else
            {
                if (PlayerInput.LeftButtonHeld() &&
                    PlayerInput.KeyUp(Keys.Space) &&
                    (highlightedListBox == null || (GUI.MouseOn != highlightedListBox && !highlightedListBox.IsParentOf(GUI.MouseOn))))
                {
                    //if clicking a selected entity, start moving it
                    foreach (MapEntity e in selectedList)
                    {
                        if (e.IsMouseOn(position))
                        {
                            startMovingPos = position;
                        }
                    }
                    selectionPos = position;

                    //stop camera movement to prevent accidental dragging or rect selection
                    Screen.Selected.Cam.StopMovement();
                }
            }
        }
        public GUIMessageBox(string headerText, string text, string[] buttons, Vector2?relativeSize = null, Point?minSize = null, Alignment textAlignment = Alignment.TopLeft, Type type = Type.Default, string tag = "", Sprite icon = null, string iconStyle = "", Sprite backgroundIcon = null)
            : base(new RectTransform(GUI.Canvas.RelativeSize, GUI.Canvas, Anchor.Center), style: GUI.Style.GetComponentStyle("GUIMessageBox." + type) != null ? "GUIMessageBox." + type : "GUIMessageBox")
        {
            int width = (int)(DefaultWidth * (type == Type.Default ? 1.0f : 1.5f)), height = 0;

            if (relativeSize.HasValue)
            {
                width  = (int)(GameMain.GraphicsWidth * relativeSize.Value.X);
                height = (int)(GameMain.GraphicsHeight * relativeSize.Value.Y);
            }
            if (minSize.HasValue)
            {
                width = Math.Max(width, minSize.Value.X);
                if (height > 0)
                {
                    height = Math.Max(height, minSize.Value.Y);
                }
            }

            if (backgroundIcon != null)
            {
                BackgroundIcon = new GUIImage(new RectTransform(backgroundIcon.size.ToPoint(), RectTransform), backgroundIcon)
                {
                    IgnoreLayoutGroups = true,
                    Color = Color.Transparent
                };
            }

            Anchor anchor = type switch
            {
                Type.InGame => Anchor.TopCenter,
                Type.Vote => Anchor.TopRight,
                _ => Anchor.Center
            };

            InnerFrame = new GUIFrame(new RectTransform(new Point(width, height), RectTransform, anchor)
            {
                IsFixedSize = false
            }, style: null);
            if (type == Type.Vote)
            {
                int offset = GUI.IntScale(64);
                InnerFrame.RectTransform.ScreenSpaceOffset = new Point(-offset, offset);
                CanBeFocused = false;
            }
            GUI.Style.Apply(InnerFrame, "", this);
            this.type = type;
            Tag       = tag;

            if (type == Type.Default || type == Type.Vote)
            {
                Content = new GUILayoutGroup(new RectTransform(new Vector2(0.9f, 0.85f), InnerFrame.RectTransform, Anchor.Center))
                {
                    AbsoluteSpacing = 5
                };

                Header = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), Content.RectTransform),
                                          headerText, font: GUI.SubHeadingFont, textAlignment: Alignment.Center, wrap: true);
                GUI.Style.Apply(Header, "", this);
                Header.RectTransform.MinSize = new Point(0, Header.Rect.Height);

                if (!string.IsNullOrWhiteSpace(text))
                {
                    Text = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), Content.RectTransform), text, textAlignment: textAlignment, wrap: true);
                    GUI.Style.Apply(Text, "", this);
                    Text.RectTransform.NonScaledSize = Text.RectTransform.MinSize = Text.RectTransform.MaxSize =
                        new Point(Text.Rect.Width, Text.Rect.Height);
                    Text.RectTransform.IsFixedSize = true;
                }

                var buttonContainer = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.15f), Content.RectTransform, Anchor.BottomCenter), childAnchor: Anchor.TopCenter)
                {
                    AbsoluteSpacing    = 5,
                    IgnoreLayoutGroups = true
                };

                int buttonSize  = 35;
                var buttonStyle = GUI.Style.GetComponentStyle("GUIButton");
                if (buttonStyle != null && buttonStyle.Height.HasValue)
                {
                    buttonSize = buttonStyle.Height.Value;
                }

                buttonContainer.RectTransform.NonScaledSize = buttonContainer.RectTransform.MinSize = buttonContainer.RectTransform.MaxSize =
                    new Point(buttonContainer.Rect.Width, (int)((buttonSize + 5) * buttons.Length));
                buttonContainer.RectTransform.IsFixedSize = true;

                if (height == 0)
                {
                    height += Header.Rect.Height + Content.AbsoluteSpacing;
                    height += (Text == null ? 0 : Text.Rect.Height) + Content.AbsoluteSpacing;
                    height += buttonContainer.Rect.Height + 20;
                    if (minSize.HasValue)
                    {
                        height = Math.Max(height, minSize.Value.Y);
                    }

                    InnerFrame.RectTransform.NonScaledSize =
                        new Point(InnerFrame.Rect.Width, (int)Math.Max(height / Content.RectTransform.RelativeSize.Y, height + (int)(50 * GUI.yScale)));
                    Content.RectTransform.NonScaledSize =
                        new Point(Content.Rect.Width, height);
                }

                Buttons = new List <GUIButton>(buttons.Length);
                for (int i = 0; i < buttons.Length; i++)
                {
                    var button = new GUIButton(new RectTransform(new Vector2(0.6f, 1.0f / buttons.Length), buttonContainer.RectTransform), buttons[i]);
                    Buttons.Add(button);
                }
            }
            else if (type == Type.InGame)
            {
                InnerFrame.RectTransform.AbsoluteOffset = new Point(0, GameMain.GraphicsHeight);
                alwaysVisible = true;
                CanBeFocused  = false;
                AutoClose     = true;
                GUI.Style.Apply(InnerFrame, "", this);

                var horizontalLayoutGroup = new GUILayoutGroup(new RectTransform(new Vector2(0.98f, 0.95f), InnerFrame.RectTransform, Anchor.Center),
                                                               isHorizontal: true, childAnchor: Anchor.CenterLeft)
                {
                    Stretch         = true,
                    RelativeSpacing = 0.02f
                };
                if (icon != null)
                {
                    Icon = new GUIImage(new RectTransform(new Vector2(0.2f, 0.95f), horizontalLayoutGroup.RectTransform), icon, scaleToFit: true);
                }
                else if (iconStyle != string.Empty)
                {
                    Icon = new GUIImage(new RectTransform(new Vector2(0.2f, 0.95f), horizontalLayoutGroup.RectTransform), iconStyle, scaleToFit: true);
                }

                Content = new GUILayoutGroup(new RectTransform(new Vector2(Icon != null ? 0.65f : 0.85f, 1.0f), horizontalLayoutGroup.RectTransform));

                var buttonContainer = new GUIFrame(new RectTransform(new Vector2(0.15f, 1.0f), horizontalLayoutGroup.RectTransform), style: null);
                Buttons = new List <GUIButton>(1)
                {
                    new GUIButton(new RectTransform(new Vector2(0.3f, 0.5f), buttonContainer.RectTransform, Anchor.Center),
                                  style: "UIToggleButton")
                    {
                        OnClicked = Close
                    }
                };

                InputType?closeInput = null;
                if (GameMain.Config.KeyBind(InputType.Use).MouseButton == MouseButton.None)
                {
                    closeInput = InputType.Use;
                }
                else if (GameMain.Config.KeyBind(InputType.Select).MouseButton == MouseButton.None)
                {
                    closeInput = InputType.Select;
                }
                if (closeInput.HasValue)
                {
                    Buttons[0].ToolTip = TextManager.ParseInputTypes($"{TextManager.Get("Close")} ([InputType.{closeInput.Value}])");
                    Buttons[0].OnAddedToGUIUpdateList += (GUIComponent component) =>
                    {
                        if (!closing && openState >= 1.0f && PlayerInput.KeyHit(closeInput.Value))
                        {
                            GUIButton btn = component as GUIButton;
                            btn?.OnClicked(btn, btn.UserData);
                            btn?.Flash(GUI.Style.Green);
                        }
                    };
                }

                Header = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), Content.RectTransform), headerText, wrap: true);
                GUI.Style.Apply(Header, "", this);
                Header.RectTransform.MinSize = new Point(0, Header.Rect.Height);

                if (!string.IsNullOrWhiteSpace(text))
                {
                    Text = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), Content.RectTransform), text, textAlignment: textAlignment, wrap: true);
                    GUI.Style.Apply(Text, "", this);
                    Content.Recalculate();
                    Text.RectTransform.NonScaledSize = Text.RectTransform.MinSize = Text.RectTransform.MaxSize =
                        new Point(Text.Rect.Width, Text.Rect.Height);
                    Text.RectTransform.IsFixedSize = true;
                    if (string.IsNullOrWhiteSpace(headerText))
                    {
                        Content.ChildAnchor = Anchor.Center;
                    }
                }

                if (height == 0)
                {
                    height += Header.Rect.Height + Content.AbsoluteSpacing;
                    height += (Text == null ? 0 : Text.Rect.Height) + Content.AbsoluteSpacing;
                    if (minSize.HasValue)
                    {
                        height = Math.Max(height, minSize.Value.Y);
                    }

                    InnerFrame.RectTransform.NonScaledSize =
                        new Point(InnerFrame.Rect.Width, (int)Math.Max(height / Content.RectTransform.RelativeSize.Y, height + (int)(50 * GUI.yScale)));
                    Content.RectTransform.NonScaledSize =
                        new Point(Content.Rect.Width, height);
                }
                Buttons[0].RectTransform.MaxSize = new Point((int)(0.4f * Buttons[0].Rect.Y), Buttons[0].Rect.Y);
            }

            MessageBoxes.Add(this);
        }
Exemple #27
0
        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            Timing.Accumulator += gameTime.ElapsedGameTime.TotalSeconds;
            int updateIterations = (int)Math.Floor(Timing.Accumulator / Timing.Step);

            if (Timing.Accumulator > Timing.Step * 6.0)
            {
                //if the game's running too slowly then we have no choice
                //but to skip a bunch of steps
                //otherwise it snowballs and becomes unplayable
                Timing.Accumulator = Timing.Step;
            }

            CrossThread.ProcessTasks();

            PlayerInput.UpdateVariable();

            if (SoundManager != null)
            {
                if (WindowActive || !Config.MuteOnFocusLost)
                {
                    SoundManager.ListenerGain = SoundManager.CompressionDynamicRangeGain;
                }
                else
                {
                    SoundManager.ListenerGain = 0.0f;
                }
            }

            while (Timing.Accumulator >= Timing.Step)
            {
                Timing.TotalTime += Timing.Step;

                Stopwatch sw = new Stopwatch();
                sw.Start();

                fixedTime.IsRunningSlowly = gameTime.IsRunningSlowly;
                TimeSpan addTime = new TimeSpan(0, 0, 0, 0, 16);
                fixedTime.ElapsedGameTime = addTime;
                fixedTime.TotalGameTime.Add(addTime);
                base.Update(fixedTime);

                PlayerInput.Update(Timing.Step);


                if (loadingScreenOpen)
                {
                    //reset accumulator if loading
                    // -> less choppy loading screens because the screen is rendered after each update
                    // -> no pause caused by leftover time in the accumulator when starting a new shift
                    ResetFrameTime();

                    if (!TitleScreen.PlayingSplashScreen)
                    {
                        SoundPlayer.Update((float)Timing.Step);
                    }

                    if (TitleScreen.LoadState >= 100.0f && !TitleScreen.PlayingSplashScreen &&
                        (!waitForKeyHit || ((PlayerInput.GetKeyboardState.GetPressedKeys().Length > 0 || PlayerInput.PrimaryMouseButtonClicked()) && WindowActive)))
                    {
                        loadingScreenOpen = false;
                    }

#if DEBUG
                    if (TitleScreen.LoadState >= 100.0f && !TitleScreen.PlayingSplashScreen && (Config.AutomaticQuickStartEnabled || Config.AutomaticCampaignLoadEnabled) && FirstLoad && !PlayerInput.KeyDown(Keys.LeftShift))
                    {
                        loadingScreenOpen = false;
                        FirstLoad         = false;

                        if (Config.AutomaticQuickStartEnabled)
                        {
                            MainMenuScreen.QuickStart();
                        }
                        else if (Config.AutomaticCampaignLoadEnabled)
                        {
                            IEnumerable <string> saveFiles = SaveUtil.GetSaveFiles(SaveUtil.SaveType.Singleplayer);

                            if (saveFiles.Count() > 0)
                            {
                                saveFiles = saveFiles.OrderBy(file => File.GetLastWriteTime(file));
                                try
                                {
                                    SaveUtil.LoadGame(saveFiles.Last());
                                }
                                catch (Exception e)
                                {
                                    DebugConsole.ThrowError("Loading save \"" + saveFiles.Last() + "\" failed", e);
                                    return;
                                }
                            }
                        }
                    }
#endif

                    if (!hasLoaded && !CoroutineManager.IsCoroutineRunning(loadingCoroutine))
                    {
                        throw new LoadingException(loadingCoroutine.Exception);
                    }
                }
                else if (hasLoaded)
                {
                    if (ConnectLobby != 0)
                    {
                        if (Client != null)
                        {
                            Client.Disconnect();
                            Client = null;

                            GameMain.MainMenuScreen.Select();
                        }
                        Steam.SteamManager.JoinLobby(ConnectLobby, true);

                        ConnectLobby    = 0;
                        ConnectEndpoint = null;
                        ConnectName     = null;
                    }
                    else if (!string.IsNullOrWhiteSpace(ConnectEndpoint))
                    {
                        if (Client != null)
                        {
                            Client.Disconnect();
                            Client = null;

                            GameMain.MainMenuScreen.Select();
                        }
                        UInt64 serverSteamId = SteamManager.SteamIDStringToUInt64(ConnectEndpoint);
                        Client = new GameClient(Config.PlayerName,
                                                serverSteamId != 0 ? null : ConnectEndpoint,
                                                serverSteamId,
                                                string.IsNullOrWhiteSpace(ConnectName) ? ConnectEndpoint : ConnectName);
                        ConnectLobby    = 0;
                        ConnectEndpoint = null;
                        ConnectName     = null;
                    }

                    SoundPlayer.Update((float)Timing.Step);

                    if (PlayerInput.KeyHit(Keys.Escape) && WindowActive)
                    {
                        // Check if a text input is selected.
                        if (GUI.KeyboardDispatcher.Subscriber != null)
                        {
                            if (GUI.KeyboardDispatcher.Subscriber is GUITextBox textBox)
                            {
                                textBox.Deselect();
                            }
                            GUI.KeyboardDispatcher.Subscriber = null;
                        }
                        //if a verification prompt (are you sure you want to x) is open, close it
                        else if (GUIMessageBox.VisibleBox as GUIMessageBox != null &&
                                 GUIMessageBox.VisibleBox.UserData as string == "verificationprompt")
                        {
                            ((GUIMessageBox)GUIMessageBox.VisibleBox).Close();
                        }
                        else if (GUIMessageBox.VisibleBox?.UserData is RoundSummary roundSummary &&
                                 roundSummary.ContinueButton != null &&
                                 roundSummary.ContinueButton.Visible)
                        {
                            GUIMessageBox.MessageBoxes.Remove(GUIMessageBox.VisibleBox);
                        }
                        else if (Tutorial.Initialized && Tutorial.ContentRunning)
                        {
                            (GameSession.GameMode as TutorialMode).Tutorial.CloseActiveContentGUI();
                        }
                        else if (GameSession.IsTabMenuOpen)
                        {
                            gameSession.ToggleTabMenu();
                        }
                        else if (GUI.PauseMenuOpen)
                        {
                            GUI.TogglePauseMenu();
                        }
                        //open the pause menu if not controlling a character OR if the character has no UIs active that can be closed with ESC
                        else if ((Character.Controlled == null || !itemHudActive())
                                 //TODO: do we need to check Inventory.SelectedSlot?
                                 && Inventory.SelectedSlot == null && CharacterHealth.OpenHealthWindow == null &&
                                 !CrewManager.IsCommandInterfaceOpen &&
                                 !(Screen.Selected is SubEditorScreen editor && !editor.WiringMode && Character.Controlled?.SelectedConstruction != null))
                        {
                            // Otherwise toggle pausing, unless another window/interface is open.
                            GUI.TogglePauseMenu();
                        }
Exemple #28
0
        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            Timing.TotalTime    = gameTime.TotalGameTime.TotalSeconds;
            Timing.Accumulator += gameTime.ElapsedGameTime.TotalSeconds;
            int updateIterations = (int)Math.Floor(Timing.Accumulator / Timing.Step);

            if (Timing.Accumulator > Timing.Step * 6.0)
            {
                //if the game's running too slowly then we have no choice
                //but to skip a bunch of steps
                //otherwise it snowballs and becomes unplayable
                Timing.Accumulator = Timing.Step;
            }

            CrossThread.ProcessTasks();

            PlayerInput.UpdateVariable();

            bool paused = true;

            if (SoundManager != null)
            {
                if (WindowActive || !Config.MuteOnFocusLost)
                {
                    SoundManager.ListenerGain = SoundManager.CompressionDynamicRangeGain;
                }
                else
                {
                    SoundManager.ListenerGain = 0.0f;
                }
            }

            while (Timing.Accumulator >= Timing.Step)
            {
                Stopwatch sw = new Stopwatch();
                sw.Start();

                fixedTime.IsRunningSlowly = gameTime.IsRunningSlowly;
                TimeSpan addTime = new TimeSpan(0, 0, 0, 0, 16);
                fixedTime.ElapsedGameTime = addTime;
                fixedTime.TotalGameTime.Add(addTime);
                base.Update(fixedTime);

                PlayerInput.Update(Timing.Step);


                if (loadingScreenOpen)
                {
                    //reset accumulator if loading
                    // -> less choppy loading screens because the screen is rendered after each update
                    // -> no pause caused by leftover time in the accumulator when starting a new shift
                    GameMain.ResetFrameTime();

                    if (!TitleScreen.PlayingSplashScreen)
                    {
                        SoundPlayer.Update((float)Timing.Step);
                    }

                    if (TitleScreen.LoadState >= 100.0f && !TitleScreen.PlayingSplashScreen &&
                        (!waitForKeyHit || ((PlayerInput.GetKeyboardState.GetPressedKeys().Length > 0 || PlayerInput.LeftButtonClicked()) && WindowActive)))
                    {
                        loadingScreenOpen = false;
                    }

                    if (!hasLoaded && !CoroutineManager.IsCoroutineRunning(loadingCoroutine))
                    {
                        string errMsg = "Loading was interrupted due to an error";
                        if (loadingCoroutine.Exception != null)
                        {
                            errMsg += ": " + loadingCoroutine.Exception.Message + "\n" + loadingCoroutine.Exception.StackTrace;
                        }
                        throw new Exception(errMsg);
                    }
                }
                else if (hasLoaded)
                {
                    if (ConnectLobby != 0)
                    {
                        if (Client != null)
                        {
                            Client.Disconnect();
                            Client = null;

                            GameMain.MainMenuScreen.Select();
                        }
                        Steam.SteamManager.JoinLobby(ConnectLobby, true);

                        ConnectLobby    = 0;
                        ConnectEndpoint = null;
                        ConnectName     = null;
                    }
                    else if (!string.IsNullOrWhiteSpace(ConnectEndpoint))
                    {
                        if (Client != null)
                        {
                            Client.Disconnect();
                            Client = null;

                            GameMain.MainMenuScreen.Select();
                        }
                        UInt64 serverSteamId = SteamManager.SteamIDStringToUInt64(ConnectEndpoint);
                        Client = new GameClient(SteamManager.GetUsername(),
                                                serverSteamId != 0 ? null : ConnectEndpoint,
                                                serverSteamId,
                                                string.IsNullOrWhiteSpace(ConnectName) ? ConnectEndpoint : ConnectName);
                        ConnectLobby    = 0;
                        ConnectEndpoint = null;
                        ConnectName     = null;
                    }

                    SoundPlayer.Update((float)Timing.Step);

                    if (PlayerInput.KeyHit(Keys.Escape) && WindowActive)
                    {
                        // Check if a text input is selected.
                        if (GUI.KeyboardDispatcher.Subscriber != null)
                        {
                            if (GUI.KeyboardDispatcher.Subscriber is GUITextBox textBox)
                            {
                                textBox.Deselect();
                            }
                            GUI.KeyboardDispatcher.Subscriber = null;
                        }
                        //if a verification prompt (are you sure you want to x) is open, close it
                        else if (GUIMessageBox.VisibleBox as GUIMessageBox != null &&
                                 GUIMessageBox.VisibleBox.UserData as string == "verificationprompt")
                        {
                            ((GUIMessageBox)GUIMessageBox.VisibleBox).Close();
                        }
                        else if (Tutorial.Initialized && Tutorial.ContentRunning)
                        {
                            (GameSession.GameMode as TutorialMode).Tutorial.CloseActiveContentGUI();
                        }
                        else if (GUI.PauseMenuOpen)
                        {
                            GUI.TogglePauseMenu();
                        }
                        else if ((Character.Controlled?.SelectedConstruction == null || !Character.Controlled.SelectedConstruction.ActiveHUDs.Any(ic => ic.GuiFrame != null)) &&
                                 Inventory.SelectedSlot == null && CharacterHealth.OpenHealthWindow == null)
                        {
                            // Otherwise toggle pausing, unless another window/interface is open.
                            GUI.TogglePauseMenu();
                        }
                    }

                    GUI.ClearUpdateList();
                    paused = (DebugConsole.IsOpen || GUI.PauseMenuOpen || GUI.SettingsMenuOpen || Tutorial.ContentRunning) &&
                             (NetworkMember == null || !NetworkMember.GameStarted);

#if !DEBUG
                    if (NetworkMember == null && !WindowActive && !paused && true && Screen.Selected != MainMenuScreen && Config.PauseOnFocusLost)
                    {
                        GUI.TogglePauseMenu();
                        paused = true;
                    }
#endif

                    Screen.Selected.AddToGUIUpdateList();

                    if (Client != null)
                    {
                        Client.AddToGUIUpdateList();
                    }

                    DebugConsole.AddToGUIUpdateList();

                    DebugConsole.Update(this, (float)Timing.Step);
                    paused = paused || (DebugConsole.IsOpen && (NetworkMember == null || !NetworkMember.GameStarted));

                    if (!paused)
                    {
                        Screen.Selected.Update(Timing.Step);
                    }
                    else if (Tutorial.Initialized && Tutorial.ContentRunning)
                    {
                        (GameSession.GameMode as TutorialMode).Update((float)Timing.Step);
                    }

                    if (NetworkMember != null)
                    {
                        NetworkMember.Update((float)Timing.Step);
                    }

                    GUI.Update((float)Timing.Step);
                }

                CoroutineManager.Update((float)Timing.Step, paused ? 0.0f : (float)Timing.Step);

                SteamManager.Update((float)Timing.Step);

                SoundManager?.Update();

                Timing.Accumulator -= Timing.Step;

                sw.Stop();
                PerformanceCounter.AddElapsedTicks("Update total", sw.ElapsedTicks);
                PerformanceCounter.UpdateTimeGraph.Update(sw.ElapsedTicks / (float)TimeSpan.TicksPerMillisecond);
                PerformanceCounter.UpdateIterationsGraph.Update(updateIterations);
            }

            if (!paused)
            {
                Timing.Alpha = Timing.Accumulator / Timing.Step;
            }
        }
        protected override void Update(float deltaTime)
        {
            if (!Visible)
            {
                return;
            }

            if (flashTimer > 0.0f)
            {
                flashTimer -= deltaTime;
            }
            if (!Enabled)
            {
                return;
            }

            if (skipUpdate)
            {
                skipUpdate = false;
                return;
            }

            if (MouseRect.Contains(PlayerInput.MousePosition) && (GUI.MouseOn == null || (!(GUI.MouseOn is GUIButton) && GUI.IsMouseOn(this))))
            {
                State = ComponentState.Hover;
                if (PlayerInput.PrimaryMouseButtonDown())
                {
                    mouseHeldInside = true;
                    Select();
                }
                else
                {
                    isSelecting = PlayerInput.PrimaryMouseButtonHeld();
                }
                if (PlayerInput.DoubleClicked())
                {
                    SelectAll();
                }
                if (isSelecting)
                {
                    if (!MathUtils.NearlyEqual(PlayerInput.MouseSpeed.X, 0))
                    {
                        CaretIndex = textBlock.GetCaretIndexFromScreenPos(PlayerInput.MousePosition);
                        CalculateCaretPos();
                        CalculateSelection();
                    }
                }
            }
            else
            {
                if ((PlayerInput.LeftButtonClicked() || PlayerInput.RightButtonClicked()) && selected)
                {
                    if (!mouseHeldInside)
                    {
                        Deselect();
                    }
                    mouseHeldInside = false;
                }
                isSelecting = false;
                State       = ComponentState.None;
            }
            if (!isSelecting)
            {
                isSelecting = PlayerInput.KeyDown(Keys.LeftShift) || PlayerInput.KeyDown(Keys.RightShift);
            }

            if (CaretEnabled)
            {
                if (textBlock.OverflowClipActive)
                {
                    if (CaretScreenPos.X < textBlock.Rect.X + textBlock.Padding.X)
                    {
                        textBlock.TextPos = new Vector2(textBlock.TextPos.X + ((textBlock.Rect.X + textBlock.Padding.X) - CaretScreenPos.X), textBlock.TextPos.Y);
                        CalculateCaretPos();
                    }
                    else if (CaretScreenPos.X > textBlock.Rect.Right - textBlock.Padding.Z)
                    {
                        textBlock.TextPos = new Vector2(textBlock.TextPos.X - (CaretScreenPos.X - (textBlock.Rect.Right - textBlock.Padding.Z)), textBlock.TextPos.Y);
                        CalculateCaretPos();
                    }
                }
                caretTimer  += deltaTime;
                caretVisible = ((caretTimer * 1000.0f) % 1000) < 500;
                if (caretVisible && caretPosDirty)
                {
                    CalculateCaretPos();
                }
            }

            if (GUI.KeyboardDispatcher.Subscriber == this)
            {
                State = ComponentState.Selected;
                Character.DisableControls = true;
                if (OnEnterPressed != null && PlayerInput.KeyHit(Keys.Enter))
                {
                    OnEnterPressed(this, Text);
                }
            }
            else if (Selected)
            {
                Deselect();
            }

            textBlock.State = State;
        }
        //MouseState previousMouse;
        public override void Update(float deltaTime)
        {
            if (!Visible)
            {
                return;
            }

            if (flashTimer > 0.0f)
            {
                flashTimer -= deltaTime;
            }
            if (!Enabled)
            {
                return;
            }

            if (rect.Contains(PlayerInput.MousePosition) && Enabled &&
                (MouseOn == null || MouseOn == this || IsParentOf(MouseOn) || MouseOn.IsParentOf(this)))
            {
                state = ComponentState.Hover;
                if (PlayerInput.LeftButtonClicked())
                {
                    Select();
                    OnSelected?.Invoke(this, Keys.None);
                }
            }
            else
            {
                state = ComponentState.None;
            }

            if (CaretEnabled)
            {
                caretTimer  += deltaTime;
                caretVisible = ((caretTimer * 1000.0f) % 1000) < 500;
            }

            if (keyboardDispatcher.Subscriber == this)
            {
                state = ComponentState.Selected;
                Character.DisableControls = true;
                if (OnEnterPressed != null && PlayerInput.KeyHit(Keys.Enter))
                {
                    string input = Text;
                    Text = "";
                    OnEnterPressed(this, input);
                }
#if LINUX
                else if (PlayerInput.KeyHit(Keys.Back) && Text.Length > 0)
                {
                    Text = Text.Substring(0, Text.Length - 1);
                }
#endif
            }
            else if (Selected)
            {
                Deselect();
            }

            textBlock.State = state;
            textBlock.Update(deltaTime);
        }