Exemplo n.º 1
0
        public void RequestJump(string destinationName, Vector3D destination, long userId)
        {
            if (!Vector3.IsZero(MyGravityProviderSystem.CalculateNaturalGravityInPoint(m_grid.WorldMatrix.Translation)))
            {
                var notification = new MyHudNotification(MySpaceTexts.NotificationCannotJumpFromGravity, 1500);
                MyHud.Notifications.Add(notification);
                return;
            }
            if (!Vector3.IsZero(MyGravityProviderSystem.CalculateNaturalGravityInPoint(destination)))
            {
                var notification = new MyHudNotification(MySpaceTexts.NotificationCannotJumpIntoGravity, 1500);
                MyHud.Notifications.Add(notification);
                return;
            }

            if (!IsJumpValid(userId))
            {
                return;
            }

            if (MySession.Static.Settings.WorldSizeKm > 0 && destination.Length() > MySession.Static.Settings.WorldSizeKm * 500)
            {
                var notification = new MyHudNotification(MySpaceTexts.NotificationCannotJumpOutsideWorld, 1500);
                MyHud.Notifications.Add(notification);
                return;
            }

            m_selectedDestination = destination;
            double maxJumpDistance = GetMaxJumpDistance(userId);

            m_jumpDirection = destination - m_grid.WorldMatrix.Translation;
            double jumpDistance   = m_jumpDirection.Length();
            double actualDistance = jumpDistance;

            if (jumpDistance > maxJumpDistance)
            {
                double ratio = maxJumpDistance / jumpDistance;
                actualDistance   = maxJumpDistance;
                m_jumpDirection *= ratio;
            }

            //By Gregory: Check for obstacle not that fast but happens rarely(on Jump drive enable)
            //TODO: make compatible with GetMaxJumpDistance and refactor to much code checks for actual jump
            var direction = Vector3D.Normalize(destination - m_grid.WorldMatrix.Translation);
            var startPos  = m_grid.WorldMatrix.Translation + m_grid.PositionComp.LocalAABB.Extents.Max() * direction;
            var line      = new LineD(startPos, destination);


            var intersection = MyEntities.GetIntersectionWithLine(ref line, m_grid, null, ignoreObjectsWithoutPhysics: false);

            Vector3D newDestination = Vector3D.Zero;
            Vector3D newDirection   = Vector3D.Zero;

            if (intersection.HasValue)
            {
                MyEntity MyEntity = intersection.Value.Entity as MyEntity;

                var targetPos     = MyEntity.WorldMatrix.Translation;
                var obstaclePoint = MyUtils.GetClosestPointOnLine(ref startPos, ref destination, ref targetPos);

                MyPlanet MyEntityPlanet = intersection.Value.Entity as MyPlanet;
                if (MyEntityPlanet != null)
                {
                    var notification = new MyHudNotification(MySpaceTexts.NotificationCannotJumpIntoGravity, 1500);
                    MyHud.Notifications.Add(notification);
                    return;
                }

                //var Radius = MyEntityPlanet != null ? MyEntityPlanet.MaximumRadius : MyEntity.PositionComp.LocalAABB.Extents.Length();
                var Radius = MyEntity.PositionComp.LocalAABB.Extents.Length();

                destination           = obstaclePoint - direction * (Radius + m_grid.PositionComp.LocalAABB.HalfExtents.Length());
                m_selectedDestination = destination;
                m_jumpDirection       = m_selectedDestination - startPos;
                actualDistance        = m_jumpDirection.Length();
            }

            if (actualDistance < MIN_JUMP_DISTANCE)
            {
                MyGuiSandbox.AddScreen(MyGuiSandbox.CreateMessageBox(
                                           buttonType: MyMessageBoxButtonsType.OK,
                                           messageText: GetWarningText(actualDistance, intersection.HasValue),
                                           messageCaption: MyTexts.Get(MyCommonTexts.MessageBoxCaptionWarning)
                                           ));
            }
            else
            {
                MyGuiSandbox.AddScreen(MyGuiSandbox.CreateMessageBox(
                                           buttonType : MyMessageBoxButtonsType.YES_NO,
                                           messageText : GetConfimationText(destinationName, jumpDistance, actualDistance, userId, intersection.HasValue),
                                           messageCaption : MyTexts.Get(MyCommonTexts.MessageBoxCaptionPleaseConfirm),
                                           size : new Vector2(0.839375f, 0.3675f), callback : delegate(MyGuiScreenMessageBox.ResultEnum result)
                {
                    if (result == MyGuiScreenMessageBox.ResultEnum.YES && IsJumpValid(userId))
                    {
                        RequestJump(m_selectedDestination, userId);
                    }
                    else
                    {
                        AbortJump();
                    }
                }
                                           ));
            }
        }
Exemplo n.º 2
0
 public override void Activate()
 {
     MyScreenManager.CloseScreen(typeof(MyGuiScreenControlMenu));
     MyGuiSandbox.AddScreen(new Sandbox.Game.Screens.MyGuiScreenBriefing());
 }
 private void OnModsClick(object sender)
 {
     MyGuiSandbox.AddScreen(new MyGuiScreenMods(m_mods));
 }
Exemplo n.º 4
0
        public override void UpdateBeforeSimulation()
        {
            base.UpdateBeforeSimulation();

            if (!MySession.Static.IsScenario)
            {
                return;
            }

            if (!Sync.IsServer)
            {
                return;
            }

            if (MySession.Static.OnlineMode == MyOnlineModeEnum.OFFLINE)//!Sync.MultiplayerActive)
            {
                if (m_gameState == MyState.Loaded)
                {
                    m_gameState         = MyState.Running;
                    ServerStartGameTime = DateTime.UtcNow;
                }
                return;
            }

            switch (m_gameState)
            {
            case MyState.Loaded:
                if (MySession.Static.OnlineMode != MyOnlineModeEnum.OFFLINE && MyMultiplayer.Static == null)
                {
                    m_bootUpCount++;
                    if (m_bootUpCount > 100)    //because MyMultiplayer.Static is initialized later than this part of game
                    {
                        //network start failure - trying to save what we can :-)
                        MyPlayerCollection.RequestLocalRespawn();
                        m_gameState = MyState.Running;
                        return;
                    }
                }
                if (MySandboxGame.IsDedicated)
                {
                    ServerPreparationStartTime             = DateTime.UtcNow;
                    MyMultiplayer.Static.ScenarioStartTime = ServerPreparationStartTime;
                    m_gameState = MyState.Running;
                    return;
                }
                if (MySession.Static.OnlineMode == MyOnlineModeEnum.OFFLINE || MyMultiplayer.Static != null)
                {
                    if (MyMultiplayer.Static != null)
                    {
                        MyMultiplayer.Static.Scenario         = true;
                        MyMultiplayer.Static.ScenarioBriefing = MySession.Static.GetWorld().Checkpoint.Briefing;
                    }
                    MyGuiScreenScenarioMpServer guiscreen = new MyGuiScreenScenarioMpServer();
                    guiscreen.Briefing = MySession.Static.GetWorld().Checkpoint.Briefing;
                    MyGuiSandbox.AddScreen(guiscreen);
                    m_playersReadyForBattle.Add(MySteam.UserId);
                    m_gameState = MyState.JoinScreen;
                }
                break;

            case MyState.JoinScreen:
                break;

            case MyState.WaitingForClients:
                // Check timeout
                TimeSpan currenTime = MySession.Static.ElapsedPlayTime;
                if (AllPlayersReadyForBattle() || (LoadTimeout > 0 && currenTime - m_startBattlePreparationOnClients > TimeSpan.FromSeconds(LoadTimeout)))
                {
                    StartScenario();
                    foreach (var playerId in m_playersReadyForBattle)
                    {
                        if (playerId != MySteam.UserId)
                        {
                            MySyncScenario.StartScenarioRequest(playerId, ServerStartGameTime.Ticks);
                        }
                    }
                }
                break;

            case MyState.Running:
                break;
            }
        }
Exemplo n.º 5
0
        void OnUserJoined(ref JoinResultMsg msg, ulong sender)
        {
            if (msg.JoinResult == JoinResult.OK)
            {
                if (OnJoin != null)
                {
                    OnJoin();
                    OnJoin         = null;
                    m_clientJoined = true;
                }
            }
            else if (msg.JoinResult == JoinResult.NotInGroup)
            {
                MyGuiScreenMainMenu.UnloadAndExitToMenu();
                Dispose();

                ulong  groupId   = Server.GetGameTagByPrefixUlong("groupId");
                string groupName = MySteam.API.Friends.GetClanName(groupId);

                var messageBox = MyGuiSandbox.CreateMessageBox(
                    messageCaption: MyTexts.Get(MyCommonTexts.MessageBoxCaptionError),
                    messageText: new StringBuilder(string.Format(
                                                       MyTexts.GetString(MyCommonTexts.MultiplayerErrorNotInGroup), groupName)),
                    buttonType: MyMessageBoxButtonsType.YES_NO);
                messageBox.ResultCallback = delegate(MyGuiScreenMessageBox.ResultEnum result)
                {
                    if (result == MyGuiScreenMessageBox.ResultEnum.YES)
                    {
                        MySteam.API.OpenOverlayUser(groupId);
                    }
                    ;
                };
                MyGuiSandbox.AddScreen(messageBox);
            }
            else if (msg.JoinResult == JoinResult.BannedByAdmins)
            {
                MyGuiScreenMainMenu.UnloadAndExitToMenu();
                Dispose();

                ulong admin = msg.Admin;

                if (admin != 0)
                {
                    var messageBox = MyGuiSandbox.CreateMessageBox(
                        messageCaption: MyTexts.Get(MyCommonTexts.MessageBoxCaptionError),
                        messageText: MyTexts.Get(MyCommonTexts.MultiplayerErrorBannedByAdminsWithDialog),
                        buttonType: MyMessageBoxButtonsType.YES_NO);
                    messageBox.ResultCallback = delegate(MyGuiScreenMessageBox.ResultEnum result)
                    {
                        if (result == MyGuiScreenMessageBox.ResultEnum.YES)
                        {
                            MySteam.API.OpenOverlayUser(admin);
                        }
                        ;
                    };
                    MyGuiSandbox.AddScreen(messageBox);
                }
                else
                {
                    MyGuiSandbox.AddScreen(MyGuiSandbox.CreateMessageBox(
                                               messageCaption: MyTexts.Get(MyCommonTexts.MessageBoxCaptionError),
                                               messageText: MyTexts.Get(MyCommonTexts.MultiplayerErrorBannedByAdmins)));
                }
            }
            else
            {
                MyStringId resultText = MyCommonTexts.MultiplayerErrorConnectionFailed;

                switch (msg.JoinResult)
                {
                case JoinResult.AlreadyJoined:
                    resultText = MyCommonTexts.MultiplayerErrorAlreadyJoined;
                    break;

                case JoinResult.ServerFull:
                    resultText = MyCommonTexts.MultiplayerErrorServerFull;
                    break;

                case JoinResult.SteamServersOffline:
                    resultText = MyCommonTexts.MultiplayerErrorSteamServersOffline;
                    break;

                case JoinResult.TicketInvalid:
                    resultText = MyCommonTexts.MultiplayerErrorTicketInvalid;
                    break;

                case JoinResult.GroupIdInvalid:
                    resultText = MyCommonTexts.MultiplayerErrorGroupIdInvalid;
                    break;

                case JoinResult.TicketCanceled:
                    resultText = MyCommonTexts.MultiplayerErrorTicketCanceled;
                    break;

                case JoinResult.TicketAlreadyUsed:
                    resultText = MyCommonTexts.MultiplayerErrorTicketAlreadyUsed;
                    break;

                case JoinResult.LoggedInElseWhere:
                    resultText = MyCommonTexts.MultiplayerErrorLoggedInElseWhere;
                    break;

                case JoinResult.NoLicenseOrExpired:
                    resultText = MyCommonTexts.MultiplayerErrorNoLicenseOrExpired;
                    break;

                case JoinResult.UserNotConnected:
                    resultText = MyCommonTexts.MultiplayerErrorUserNotConnected;
                    break;

                case JoinResult.VACBanned:
                    resultText = MyCommonTexts.MultiplayerErrorVACBanned;
                    break;

                case JoinResult.VACCheckTimedOut:
                    resultText = MyCommonTexts.MultiplayerErrorVACCheckTimedOut;
                    break;

                default:
                    System.Diagnostics.Debug.Fail("Unknown JoinResult");
                    break;
                }

                Dispose();
                MyGuiScreenMainMenu.UnloadAndExitToMenu();
                MyGuiSandbox.AddScreen(MyGuiSandbox.CreateMessageBox(
                                           messageCaption: MyTexts.Get(MyCommonTexts.MessageBoxCaptionError),
                                           messageText: MyTexts.Get(resultText)));
                return;
            }
        }
Exemplo n.º 6
0
        //loads next mission, SP only
        //id can be workshop ID or save name (in that case official scenarios are searched first, if not found, then user's saves)
        public static void LoadNextScenario(string id)
        {
            if (MySession.Static.OnlineMode != MyOnlineModeEnum.OFFLINE)
            {
                return;
            }
            MyAPIGateway.Utilities.ShowNotification(MyTexts.GetString(MySpaceTexts.NotificationNextScenarioWillLoad), 10000);
            ulong workshopID;

            if (ulong.TryParse(id, out workshopID))
            {
                //scenario from steam, without the user needing to subscribe it first:
                if (!MySteam.IsOnline)
                {
                    MyGuiSandbox.AddScreen(MyGuiSandbox.CreateMessageBox(
                                               messageText: MyTexts.Get(MySpaceTexts.MessageBoxTextWorkshopDownloadFailed),
                                               messageCaption: MyTexts.Get(MyCommonTexts.ScreenCaptionWorkshop)));
                }
                else
                {
                    MySandboxGame.Log.WriteLine(string.Format("Querying details of file " + workshopID));

                    Action <bool, RemoteStorageGetPublishedFileDetailsResult> onGetDetailsCallResult = delegate(bool ioFailure, RemoteStorageGetPublishedFileDetailsResult data)
                    {
                        MySandboxGame.Log.WriteLine(string.Format("Obtained details: Id={4}; Result={0}; ugcHandle={1}; title='{2}'; tags='{3}'", data.Result, data.FileHandle, data.Title, data.Tags, data.PublishedFileId));
                        if (!ioFailure && data.Result == Result.OK && data.Tags.Length != 0)
                        {
#if !XB1 // XB1_NOWORKSHOP
                            m_newWorkshopMap.Title           = data.Title;
                            m_newWorkshopMap.PublishedFileId = data.PublishedFileId;
                            m_newWorkshopMap.Description     = data.Description;
                            m_newWorkshopMap.UGCHandle       = data.FileHandle;
                            m_newWorkshopMap.SteamIDOwner    = data.SteamIDOwner;
                            m_newWorkshopMap.TimeUpdated     = data.TimeUpdated;
                            m_newWorkshopMap.Tags            = data.Tags.Split(',');
                            Static.EndAction += EndActionLoadWorkshop;
#else // XB1
                            System.Diagnostics.Debug.Assert(false); // TODO?
#endif // XB1
                        }
                        else
                        {
                            MyGuiSandbox.AddScreen(MyGuiSandbox.CreateMessageBox(
                                                       messageText: MyTexts.Get(MySpaceTexts.MessageBoxTextWorkshopDownloadFailed),
                                                       messageCaption: MyTexts.Get(MyCommonTexts.ScreenCaptionWorkshop)));
                        }
                    };
                    MySteam.API.RemoteStorage.GetPublishedFileDetails(workshopID, 0, onGetDetailsCallResult);
                }
            }
            else
            {
                var contentDir = Path.Combine(MyFileSystem.ContentPath, "Missions", id);
                if (Directory.Exists(contentDir))
                {
                    m_newPath         = contentDir;
                    Static.EndAction += EndActionLoadLocal;
                    return;
                }
                var saveDir = Path.Combine(MyFileSystem.SavesPath, id);
                if (Directory.Exists(saveDir))
                {
                    m_newPath         = saveDir;
                    Static.EndAction += EndActionLoadLocal;
                    return;
                }
                //fail msg:
                StringBuilder error = new StringBuilder();
                error.AppendFormat(MyTexts.GetString(MySpaceTexts.MessageBoxTextScenarioNotFound), contentDir, saveDir);
                MyGuiScreenMessageBox mb = MyGuiSandbox.CreateMessageBox(messageText: error, messageCaption: MyTexts.Get(MyCommonTexts.MessageBoxCaptionError));
                MyGuiSandbox.AddScreen(mb);
            }
        }
 //GUI
 public override void DisplayGUI()
 {
     MyGuiSandbox.AddScreen(new MyGuiScreenTriggerPositionReached(this));
 }
Exemplo n.º 8
0
 public void OnScenarioGameClick(MyGuiControlButton sender)
 {
     MyGuiSandbox.AddScreen(MyGuiSandbox.CreateScreen(MyPerGameSettings.GUI.ScenarioScreen));
 }
Exemplo n.º 9
0
 public void OnTutorialClick(MyGuiControlButton sender)
 {
     MyAnalyticsHelper.ReportTutorialScreen("TutorialsButtonClicked");
     MyGuiSandbox.AddScreen(MyGuiSandbox.CreateScreen(MyPerGameSettings.GUI.TutorialScreen));
 }
        public bool CreateSpawnMenu(float usableWidth, MyGuiControlParentTableLayout parentTable, MyPluginAdminMenu adminScreen)
        {
            m_parentScreen            = adminScreen;
            m_offset                  = Vector3D.Zero;
            m_currentSelectedAsteroid = null;

            if (m_fetchedStarSytem == null)
            {
                MyGuiControlRotatingWheel m_loadingWheel = new MyGuiControlRotatingWheel(position: Vector2.Zero);
                m_loadingWheel.OriginAlign = MyGuiDrawAlignEnum.HORISONTAL_CENTER_AND_VERTICAL_CENTER;

                adminScreen.Controls.Add(m_loadingWheel);

                MyStarSystemGenerator.Static.GetStarSystem(delegate(MyObjectBuilder_SystemData starSystem)
                {
                    m_fetchedStarSytem         = starSystem;
                    adminScreen.ShouldRecreate = true;
                });
                return(true);
            }

            MyGuiControlLabel label = new MyGuiControlLabel(null, null, "Parent objects");

            parentTable.AddTableRow(label);

            m_parentObjectListBox = new MyGuiControlListbox();
            m_parentObjectListBox.Add(new MyGuiControlListbox.Item(new System.Text.StringBuilder("System center"), userData: m_fetchedStarSytem.CenterObject));
            m_parentObjectListBox.VisibleRowsCount = 8;
            m_parentObjectListBox.Size             = new Vector2(usableWidth, m_parentObjectListBox.Size.Y);
            m_parentObjectListBox.SelectAllVisible();
            m_parentObjectListBox.ItemsSelected += OnParentItemClicked;

            foreach (var obj in m_fetchedStarSytem.CenterObject.GetAllChildren())
            {
                if (obj.Type == MySystemObjectType.PLANET || obj.Type == MySystemObjectType.MOON)
                {
                    m_parentObjectListBox.Add(new MyGuiControlListbox.Item(new System.Text.StringBuilder(obj.DisplayName), userData: obj));
                }
            }

            parentTable.AddTableRow(m_parentObjectListBox);

            var row = new MyGuiControlParentTableLayout(2, false, Vector2.Zero);

            m_snapToParentCheck                   = new MyGuiControlCheckbox();
            m_snapToParentCheck.IsChecked         = m_snapToParent;
            m_snapToParentCheck.IsCheckedChanged += delegate
            {
                m_snapToParent         = m_snapToParentCheck.IsChecked;
                m_zoomInButton.Enabled = m_snapToParent;
            };

            row.AddTableRow(m_snapToParentCheck, new MyGuiControlLabel(null, null, "Snap camera to parent"));

            row.ApplyRows();

            parentTable.AddTableRow(row);

            parentTable.AddTableSeparator();

            GenerateRingSettingElements(usableWidth, parentTable);

            m_nameBox      = new MyGuiControlTextbox();
            m_nameBox.Size = new Vector2(usableWidth, m_nameBox.Size.Y);

            parentTable.AddTableRow(new MyGuiControlLabel(null, null, "Name"));
            parentTable.AddTableRow(m_nameBox);

            m_zoomInButton = MyPluginGuiHelper.CreateDebugButton(usableWidth, "Zoom to ring", delegate
            {
                if (m_snapToParent)
                {
                    m_parentScreen.CameraLookAt(GenerateAsteroidRing().CenterPosition, new Vector3D(0, 0, (m_radiusSlider.Value + m_widthSlider.Value) * 2000));
                }
            });

            parentTable.AddTableRow(m_zoomInButton);

            m_offsetToCoordButton = MyPluginGuiHelper.CreateDebugButton(usableWidth, "Offset to coordinate", delegate
            {
                var coordMessage          = new MyGuiScreenDialogCoordinate("Enter coordinate to offset the center of the ring from its parent");
                coordMessage.OnConfirmed += delegate(Vector3D coord)
                {
                    m_offset = coord;
                    UpdateRingVisual(GenerateAsteroidRing());
                };
                MyGuiSandbox.AddScreen(coordMessage);
            });

            parentTable.AddTableRow(m_offsetToCoordButton);

            m_spawnRingButton = MyPluginGuiHelper.CreateDebugButton(usableWidth, "Add ring", delegate
            {
                StringBuilder name = new StringBuilder();
                m_nameBox.GetText(name);
                if (name.Length < 4)
                {
                    MyPluginGuiHelper.DisplayError("Name must be at least 4 letters long", "Error");
                    return;
                }

                MySystemAsteroids instance;
                MyAsteroidRingData ring;
                GenerateAsteroidData(out ring, out instance);

                if (ring == null || instance == null)
                {
                    MyPluginGuiHelper.DisplayError("Could not generate asteroid ring. No data found.", "Error");
                    return;
                }

                MyAsteroidRingProvider.Static.AddInstance(instance, ring, delegate(bool success)
                {
                    if (!success)
                    {
                        MyPluginGuiHelper.DisplayError("Ring could not be added, because an object with the same id already exists. This error should not occour, so please try again.", "Error");
                    }
                    else
                    {
                        MyPluginGuiHelper.DisplayMessage("Ring was created successfully.", "Success");
                        m_parentScreen.ForceFetchStarSystem = true;
                        m_parentScreen.ShouldRecreate       = true;
                    }
                });
            });

            parentTable.AddTableRow(m_spawnRingButton);

            return(true);
        }
Exemplo n.º 11
0
 public void OnCustomGameClick(MyGuiControlButton sender)
 {
     MyGuiSandbox.AddScreen(MyGuiSandbox.CreateScreen(MyPerGameSettings.GUI.CustomWorldScreen));
 }
Exemplo n.º 12
0
        protected void CreateTerminalControls()
        {
            if (MyTerminalControlFactory.AreControlsCreated <MySensorBlock>())
            {
                return;
            }
            base.CreateTerminalControls();
            m_openedToolbars = new List <MyToolbar>();

            var toolbarButton = new MyTerminalControlButton <MySensorBlock>("Open Toolbar", MySpaceTexts.BlockPropertyTitle_SensorToolbarOpen, MySpaceTexts.BlockPropertyDescription_SensorToolbarOpen,
                                                                            delegate(MySensorBlock self)
            {
                m_openedToolbars.Add(self.Toolbar);
                if (MyGuiScreenCubeBuilder.Static == null)
                {
                    m_shouldSetOtherToolbars          = true;
                    MyToolbarComponent.CurrentToolbar = self.Toolbar;
                    MyGuiScreenBase screen            = MyGuiSandbox.CreateScreen(MyPerGameSettings.GUI.ToolbarConfigScreen, 0, self);
                    MyToolbarComponent.AutoUpdate     = false;
                    screen.Closed += (source) =>
                    {
                        MyToolbarComponent.AutoUpdate = true;
                        m_openedToolbars.Clear();
                    };
                    MyGuiSandbox.AddScreen(screen);
                }
            });

            MyTerminalControlFactory.AddControl(toolbarButton);

            var fieldWidthMin = new MyTerminalControlSlider <MySensorBlock>("Left", MySpaceTexts.BlockPropertyTitle_SensorFieldWidthMin, MySpaceTexts.BlockPropertyDescription_SensorFieldLeft);

            fieldWidthMin.SetLimits(block => 1, block => block.MaxRange);
            fieldWidthMin.DefaultValue = 5;
            fieldWidthMin.Getter       = (x) => - x.m_fieldMin.Value.X;
            fieldWidthMin.Setter       = (x, v) =>
            {
                var fieldMin = x.FieldMin;
                if (fieldMin.X == -v)
                {
                    return;
                }
                fieldMin.X = -v;
                x.FieldMin = fieldMin;
            };
            fieldWidthMin.Writer = (x, result) => result.AppendInt32((int)-x.m_fieldMin.Value.X).Append(" m");
            fieldWidthMin.EnableActions();
            MyTerminalControlFactory.AddControl(fieldWidthMin);

            var fieldWidthMax = new MyTerminalControlSlider <MySensorBlock>("Right", MySpaceTexts.BlockPropertyTitle_SensorFieldWidthMax, MySpaceTexts.BlockPropertyDescription_SensorFieldRight);

            fieldWidthMax.SetLimits(block => 1, block => block.MaxRange);
            fieldWidthMax.DefaultValue = 5;
            fieldWidthMax.Getter       = (x) => x.m_fieldMax.Value.X;
            fieldWidthMax.Setter       = (x, v) =>
            {
                var fieldMax = x.FieldMax;
                if (fieldMax.X == v)
                {
                    return;
                }
                fieldMax.X = v;
                x.FieldMax = fieldMax;
            };
            fieldWidthMax.Writer = (x, result) => result.AppendInt32((int)x.m_fieldMax.Value.X).Append(" m");
            fieldWidthMax.EnableActions();
            MyTerminalControlFactory.AddControl(fieldWidthMax);


            var fieldHeightMin = new MyTerminalControlSlider <MySensorBlock>("Bottom", MySpaceTexts.BlockPropertyTitle_SensorFieldHeightMin, MySpaceTexts.BlockPropertyDescription_SensorFieldBottom);

            fieldHeightMin.SetLimits(block => 1, block => block.MaxRange);
            fieldHeightMin.DefaultValue = 5;
            fieldHeightMin.Getter       = (x) => - x.m_fieldMin.Value.Y;
            fieldHeightMin.Setter       = (x, v) =>
            {
                var fieldMin = x.FieldMin;
                if (fieldMin.Y == -v)
                {
                    return;
                }
                fieldMin.Y = -v;
                x.FieldMin = fieldMin;
            };
            fieldHeightMin.Writer = (x, result) => result.AppendInt32((int)-x.m_fieldMin.Value.Y).Append(" m");
            fieldHeightMin.EnableActions();
            MyTerminalControlFactory.AddControl(fieldHeightMin);

            var fieldHeightMax = new MyTerminalControlSlider <MySensorBlock>("Top", MySpaceTexts.BlockPropertyTitle_SensorFieldHeightMax, MySpaceTexts.BlockPropertyDescription_SensorFieldTop);

            fieldHeightMax.SetLimits(block => 1, block => block.MaxRange);
            fieldHeightMax.DefaultValue = 5;
            fieldHeightMax.Getter       = (x) => x.m_fieldMax.Value.Y;
            fieldHeightMax.Setter       = (x, v) =>
            {
                var fieldMax = x.FieldMax;
                if (fieldMax.Y == v)
                {
                    return;
                }
                fieldMax.Y = v;
                x.FieldMax = fieldMax;
            };
            fieldHeightMax.Writer = (x, result) => result.AppendInt32((int)x.m_fieldMax.Value.Y).Append(" m");
            fieldHeightMax.EnableActions();
            MyTerminalControlFactory.AddControl(fieldHeightMax);

            var fieldDepthMax = new MyTerminalControlSlider <MySensorBlock>("Back", MySpaceTexts.BlockPropertyTitle_SensorFieldDepthMax, MySpaceTexts.BlockPropertyDescription_SensorFieldBack);

            fieldDepthMax.SetLimits(block => 1, block => block.MaxRange);
            fieldDepthMax.DefaultValue = 5;
            fieldDepthMax.Getter       = (x) => x.m_fieldMax.Value.Z;
            fieldDepthMax.Setter       = (x, v) =>
            {
                var fieldMax = x.FieldMax;
                if (fieldMax.Z == v)
                {
                    return;
                }
                fieldMax.Z = v;
                x.FieldMax = fieldMax;
            };
            fieldDepthMax.Writer = (x, result) => result.AppendInt32((int)x.m_fieldMax.Value.Z).Append(" m");
            fieldDepthMax.EnableActions();
            MyTerminalControlFactory.AddControl(fieldDepthMax);

            var fieldDepthMin = new MyTerminalControlSlider <MySensorBlock>("Front", MySpaceTexts.BlockPropertyTitle_SensorFieldDepthMin, MySpaceTexts.BlockPropertyDescription_SensorFieldFront);

            fieldDepthMin.SetLimits(block => 1, block => block.MaxRange);
            fieldDepthMin.DefaultValue = 5;
            fieldDepthMin.Getter       = (x) => - x.m_fieldMin.Value.Z;
            fieldDepthMin.Setter       = (x, v) =>
            {
                var fieldMin = x.FieldMin;
                if (fieldMin.Z == -v)
                {
                    return;
                }
                fieldMin.Z = -v;
                x.FieldMin = fieldMin;
            };
            fieldDepthMin.Writer = (x, result) => result.AppendInt32((int)-x.m_fieldMin.Value.Z).Append(" m");
            fieldDepthMin.EnableActions();
            MyTerminalControlFactory.AddControl(fieldDepthMin);

            var separatorFilters = new MyTerminalControlSeparator <MySensorBlock>();

            MyTerminalControlFactory.AddControl(separatorFilters);

            var detectPlayProximitySoundSwitch = new MyTerminalControlOnOffSwitch <MySensorBlock>("Audible Proximity Alert", MySpaceTexts.BlockPropertyTitle_SensorPlaySound, MySpaceTexts.BlockPropertyTitle_SensorPlaySound);

            detectPlayProximitySoundSwitch.Getter = (x) => x.PlayProximitySound;
            detectPlayProximitySoundSwitch.Setter = (x, v) =>
            {
                x.PlayProximitySound = v;
            };
            MyTerminalControlFactory.AddControl(detectPlayProximitySoundSwitch);

            var detectPlayersSwitch = new MyTerminalControlOnOffSwitch <MySensorBlock>("Detect Players", MySpaceTexts.BlockPropertyTitle_SensorDetectPlayers, MySpaceTexts.BlockPropertyTitle_SensorDetectPlayers);

            detectPlayersSwitch.Getter = (x) => x.DetectPlayers;
            detectPlayersSwitch.Setter = (x, v) =>
            {
                x.DetectPlayers = v;
            };
            detectPlayersSwitch.EnableToggleAction(MyTerminalActionIcons.CHARACTER_TOGGLE);
            detectPlayersSwitch.EnableOnOffActions(MyTerminalActionIcons.CHARACTER_ON, MyTerminalActionIcons.CHARACTER_OFF);
            MyTerminalControlFactory.AddControl(detectPlayersSwitch);

            var detectFloatingObjectsSwitch = new MyTerminalControlOnOffSwitch <MySensorBlock>("Detect Floating Objects", MySpaceTexts.BlockPropertyTitle_SensorDetectFloatingObjects, MySpaceTexts.BlockPropertyTitle_SensorDetectFloatingObjects);

            detectFloatingObjectsSwitch.Getter = (x) => x.DetectFloatingObjects;
            detectFloatingObjectsSwitch.Setter = (x, v) =>
            {
                x.DetectFloatingObjects = v;
            };
            detectFloatingObjectsSwitch.EnableToggleAction(MyTerminalActionIcons.MOVING_OBJECT_TOGGLE);
            detectFloatingObjectsSwitch.EnableOnOffActions(MyTerminalActionIcons.MOVING_OBJECT_ON, MyTerminalActionIcons.MOVING_OBJECT_OFF);
            MyTerminalControlFactory.AddControl(detectFloatingObjectsSwitch);

            var detectSmallShipsSwitch = new MyTerminalControlOnOffSwitch <MySensorBlock>("Detect Small Ships", MySpaceTexts.BlockPropertyTitle_SensorDetectSmallShips, MySpaceTexts.BlockPropertyTitle_SensorDetectSmallShips);

            detectSmallShipsSwitch.Getter = (x) => x.DetectSmallShips;
            detectSmallShipsSwitch.Setter = (x, v) =>
            {
                x.DetectSmallShips = v;
            };
            detectSmallShipsSwitch.EnableToggleAction(MyTerminalActionIcons.SMALLSHIP_TOGGLE);
            detectSmallShipsSwitch.EnableOnOffActions(MyTerminalActionIcons.SMALLSHIP_ON, MyTerminalActionIcons.SMALLSHIP_OFF);
            MyTerminalControlFactory.AddControl(detectSmallShipsSwitch);

            var detectLargeShipsSwitch = new MyTerminalControlOnOffSwitch <MySensorBlock>("Detect Large Ships", MySpaceTexts.BlockPropertyTitle_SensorDetectLargeShips, MySpaceTexts.BlockPropertyTitle_SensorDetectLargeShips);

            detectLargeShipsSwitch.Getter = (x) => x.DetectLargeShips;
            detectLargeShipsSwitch.Setter = (x, v) =>
            {
                x.DetectLargeShips = v;
            };
            detectLargeShipsSwitch.EnableToggleAction(MyTerminalActionIcons.LARGESHIP_TOGGLE);
            detectLargeShipsSwitch.EnableOnOffActions(MyTerminalActionIcons.LARGESHIP_ON, MyTerminalActionIcons.LARGESHIP_OFF);
            MyTerminalControlFactory.AddControl(detectLargeShipsSwitch);

            var detectStationsSwitch = new MyTerminalControlOnOffSwitch <MySensorBlock>("Detect Stations", MySpaceTexts.BlockPropertyTitle_SensorDetectStations, MySpaceTexts.BlockPropertyTitle_SensorDetectStations);

            detectStationsSwitch.Getter = (x) => x.DetectStations;
            detectStationsSwitch.Setter = (x, v) =>
            {
                x.DetectStations = v;
            };
            detectStationsSwitch.EnableToggleAction(MyTerminalActionIcons.STATION_TOGGLE);
            detectStationsSwitch.EnableOnOffActions(MyTerminalActionIcons.STATION_ON, MyTerminalActionIcons.STATION_OFF);
            MyTerminalControlFactory.AddControl(detectStationsSwitch);

            var detectSubgridsSwitch = new MyTerminalControlOnOffSwitch <MySensorBlock>("Detect Subgrids", MySpaceTexts.BlockPropertyTitle_SensorDetectSubgrids, MySpaceTexts.BlockPropertyTitle_SensorDetectSubgrids);

            detectSubgridsSwitch.Getter = (x) => x.DetectSubgrids;
            detectSubgridsSwitch.Setter = (x, v) =>
            {
                x.DetectSubgrids = v;
            };
            detectSubgridsSwitch.EnableToggleAction(MyTerminalActionIcons.SUBGRID_TOGGLE);
            detectSubgridsSwitch.EnableOnOffActions(MyTerminalActionIcons.SUBGRID_ON, MyTerminalActionIcons.SUBGRID_OFF);
            MyTerminalControlFactory.AddControl(detectSubgridsSwitch);

            var detectAsteroidsSwitch = new MyTerminalControlOnOffSwitch <MySensorBlock>("Detect Asteroids", MySpaceTexts.BlockPropertyTitle_SensorDetectAsteroids, MySpaceTexts.BlockPropertyTitle_SensorDetectAsteroids);

            detectAsteroidsSwitch.Getter = (x) => x.DetectAsteroids;
            detectAsteroidsSwitch.Setter = (x, v) =>
            {
                x.DetectAsteroids = v;
            };
            detectAsteroidsSwitch.EnableToggleAction();
            detectAsteroidsSwitch.EnableOnOffActions();
            MyTerminalControlFactory.AddControl(detectAsteroidsSwitch);

            var separatorFactionFilters = new MyTerminalControlSeparator <MySensorBlock>();

            MyTerminalControlFactory.AddControl(separatorFactionFilters);

            var detectOwnerSwitch = new MyTerminalControlOnOffSwitch <MySensorBlock>("Detect Owner", MySpaceTexts.BlockPropertyTitle_SensorDetectOwner, MySpaceTexts.BlockPropertyTitle_SensorDetectOwner);

            detectOwnerSwitch.Getter = (x) => x.DetectOwner;
            detectOwnerSwitch.Setter = (x, v) =>
            {
                x.DetectOwner = v;
            };
            detectOwnerSwitch.EnableToggleAction();
            detectOwnerSwitch.EnableOnOffActions();
            MyTerminalControlFactory.AddControl(detectOwnerSwitch);

            var detectFriendlySwitch = new MyTerminalControlOnOffSwitch <MySensorBlock>("Detect Friendly", MySpaceTexts.BlockPropertyTitle_SensorDetectFriendly, MySpaceTexts.BlockPropertyTitle_SensorDetectFriendly);

            detectFriendlySwitch.Getter = (x) => x.DetectFriendly;
            detectFriendlySwitch.Setter = (x, v) =>
            {
                x.DetectFriendly = v;
            };
            detectFriendlySwitch.EnableToggleAction();
            detectFriendlySwitch.EnableOnOffActions();
            MyTerminalControlFactory.AddControl(detectFriendlySwitch);

            var detectNeutralSwitch = new  MyTerminalControlOnOffSwitch <MySensorBlock>("Detect Neutral", MySpaceTexts.BlockPropertyTitle_SensorDetectNeutral, MySpaceTexts.BlockPropertyTitle_SensorDetectNeutral);

            detectNeutralSwitch.Getter = (x) => x.DetectNeutral;
            detectNeutralSwitch.Setter = (x, v) =>
            {
                x.DetectNeutral = v;
            };
            detectNeutralSwitch.EnableToggleAction();
            detectNeutralSwitch.EnableOnOffActions();
            MyTerminalControlFactory.AddControl(detectNeutralSwitch);

            var detectEnemySwitch = new MyTerminalControlOnOffSwitch <MySensorBlock>("Detect Enemy", MySpaceTexts.BlockPropertyTitle_SensorDetectEnemy, MySpaceTexts.BlockPropertyTitle_SensorDetectEnemy);

            detectEnemySwitch.Getter = (x) => x.DetectEnemy;
            detectEnemySwitch.Setter = (x, v) =>
            {
                x.DetectEnemy = v;
            };
            detectEnemySwitch.EnableToggleAction();
            detectEnemySwitch.EnableOnOffActions();
            MyTerminalControlFactory.AddControl(detectEnemySwitch);
        }
Exemplo n.º 13
0
        public static void JoinGame(GameServerItem server)
        {
            MyAnalyticsHelper.SetEntry(MyGameEntryEnum.Join);
            if (server.ServerVersion != MyFinalBuildConstants.APP_VERSION)
            {
                var sb = new StringBuilder();
                sb.AppendFormat(MyTexts.GetString(MyCommonTexts.MultiplayerError_IncorrectVersion), MyFinalBuildConstants.APP_VERSION, server.ServerVersion);
                MyGuiSandbox.Show(sb, MyCommonTexts.MessageBoxCaptionError);
                return;
            }
            if (MyFakes.ENABLE_MP_DATA_HASHES)
            {
                var serverHash = server.GetGameTagByPrefix("datahash");
                if (serverHash != "" && serverHash != MyDataIntegrityChecker.GetHashBase64())
                {
                    MyGuiSandbox.Show(MyCommonTexts.MultiplayerError_DifferentData);
                    MySandboxGame.Log.WriteLine("Different game data when connecting to server. Local hash: " + MyDataIntegrityChecker.GetHashBase64() + ", server hash: " + serverHash);
                    return;
                }
            }

            UInt32 unixTimestamp = (UInt32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;

            SteamAPI.Instance.AddFavoriteGame(server.AppID, System.Net.IPAddressExtensions.ToIPv4NetworkOrder(server.NetAdr.Address), (UInt16)server.NetAdr.Port, (UInt16)server.NetAdr.Port, FavoriteEnum.History, unixTimestamp);

            MyMultiplayerClient multiplayer = new MyMultiplayerClient(server, new MySyncLayer(new MyTransportLayer(MyMultiplayer.GameEventChannel)));

            MyMultiplayer.Static = multiplayer;
            MyMultiplayer.Static.SyncLayer.AutoRegisterGameEvents = false;
            MyMultiplayer.Static.SyncLayer.RegisterGameEvents();

            multiplayer.SendPlayerData(MySteam.UserName);

            string gamemode = server.GetGameTagByPrefix("gamemode");

            if (MyFakes.ENABLE_BATTLE_SYSTEM && gamemode == "B")
            {
                StringBuilder text = MyTexts.Get(MySpaceTexts.DialogTextJoiningBattle);

                MyGuiScreenProgress progress = new MyGuiScreenProgress(text, MyCommonTexts.Cancel);
                MyGuiSandbox.AddScreen(progress);
                progress.ProgressCancelled += () =>
                {
                    multiplayer.Dispose();
                    MyGuiScreenMainMenu.ReturnToMainMenu();
                };

                multiplayer.OnJoin += delegate
                {
                    MyJoinGameHelper.OnJoinBattle(progress, SteamSDK.Result.OK, new LobbyEnterInfo()
                    {
                        EnterState = LobbyEnterResponseEnum.Success
                    }, multiplayer);
                };
            }
            else
            {
                StringBuilder text = MyTexts.Get(MyCommonTexts.DialogTextJoiningWorld);

                MyGuiScreenProgress progress = new MyGuiScreenProgress(text, MyCommonTexts.Cancel);
                MyGuiSandbox.AddScreen(progress);
                progress.ProgressCancelled += () =>
                {
                    multiplayer.Dispose();
                    if (MyMultiplayer.Static != null)
                    {
                        MyMultiplayer.Static.Dispose();
                    }
                };

                multiplayer.OnJoin += delegate
                {
                    MyJoinGameHelper.OnJoin(progress, SteamSDK.Result.OK, new LobbyEnterInfo()
                    {
                        EnterState = LobbyEnterResponseEnum.Success
                    }, multiplayer);
                };
            }
        }
Exemplo n.º 14
0
        public static void OnJoinBattle(MyGuiScreenProgress progress, Result joinResult, LobbyEnterInfo enterInfo, MyMultiplayerBase multiplayer)
        {
            MyLog.Default.WriteLine(String.Format("Battle lobby join response: {0}, enter state: {1}", joinResult.ToString(), enterInfo.EnterState));

            bool battleCanBeJoined = multiplayer != null && multiplayer.BattleCanBeJoined;

            if (joinResult == Result.OK && enterInfo.EnterState == LobbyEnterResponseEnum.Success && battleCanBeJoined && multiplayer.GetOwner() != Sync.MyId)
            {
                // Create session with empty world
                Debug.Assert(MySession.Static == null);

                MySession.CreateWithEmptyWorld(multiplayer);
                MySession.Static.Settings.Battle = true;

                progress.CloseScreen();

                MyLog.Default.WriteLine("Battle lobby joined");

                if (MyPerGameSettings.GUI.BattleLobbyClientScreen != null)
                {
                    MyGuiSandbox.AddScreen(MyGuiSandbox.CreateScreen(MyPerGameSettings.GUI.BattleLobbyClientScreen));
                }
                else
                {
                    Debug.Fail("No battle lobby client screen");
                }
            }
            else
            {
                bool   statusFullMessage = true;
                string status            = MyTexts.GetString(MyCommonTexts.MultiplayerErrorServerHasLeft);

                if (joinResult != Result.OK)
                {
                    status            = joinResult.ToString();
                    statusFullMessage = false;
                }
                else if (enterInfo.EnterState != LobbyEnterResponseEnum.Success)
                {
                    status            = enterInfo.EnterState.ToString();
                    statusFullMessage = false;
                }
                else if (!battleCanBeJoined)
                {
                    if (MyFakes.ENABLE_JOIN_STARTED_BATTLE)
                    {
                        status            = status = MyTexts.GetString(MyCommonTexts.MultiplayerErrorSessionEnded);
                        statusFullMessage = true;
                    }
                    else
                    {
                        status            = "GameStarted";
                        statusFullMessage = false;
                    }
                }

                MyLog.Default.WriteLine("Battle join failed: " + status);

                OnJoinBattleFailed(progress, multiplayer, status, statusFullMessage: statusFullMessage);
            }
        }
 //GUI
 public override void DisplayGUI()
 {
     MyGuiSandbox.AddScreen(new MyGuiScreenTriggerAllOthersLost(this));
 }
 private unsafe void OnClickLoad(MyGuiControlBase sender)
 {
     MyGuiSandbox.AddScreen(new MyGuiScreenLoadSandbox());
 }
        void Matchmaking_LobbyChatUpdate(Lobby lobby, ulong changedUser, ulong makingChangeUser, ChatMemberStateChangeEnum stateChange)
        {
            //System.Diagnostics.Debug.Assert(MySession.Static != null);

            if (lobby.LobbyId == Lobby.LobbyId)
            {
                if (stateChange == ChatMemberStateChangeEnum.Entered)
                {
                    MySandboxGame.Log.WriteLineAndConsole("Player entered: " + MySteam.API.Friends.GetPersonaName(changedUser) + " (" + changedUser + ")");
                    MyTrace.Send(TraceWindow.Multiplayer, "Player entered");
                    Peer2Peer.AcceptSession(changedUser);

                    // When some clients connect at the same time then some of them can have already added clients
                    // (see function MySyncLayer.RegisterClientEvents which registers all Members in Lobby).
                    if (Sync.Clients == null || !Sync.Clients.HasClient(changedUser))
                    {
                        RaiseClientJoined(changedUser);

                        // Battles - send all clients, identities, players, factions as first message to client
                        if ((Battle || Scenario) && changedUser != Sync.MyId)
                        {
                            SendAllMembersDataToClient(changedUser);
                        }
                    }

                    if (MySandboxGame.IsGameReady && changedUser != ServerId)
                    {
                        // Player is able to connect to the battle which already started - player is then kicked and we do not want to show connected message in HUD.
                        bool showMsg = true;
                        if (MyFakes.ENABLE_BATTLE_SYSTEM && MySession.Static != null && MySession.Static.Battle && !BattleCanBeJoined)
                        {
                            showMsg = false;
                        }

                        if (showMsg)
                        {
                            var playerJoined = new MyHudNotification(MyCommonTexts.NotificationClientConnected, 5000, level: MyNotificationLevel.Important);
                            playerJoined.SetTextFormatArguments(MySteam.API.Friends.GetPersonaName(changedUser));
                            MyHud.Notifications.Add(playerJoined);
                        }
                    }
                }
                else
                {
                    // Kicked client can be already removed from Clients
                    if (Sync.Clients == null || Sync.Clients.HasClient(changedUser))
                    {
                        RaiseClientLeft(changedUser, stateChange);
                    }

                    if (changedUser == ServerId)
                    {
                        MyTrace.Send(TraceWindow.Multiplayer, "Host left: " + stateChange.ToString());
                        RaiseHostLeft();

                        MySessionLoader.UnloadAndExitToMenu();
                        MyGuiSandbox.AddScreen(MyGuiSandbox.CreateMessageBox(
                                                   messageCaption: MyTexts.Get(MyCommonTexts.MessageBoxCaptionError),
                                                   messageText: MyTexts.Get(MyCommonTexts.MultiplayerErrorServerHasLeft)));

                        // Set new server
                        //ServerId = Lobby.GetOwner();

                        //if (ServerId == Sync.MyId)
                        //{
                        //    Lobby.SetLobbyData(HostNameTag, Sync.MyName);
                        //}
                    }
                    else if (MySandboxGame.IsGameReady)
                    {
                        var playerLeft = new MyHudNotification(MyCommonTexts.NotificationClientDisconnected, 5000, level: MyNotificationLevel.Important);
                        playerLeft.SetTextFormatArguments(MySteam.API.Friends.GetPersonaName(changedUser));
                        MyHud.Notifications.Add(playerLeft);
                    }
                }
            }
        }
 private void OnClickPlayers(MyGuiControlButton obj)
 {
     MyGuiSandbox.AddScreen(MyGuiSandbox.CreateScreen(MyPerGameSettings.GUI.PlayersScreen));
 }
Exemplo n.º 19
0
        public MyTomasInputComponent()
        {
            AddShortcut(MyKeys.Delete, true, true, false, false,
                        () => "Delete all characters",
                        delegate
            {
                foreach (var obj in MyEntities.GetEntities().OfType <MyCharacter>())
                {
                    if (obj == MySession.ControlledEntity)
                    {
                        MySession.SetCameraController(MyCameraControllerEnum.Spectator);
                    }
                    obj.Close();
                }

                foreach (var obj in MyEntities.GetEntities().OfType <MyCubeGrid>())
                {
                    foreach (var obj2 in obj.GetBlocks())
                    {
                        if (obj2.FatBlock is MyCockpit)
                        {
                            var cockpit = obj2.FatBlock as MyCockpit;
                            if (cockpit.Pilot != null)
                            {
                                cockpit.Pilot.Close();
                            }
                        }
                    }
                }
                return(true);
            });

            AddShortcut(MyKeys.NumPad4, true, false, false, false,
                        () => "Spawn cargo ship",
                        delegate
            {
                var cargoEvent = MyGlobalEvents.GetEventById(new MyDefinitionId(typeof(MyObjectBuilder_GlobalEventDefinition), "SpawnCargoShip"));
                if (cargoEvent != null)
                {
                    MyGlobalEvents.RemoveGlobalEvent(cargoEvent);
                    cargoEvent.SetActivationTime(TimeSpan.FromSeconds(1));
                    MyGlobalEvents.AddGlobalEvent(cargoEvent);
                }
                return(true);
            });

            AddShortcut(MyKeys.NumPad5, true, false, false, false,
                        () => "Spawn random meteor",
                        delegate
            {
                var camera        = MySector.MainCamera;
                var target        = camera.Position + MySector.MainCamera.ForwardVector * 20.0f;
                var spawnPosition = target + MySector.DirectionToSunNormalized * 1000.0f;

                if (MyUtils.GetRandomFloat(0.0f, 1.0f) < 0.2f)
                {
                    MyMeteor.SpawnRandomLarge(spawnPosition, -MySector.DirectionToSunNormalized);
                }
                else
                {
                    MyMeteor.SpawnRandomSmall(spawnPosition, -MySector.DirectionToSunNormalized);
                }
                return(true);
            });

            AddShortcut(MyKeys.NumPad8, true, false, false, false,
                        () => "Switch control to next entity",
                        delegate
            {
                if (MySession.ControlledEntity != null)
                { //we already are controlling this object
                    var cameraController = MySession.GetCameraControllerEnum();
                    if (cameraController != MyCameraControllerEnum.Entity && cameraController != MyCameraControllerEnum.ThirdPersonSpectator)
                    {
                        MySession.SetCameraController(MyCameraControllerEnum.Entity, MySession.ControlledEntity.Entity);
                    }
                    else
                    {
                        var entities       = MyEntities.GetEntities().ToList();
                        int lastKnownIndex = entities.IndexOf(MySession.ControlledEntity.Entity);

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

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

                        MyCharacter newControlledObject = null;

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

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

                return(true);
            });


            AddShortcut(MyKeys.NumPad7, true, false, false, false,
                        () => "Use next ship",
                        delegate
            {
                MyCharacterInputComponent.UseNextShip();
                return(true);
            });

            AddShortcut(MyKeys.NumPad9, true, false, false, false,
                        () => "Debug new grid screen",
                        delegate
            {
                MyGuiSandbox.AddScreen(new DebugNewGridScreen());
                return(true);
            });

            AddShortcut(MyKeys.N, true, false, false, false,
                        () => "Refill all batteries",
                        delegate
            {
                foreach (var entity in MyEntities.GetEntities())
                {
                    MyCubeGrid grid = entity as MyCubeGrid;
                    if (grid != null)
                    {
                        foreach (var block in grid.GetBlocks())
                        {
                            MyBatteryBlock battery = block.FatBlock as MyBatteryBlock;
                            if (battery != null)
                            {
                                battery.CurrentStoredPower = battery.MaxStoredPower;
                            }
                        }
                    }
                }
                return(true);
            });

            AddShortcut(MyKeys.U, true, false, false, false,
                        () => "Spawn new character",
                        delegate
            {
                var character = MyCharacterInputComponent.SpawnCharacter();
                return(true);
            });


            AddShortcut(MyKeys.NumPad2, true, false, false, false,
                        () => "Merge static grids",
                        delegate
            {
                // Try to merge all static large grids
                HashSet <MyCubeGrid> ignoredGrids = new HashSet <MyCubeGrid>();
                while (true)
                {
                    // Flag that we need new entities enumeration
                    bool needNewEntitites = false;

                    foreach (var entity in MyEntities.GetEntities())
                    {
                        MyCubeGrid grid = entity as MyCubeGrid;
                        if (grid != null && grid.IsStatic && grid.GridSizeEnum == MyCubeSize.Large)
                        {
                            if (ignoredGrids.Contains(grid))
                            {
                                continue;
                            }

                            List <MySlimBlock> blocks = grid.GetBlocks().ToList();
                            foreach (var block in blocks)
                            {
                                var mergedGrid = grid.DetectMerge(block);
                                if (mergedGrid == null)
                                {
                                    continue;
                                }

                                needNewEntitites = true;
                                // Grid merged to other grid? Then break and loop all entities again.
                                if (mergedGrid != grid)
                                {
                                    break;
                                }
                            }

                            if (!needNewEntitites)
                            {
                                ignoredGrids.Add(grid);
                            }
                        }

                        if (needNewEntitites)
                        {
                            break;
                        }
                    }

                    if (!needNewEntitites)
                    {
                        break;
                    }
                }
                return(true);
            });

            AddShortcut(MyKeys.Add, true, false, false, false,
                        () => "Increase wheel animation speed",
                        delegate
            {
                USE_WHEEL_ANIMATION_SPEED += 0.05f;
                return(true);
            });

            AddShortcut(MyKeys.Subtract, true, false, false, false,
                        () => "Decrease wheel animation speed",
                        delegate
            {
                USE_WHEEL_ANIMATION_SPEED -= 0.05f;
                return(true);
            });

            AddShortcut(MyKeys.Divide, true, false, false, false,
                        () => "Show model texture names",
                        delegate
            {
                MyFakes.ENABLE_DEBUG_DRAW_TEXTURE_NAMES = !MyFakes.ENABLE_DEBUG_DRAW_TEXTURE_NAMES;
                return(true);
            });

            AddShortcut(MyKeys.NumPad1, true, false, false, false,
                        () => "Throw from spectator: " + Sandbox.Game.Components.MySessionComponentThrower.USE_SPECTATOR_FOR_THROW,
                        delegate
            {
                Sandbox.Game.Components.MySessionComponentThrower.USE_SPECTATOR_FOR_THROW = !Sandbox.Game.Components.MySessionComponentThrower.USE_SPECTATOR_FOR_THROW;
                return(true);
            });

            AddShortcut(MyKeys.F2, true, false, false, false, () => "Spectator to next small grid", () => SpectatorToNextGrid(MyCubeSize.Small));
            AddShortcut(MyKeys.F3, true, false, false, false, () => "Spectator to next large grid", () => SpectatorToNextGrid(MyCubeSize.Large));
        }
 private void OnClickCredits(MyGuiControlButton sender)
 {
     //opens dialog screen with list of trailers, where could be selected animation to play
     MyGuiSandbox.AddScreen(new MyGuiScreenGameCredits());
 }
Exemplo n.º 21
0
        public static void Publish(MyObjectBuilder_Definitions prefab, string blueprintName, Action <ulong> publishCallback = null)
        {
            string file        = Path.Combine(m_localBlueprintFolder, blueprintName);
            string title       = prefab.ShipBlueprints[0].CubeGrids[0].DisplayName;
            string description = prefab.ShipBlueprints[0].Description;
            ulong  publishId   = prefab.ShipBlueprints[0].WorkshopId;

            MyGuiSandbox.AddScreen(MyGuiSandbox.CreateMessageBox(
                                       styleEnum : MyMessageBoxStyleEnum.Info,
                                       buttonType : MyMessageBoxButtonsType.YES_NO,
                                       messageCaption : new StringBuilder("Publish"),
                                       messageText : new StringBuilder("Do you want to publish this blueprint?"),
                                       callback : delegate(MyGuiScreenMessageBox.ResultEnum val)
            {
                if (val == MyGuiScreenMessageBox.ResultEnum.YES)
                {
                    Action <MyGuiScreenMessageBox.ResultEnum, string[]> onTagsChosen = delegate(MyGuiScreenMessageBox.ResultEnum tagsResult, string[] outTags)
                    {
                        if (tagsResult == MyGuiScreenMessageBox.ResultEnum.YES)
                        {
                            MySteamWorkshop.PublishBlueprintAsync(file, title, description, publishId, outTags, SteamSDK.PublishedFileVisibility.Public,
                                                                  callbackOnFinished : delegate(bool success, Result result, ulong publishedFileId)
                            {
                                if (success)
                                {
                                    if (publishCallback != null)
                                    {
                                        publishCallback(publishedFileId);
                                    }

                                    prefab.ShipBlueprints[0].WorkshopId = publishedFileId;
                                    SavePrefabToFile(prefab, blueprintName, true);
                                    MyGuiSandbox.AddScreen(MyGuiSandbox.CreateMessageBox(
                                                               styleEnum: MyMessageBoxStyleEnum.Info,
                                                               messageText: MyTexts.Get(MyCommonTexts.MessageBoxTextWorldPublished),
                                                               messageCaption: new StringBuilder("BLUEPRINT PUBLISHED"),
                                                               callback: (a) =>
                                    {
                                        MySteam.API.OpenOverlayUrl(string.Format("http://steamcommunity.com/sharedfiles/filedetails/?id={0}", publishedFileId));
                                    }));
                                }
                                else
                                {
                                    MyStringId error;
                                    switch (result)
                                    {
                                    case Result.AccessDenied:
                                        error = MyCommonTexts.MessageBoxTextPublishFailed_AccessDenied;
                                        break;

                                    default:
                                        error = MyCommonTexts.MessageBoxTextWorldPublishFailed;
                                        break;
                                    }

                                    MyGuiSandbox.AddScreen(MyGuiSandbox.CreateMessageBox(
                                                               messageText: MyTexts.Get(error),
                                                               messageCaption: MyTexts.Get(MyCommonTexts.MessageBoxCaptionWorldPublishFailed)));
                                }
                            });
                        }
                    };

                    if (MySteamWorkshop.BlueprintCategories.Length > 0)
                    {
                        MyGuiSandbox.AddScreen(new MyGuiScreenWorkshopTags(MySteamWorkshop.WORKSHOP_BLUEPRINT_TAG, MySteamWorkshop.BlueprintCategories, null, onTagsChosen));
                    }
                    else
                    {
                        onTagsChosen(MyGuiScreenMessageBox.ResultEnum.YES, new string[] { MySteamWorkshop.WORKSHOP_BLUEPRINT_TAG });
                    }
                }
            }));
        }
 private void OnClickHelp(MyGuiControlButton sender)
 {
     MyGuiSandbox.AddScreen(MyGuiSandbox.CreateScreen(MyPerGameSettings.GUI.HelpScreen));
 }
Exemplo n.º 23
0
        public static void LoadMission(string sessionPath, bool multiplayer, MyOnlineModeEnum onlineMode, short maxPlayers)
        {
            MyLog.Default.WriteLine("LoadSession() - Start");
            MyLog.Default.WriteLine(sessionPath);

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

            checkpoint.Settings.OnlineMode       = onlineMode;
            checkpoint.Settings.MaxPlayers       = maxPlayers;
            checkpoint.Settings.Scenario         = true;
            checkpoint.Settings.GameMode         = MyGameModeEnum.Survival;
            checkpoint.Settings.ScenarioEditMode = false;

            if (!MySession.IsCompatibleVersion(checkpoint))
            {
                MyLog.Default.WriteLine(MyTexts.Get(MySpaceTexts.DialogTextIncompatibleWorldVersion).ToString());
                MyGuiSandbox.AddScreen(MyGuiSandbox.CreateMessageBox(
                                           messageCaption: MyTexts.Get(MySpaceTexts.MessageBoxCaptionError),
                                           messageText: MyTexts.Get(MySpaceTexts.DialogTextIncompatibleWorldVersion),
                                           buttonType: MyMessageBoxButtonsType.OK));
                MyLog.Default.WriteLine("LoadSession() - End");
                return;
            }

            if (checkpoint.BriefingVideo != null && checkpoint.BriefingVideo.Length > 0)
            {
                MyGuiSandbox.OpenUrlWithFallback(checkpoint.BriefingVideo, "Scenario briefing video");
            }

            if (!MySteamWorkshop.CheckLocalModsAllowed(checkpoint.Mods, checkpoint.Settings.OnlineMode == MyOnlineModeEnum.OFFLINE))
            {
                MyLog.Default.WriteLine(MyTexts.Get(MySpaceTexts.DialogTextLocalModsDisabledInMultiplayer).ToString());
                MyGuiSandbox.AddScreen(MyGuiSandbox.CreateMessageBox(
                                           messageCaption: MyTexts.Get(MySpaceTexts.MessageBoxCaptionError),
                                           messageText: MyTexts.Get(MySpaceTexts.DialogTextLocalModsDisabledInMultiplayer),
                                           buttonType: MyMessageBoxButtonsType.OK));
                MyLog.Default.WriteLine("LoadSession() - End");
                return;
            }


            MySteamWorkshop.DownloadModsAsync(checkpoint.Mods, delegate(bool success)
            {
                if (success || (checkpoint.Settings.OnlineMode == MyOnlineModeEnum.OFFLINE) && MySteamWorkshop.CanRunOffline(checkpoint.Mods))
                {
                    //Sandbox.Audio.MyAudio.Static.Mute = true;

                    MyScreenManager.CloseAllScreensNowExcept(null);
                    MyGuiSandbox.Update(MyEngineConstants.UPDATE_STEP_SIZE_IN_MILLISECONDS);

                    // May be called from gameplay, so we must make sure we unload the current game
                    if (MySession.Static != null)
                    {
                        MySession.Static.Unload();
                        MySession.Static = null;
                    }

                    //seed 0 has special meaning - please randomize at mission start. New seed will be saved and game will run with it ever since.
                    //  if you use this, YOU CANNOT HAVE ANY PROCEDURAL ASTEROIDS ALREADY SAVED
                    if (checkpoint.Settings.ProceduralSeed == 0)
                    {
                        checkpoint.Settings.ProceduralSeed = MyRandom.Instance.Next();
                    }

                    MyGuiScreenGamePlay.StartLoading(delegate
                    {
                        checkpoint.Settings.Scenario = true;
                        MySession.LoadMission(sessionPath, checkpoint, checkpointSizeInBytes);
                    });
                }
                else
                {
                    MyLog.Default.WriteLine(MyTexts.Get(MySpaceTexts.DialogTextDownloadModsFailed).ToString());
                    MyGuiSandbox.AddScreen(MyGuiSandbox.CreateMessageBox(
                                               messageCaption : MyTexts.Get(MySpaceTexts.MessageBoxCaptionError),
                                               messageText : MyTexts.Get(MySpaceTexts.DialogTextDownloadModsFailed),
                                               buttonType : MyMessageBoxButtonsType.OK, callback : delegate(MyGuiScreenMessageBox.ResultEnum result)
                    {
                        if (MyFakes.QUICK_LAUNCH != null)
                        {
                            MyGuiScreenMainMenu.ReturnToMainMenu();
                        }
                    }));
                }
                MyLog.Default.WriteLine("LoadSession() - End");
            });
        }
 void OnClickSaveAs(MyGuiControlButton sender)
 {
     MyGuiSandbox.AddScreen(new MyGuiScreenSaveAs(MySession.Static.Name));
 }
Exemplo n.º 25
0
 public override void Activate()
 {
     MyScreenManager.CloseScreen(typeof(MyGuiScreenControlMenu));
     MyGuiSandbox.AddScreen(MyGuiScreenGamePlay.ActiveGameplayScreen = new MyGuiScreenColorPicker());
 }
 //  This is for adding main menu the easy way
 public static void AddMainMenu(bool pauseGame = false)
 {
     MyGuiSandbox.AddScreen(new MyGuiScreenMainMenu(pauseGame));
 }
 private void OnWorldGeneratorClick(object sender)
 {
     WorldGenerator = new MyGuiScreenWorldGeneratorSettings(this);
     WorldGenerator.OnOkButtonClicked += WorldGenerator_OnOkButtonClicked;
     MyGuiSandbox.AddScreen(WorldGenerator);
 }
Exemplo n.º 28
0
 void LoadPublicLobbies()
 {
     MyGuiSandbox.AddScreen(new MyGuiScreenProgressAsync(MyCommonTexts.LoadingPleaseWait, null, beginAction, endPublicLobbiesAction));
 }
 private void ShowControlIsNotValidMessageBox()
 {
     MyGuiSandbox.AddScreen(MyGuiSandbox.CreateMessageBox(
                                messageText: MyTexts.Get(MyCommonTexts.ControlIsNotValid),
                                messageCaption: MyTexts.Get(MyCommonTexts.CanNotAssignControl)));
 }
Exemplo n.º 30
0
 private void RefreshCustomWorldsList()
 {
     // Add loading mini screen
     MyGuiSandbox.AddScreen(new MyGuiScreenProgressAsync(MyCommonTexts.LoadingPleaseWait, null, StartLoadingWorldInfos, OnLoadingFinished));
 }