示例#1
0
        /// <summary>
        /// Toggles blips on/off.
        /// </summary>
        /// <param name="enable"></param>
        private void ToggleBlips(bool enable)
        {
            if (enable)
            {
                string json = LoadResourceFile(GetCurrentResourceName(), "config/locations.json");
                if (string.IsNullOrEmpty(json))
                {
                    Notify.Error("An error occurred while loading the locations file.");
                }
                else
                {
                    try
                    {
                        Newtonsoft.Json.Linq.JObject data = JsonConvert.DeserializeObject <Newtonsoft.Json.Linq.JObject>(json);
                        if (data != null && data["blips"] != null && data["blips"].Count() > 0)
                        {
                            foreach (Newtonsoft.Json.Linq.JToken blip in data["blips"])
                            {
                                string  name     = blip["name"].ToString();
                                int     color    = (int)blip["color"];
                                int     spriteID = (int)blip["spriteID"];
                                Vector3 coords   = new Vector3((float)blip["coordinates"]["x"], (float)blip["coordinates"]["y"], (float)blip["coordinates"]["z"]);
                                int     blipID   = AddBlipForCoord(coords.X, coords.Y, coords.Z);
                                SetBlipSprite(blipID, spriteID);
                                BeginTextCommandSetBlipName("STRING");
                                AddTextComponentSubstringPlayerName(name);
                                EndTextCommandSetBlipName(blipID);
                                SetBlipColour(blipID, color);
                                SetBlipAsShortRange(blipID, true);


                                Blip b = new Blip(coords, spriteID, name, color, blipID);
                                blips.Add(b);
                            }
                        }
                    }
                    catch (JsonReaderException ex)
                    {
                        Debug.Write($"\n\n[vMenu] An error occurred while loading the locations.json file. Please contact the server owner to resolve this.\nWhen contacting the owner, provide the following error details:\n{ex.Message}.\n\n\n");
                    }
                }
            }
            else
            {
                if (blips.Count > 0)
                {
                    foreach (Blip blip in blips)
                    {
                        int id = blip.blipID;
                        if (DoesBlipExist(id))
                        {
                            RemoveBlip(ref id);
                        }
                    }
                }
                blips.Clear();
            }
        }
示例#2
0
        /// <summary>
        /// Method for spawning entity with EntitySpawner. After entity is spawned you will be able to change
        /// position of entity with your mouse.
        /// </summary>
        /// <param name="model">model of entity as hash</param>
        /// <param name="coords">initial coords for the entity</param>
        /// <returns>true spawn was succesful</returns>
        public static async void SpawnEntity(uint model, Vector3 coords)
        {
            if (!IsModelValid(model))
            {
                Notify.Error(CommonErrors.InvalidInput);
                return;
            }

            if (CurrentEntity != null)
            {
                Notify.Error("One entity is currently beeing processed");
                return;
            }

            int handle = 0;

            RequestModel(model);
            while (!HasModelLoaded(model))
            {
                await Delay(1);
            }
            if (IsModelAPed(model))
            {
                handle = CreatePed(4, model, coords.X, coords.Y, coords.Z, Game.PlayerPed.Heading, true, true);
            }
            else if (IsModelAVehicle(model))
            {
                int modelClass = GetVehicleClassFromName(model);
                if (!VehicleSpawner.allowedCategories[modelClass])
                {
                    Notify.Alert("You are not allowed to spawn this vehicle, because it belongs to a category which is restricted by the server owner.");
                    return;
                }
                handle = CreateVehicle(model, coords.X, coords.Y, coords.Z, Game.PlayerPed.Heading, true, true);
            }
            else
            {
                handle = CreateObject((int)model, coords.X, coords.Y, coords.Z, true, true, true);
            }

            SetEntityAsMissionEntity(handle, true, true); // Set As mission to prevent despawning

            CurrentEntity = Entity.FromHandle(handle);

            if (!CurrentEntity.Exists())
            {
                throw new Exception("Failed to create entity");
            }


            if (!Active)
            {
                Active = true;
            }
        }
示例#3
0
        /// <summary>
        /// Notifies the player that the current version of vMenu is outdated.
        /// </summary>
        private async void NotifyOutdatedVersion(string message)
        {
            Debug.WriteLine("\n\n\n\n[vMenu] [WARNING] vMenu is outdated, please update as soon as possible. Update info:\n" + message + "\n\n\n\n");
            while (IsHudHidden() || !IsHudPreferenceSwitchedOn() || !IsScreenFadedIn() || IsPlayerSwitchInProgress())
            {
                await Delay(0);
            }

            Log("Sending alert now after the hud is confirmed to be enabled.");

            Notify.Error("vMenu is outdated. Please update as soon as possible!", true, true);
            Notify.Custom(message, true, true);
        }
示例#4
0
        public async void SaveCamera(string updateExistingSavedCameraName = null)
        {
            DroneSaveInfo ci = new DroneSaveInfo()
            {
                gravityMult_      = gravityMult,
                timestepMult_     = timestepMult,
                dragMult_         = dragMult,
                accelerationMult_ = accelerationMult,
                rotationMult_     = rotationMult,
                maxVel_           = maxVel,
                tiltAngle_        = tiltAngle,
                droneFov_         = droneFov
            };

            if (updateExistingSavedCameraName == null)
            {
                var saveName = await GetUserInput(windowTitle : "Enter a save name", maxInputLength : 30);

                // If the name is not invalid.
                if (!string.IsNullOrEmpty(saveName))
                {
                    // Save everything from the dictionary into the client's kvp storage.
                    // If the save was successfull:
                    if (SaveCameraInfo("xdm_" + saveName, ci, false))
                    {
                        Notify.Success($"Drone {saveName} saved.");
                        LoadDroneCameras();
                    }
                    // If the save was not successfull:
                    else
                    {
                        Notify.Error(CommonErrors.SaveNameAlreadyExists, placeholderValue: "(" + saveName + ")");
                    }
                }
                // The user did not enter a valid name to use as a save name for this vehicle.
                else
                {
                    Notify.Error(CommonErrors.InvalidSaveName);
                }
            }
            // We need to update an existing slot.
            else
            {
                SaveCameraInfo("xdm_" + updateExistingSavedCameraName, ci, true);
            }
        }
示例#5
0
        /// <summary>
        /// Method for spawning entity with EntitySpawner. After entity is spawned you will be able to change
        /// position of entity with your mouse.
        /// </summary>
        /// <param name="model">model of entity as hash</param>
        /// <param name="coords">initial coords for the entity</param>
        /// <returns>true spawn was succesful</returns>
        public static async void SpawnEntity(uint model, Vector3 coords)
        {
            if (!IsModelValid(model))
            {
                Notify.Error(CommonErrors.InvalidInput);
                return;
            }

            if (CurrentEntity != null)
            {
                Notify.Error("One entity is currently being processed.");
                return;
            }

            int handle;

            RequestModel(model);
            while (!HasModelLoaded(model))
            {
                await Delay(1);
            }
            if (IsModelAPed(model))
            {
                handle = CreatePed(4, model, coords.X, coords.Y, coords.Z, Game.PlayerPed.Heading, true, true);
            }
            else if (IsModelAVehicle(model))
            {
                handle = await CommonFunctions.SpawnVehicle(model, false, false, skipLoad : false, vehicleInfo : new CommonFunctions.VehicleInfo(), saveName : null, coords.X, coords.Y, coords.Z, Game.PlayerPed.Heading);
            }
            else
            {
                handle = CreateObject((int)model, coords.X, coords.Y, coords.Z, true, true, true);
            }

            CurrentEntity = Entity.FromHandle(handle);

            if (!CurrentEntity.Exists())
            {
                Notify.Error("Failed to create entity");
                return;
            }

            SetEntityAsMissionEntity(handle, true, true); // Set As mission to prevent despawning

            Active = true;
        }
示例#6
0
        /// <summary>
        /// Updates the selected vehicle.
        /// </summary>
        /// <param name="selectedItem"></param>
        /// <returns>A bool, true if successfull, false if unsuccessfull</returns>
        private bool UpdateSelectedVehicleMenu(MenuItem selectedItem, Menu parentMenu = null)
        {
            if (!svMenuItems.ContainsKey(selectedItem))
            {
                Notify.Error("In some very strange way, you've managed to select a button, that does not exist according to this list. So your vehicle could not be loaded. :( Maybe your save files are broken?");
                return(false);
            }
            var vehInfo = svMenuItems[selectedItem];

            selectedVehicleMenu.MenuSubtitle = $"{vehInfo.Key.Substring(4)} ({vehInfo.Value.name})";
            currentlySelectedVehicle         = vehInfo;
            MenuController.CloseAllMenus();
            selectedVehicleMenu.OpenMenu();
            if (parentMenu != null)
            {
                MenuController.AddSubmenu(parentMenu, selectedVehicleMenu);
            }
            return(true);
        }
示例#7
0
 private bool SpawnSavedCamera()
 {
     if (currentlySelectedDrone.Key != null)
     {
         gravityMult      = currentlySelectedDrone.Value.gravityMult_;
         timestepMult     = currentlySelectedDrone.Value.timestepMult_;
         dragMult         = currentlySelectedDrone.Value.dragMult_;
         accelerationMult = currentlySelectedDrone.Value.accelerationMult_;
         rotationMult     = currentlySelectedDrone.Value.rotationMult_;
         maxVel           = currentlySelectedDrone.Value.maxVel_;
         tiltAngle        = currentlySelectedDrone.Value.tiltAngle_;
         droneFov         = currentlySelectedDrone.Value.droneFov_;
     }
     else
     {
         Notify.Error("It seems that this slot got corrupted in some way, you need to delete it.");
         return(false);
     }
     return(true);
 }
示例#8
0
        /// <summary>
        /// Disables all the submenus except for three first checkboxes
        /// </summary>
        public void DisableMenus()
        {
            // Disable everything
            List <MenuItem> items = GetMenu().GetMenuItems();

            foreach (MenuItem item in items)
            {
                item.Enabled = false;
            }
            // Reenable Drift Cam, Chase Cam, Drone Cam fields
            if (items.Count >= 3)
            {
                items[0].Enabled = true;
                items[1].Enabled = true;
                items[2].Enabled = true;
            }
            else
            {
                Notify.Error("Your menu does not seem to have any submenus, something got corrupted.");
            }
        }
示例#9
0
        /// <summary>
        /// Creates the menu.
        /// </summary>
        private void CreateMenu()
        {
            try
            {
                MenuController.MenuAlignment = MiscRightAlignMenu ? MenuController.MenuAlignmentOption.Right : MenuController.MenuAlignmentOption.Left;
            }
            catch (AspectRatioException)
            {
                Notify.Error(CommonErrors.RightAlignedNotSupported);
                // (re)set the default to left just in case so they don't get this error again in the future.
                MenuController.MenuAlignment    = MenuController.MenuAlignmentOption.Left;
                MiscRightAlignMenu              = false;
                UserDefaults.MiscRightAlignMenu = false;
            }

            // Create the menu.
            menu = new Menu("YDDY:RP", "Прочие настройки");

            // teleport menu
            Menu     teleportMenu    = new Menu(Game.Player.Name, "Teleport Locations");
            MenuItem teleportMenuBtn = new MenuItem("Teleport Locations", "Teleport to pre-configured locations, added by the server owner.");

            MenuController.AddSubmenu(menu, teleportMenu);
            MenuController.BindMenuItem(menu, teleportMenu, teleportMenuBtn);

            // keybind settings menu
            Menu     keybindMenu    = new Menu(Game.Player.Name, "Бинды");
            MenuItem keybindMenuBtn = new MenuItem("Настройки биндов", "Включите или выключите бинды на функции трейнера.");

            MenuController.AddSubmenu(menu, keybindMenu);
            MenuController.BindMenuItem(menu, keybindMenu, keybindMenuBtn);

            // keybind settings menu items
            MenuCheckboxItem kbTpToWaypoint = new MenuCheckboxItem("Teleport To Waypoint", "Teleport to your waypoint when pressing the keybind. By default, this keybind is set to ~r~F7~s~, server owners are able to change this however so ask them if you don't know what it is.", KbTpToWaypoint);
            MenuCheckboxItem kbDriftMode    = new MenuCheckboxItem("Drift Mode", "Makes your vehicle have almost no traction while holding left shift on keyboard, or X on controller.", KbDriftMode);
            MenuItem         backBtn        = new MenuItem("Назад");

            // Create the menu items.
            MenuItem         tptowp         = new MenuItem("Teleport To Waypoint", "Teleport to the waypoint on your map.");
            MenuCheckboxItem rightAlignMenu = new MenuCheckboxItem("Меню справа", "", MiscRightAlignMenu);
            MenuCheckboxItem speedKmh       = new MenuCheckboxItem("Спидометр в км/ч", "", ShowSpeedoKmh);
            MenuCheckboxItem speedMph       = new MenuCheckboxItem("Спидометр в м/ч", "", ShowSpeedoMph);
            MenuCheckboxItem coords         = new MenuCheckboxItem("Show Coordinates", "Show your current coordinates at the top of your screen.", ShowCoordinates);
            MenuCheckboxItem hideRadar      = new MenuCheckboxItem("Спрятать радар", "", HideRadar);
            MenuCheckboxItem hideHud        = new MenuCheckboxItem("Спрятать худ", "", HideHud);
            MenuCheckboxItem showLocation   = new MenuCheckboxItem("Location Display", "Shows your current location and heading, as well as the nearest cross road. Similar like PLD. ~r~Warning: This feature (can) take about 1.6 FPS when running at 60 Hz.", ShowLocation)
            {
                LeftIcon = MenuItem.Icon.WARNING
            };
            MenuCheckboxItem drawTime     = new MenuCheckboxItem("Показывать игровое время", "", DrawTimeOnScreen);
            MenuItem         saveSettings = new MenuItem("Сохранить настройки", "")
            {
                RightIcon = MenuItem.Icon.TICK
            };
            MenuCheckboxItem joinQuitNotifs  = new MenuCheckboxItem("Уведомления о входе / выходе", "", JoinQuitNotifications);
            MenuCheckboxItem deathNotifs     = new MenuCheckboxItem("Уведомления о смерти", "", DeathNotifications);
            MenuCheckboxItem nightVision     = new MenuCheckboxItem("Ночное видение", "", false);
            MenuCheckboxItem thermalVision   = new MenuCheckboxItem("Toggle Thermal Vision", "Enable or disable thermal vision.", false);
            MenuCheckboxItem modelDimensions = new MenuCheckboxItem("Показывать размеры т/с", "", ShowVehicleModelDimensions);

            MenuItem         clearArea = new MenuItem("Очистить зону", "");
            MenuCheckboxItem lockCamX  = new MenuCheckboxItem("Заблокировать камеру горизонтально", "", false);
            MenuCheckboxItem lockCamY  = new MenuCheckboxItem("Заблокировать камеру вертикально", "", false);

            Menu     connectionSubmenu    = new Menu("YDDY:RP", "Опции подключения");
            MenuItem connectionSubmenuBtn = new MenuItem("Подключение", "Опции подключения к серверу");
            MenuItem quitSession          = new MenuItem("Выйти из сессии", "");
            MenuItem quitGame             = new MenuItem("Выйти из игры", "");
            MenuItem disconnectFromServer = new MenuItem("Отключиться от сервера", "");

            connectionSubmenu.AddMenuItem(quitSession);
            connectionSubmenu.AddMenuItem(quitGame);
            connectionSubmenu.AddMenuItem(disconnectFromServer);

            MenuCheckboxItem locationBlips           = new MenuCheckboxItem("Location Blips", "Shows blips on the map for some common locations.", ShowLocationBlips);
            MenuCheckboxItem playerBlips             = new MenuCheckboxItem("Show Player Blips", "Shows blips on the map for all players.", ShowPlayerBlips);
            MenuCheckboxItem respawnDefaultCharacter = new MenuCheckboxItem("Спавниться как MP по умолчанию", "", MiscRespawnDefaultCharacter);
            MenuCheckboxItem restorePlayerAppearance = new MenuCheckboxItem("Восстанавливать внешний вид", "", RestorePlayerAppearance);
            MenuCheckboxItem restorePlayerWeapons    = new MenuCheckboxItem("Восстанавливать оружие", "", RestorePlayerWeapons);

            MenuController.AddSubmenu(menu, connectionSubmenu);
            MenuController.BindMenuItem(menu, connectionSubmenu, connectionSubmenuBtn);
            //MainMenu.Mp.Add(connectionSubmenu);
            //connectionSubmenu.RefreshIndex();
            //connectionSubmenu.UpdateScaleform();
            //menu.BindMenuToItem(connectionSubmenu, connectionSubmenuBtn);

            keybindMenu.OnCheckboxChange += (sender, item, index, _checked) =>
            {
                if (item == kbTpToWaypoint)
                {
                    KbTpToWaypoint = _checked;
                }
                else if (item == kbDriftMode)
                {
                    KbDriftMode = _checked;
                }
            };
            keybindMenu.OnItemSelect += (sender, item, index) =>
            {
                if (item == backBtn)
                {
                    keybindMenu.GoBack();
                }
            };

            connectionSubmenu.OnItemSelect += (sender, item, index) =>
            {
                if (item == quitGame)
                {
                    QuitGame();
                }
                else if (item == quitSession)
                {
                    QuitSession();
                }
                else if (item == disconnectFromServer)
                {
                    BaseScript.TriggerServerEvent("vMenu:DisconnectSelf");
                }
            };

            // Add menu items to the menu.
            if (IsAllowed(Permission.MSTeleportToWp))
            {
                menu.AddMenuItem(tptowp);
                keybindMenu.AddMenuItem(kbTpToWaypoint);
            }

            if (IsAllowed(Permission.MSDriftMode))
            {
                keybindMenu.AddMenuItem(kbDriftMode);
            }

            keybindMenu.AddMenuItem(backBtn);

            // Always allowed
            menu.AddMenuItem(rightAlignMenu);
            menu.AddMenuItem(speedKmh);
            menu.AddMenuItem(speedMph);
            menu.AddMenuItem(modelDimensions);
            menu.AddMenuItem(keybindMenuBtn);
            keybindMenuBtn.Label = "→→→";
            if (IsAllowed(Permission.MSConnectionMenu))
            {
                menu.AddMenuItem(connectionSubmenuBtn);
                connectionSubmenuBtn.Label = "→→→";
            }
            if (IsAllowed(Permission.MSShowCoordinates))
            {
                menu.AddMenuItem(coords);
            }
            if (IsAllowed(Permission.MSShowLocation))
            {
                menu.AddMenuItem(showLocation);
            }
            menu.AddMenuItem(drawTime); // always allowed
            if (IsAllowed(Permission.MSJoinQuitNotifs))
            {
                menu.AddMenuItem(deathNotifs);
            }
            if (IsAllowed(Permission.MSDeathNotifs))
            {
                menu.AddMenuItem(joinQuitNotifs);
            }
            if (IsAllowed(Permission.MSNightVision))
            {
                menu.AddMenuItem(nightVision);
            }
            if (IsAllowed(Permission.MSThermalVision))
            {
                menu.AddMenuItem(thermalVision);
            }
            if (IsAllowed(Permission.MSLocationBlips))
            {
                menu.AddMenuItem(locationBlips);
                ToggleBlips(ShowLocationBlips);
            }
            if (IsAllowed(Permission.MSPlayerBlips))
            {
                menu.AddMenuItem(playerBlips);
            }
            if (IsAllowed(Permission.MSTeleportLocations))
            {
                menu.AddMenuItem(teleportMenuBtn);
                teleportMenuBtn.Label = "→→→";

                string json = LoadResourceFile(GetCurrentResourceName(), "config/locations.json");
                if (string.IsNullOrEmpty(json))
                {
                    Notify.Error("An error occurred while loading the locations file.");
                }
                else
                {
                    try
                    {
                        Newtonsoft.Json.Linq.JObject data = JsonConvert.DeserializeObject <Newtonsoft.Json.Linq.JObject>(json);
                        foreach (Newtonsoft.Json.Linq.JToken teleport in data["teleports"])
                        {
                            string   name        = teleport["name"].ToString();
                            float    heading     = (float)teleport["heading"];
                            Vector3  coordinates = new Vector3((float)teleport["coordinates"]["x"], (float)teleport["coordinates"]["y"], (float)teleport["coordinates"]["z"]);
                            MenuItem tpBtn       = new MenuItem(name, $"Teleport to X: {(int)coordinates.X} Y: {(int)coordinates.Y} Z: {(int)coordinates.Z} HEADING: {(int)heading}.");
                            teleportMenu.AddMenuItem(tpBtn);
                            tpLocations.Add(coordinates);
                            tpLocationsHeading.Add(heading);
                        }
                        teleportMenu.OnItemSelect += async(sender, item, index) =>
                        {
                            await TeleportToCoords(tpLocations[index], true);

                            SetEntityHeading(Game.PlayerPed.Handle, tpLocationsHeading[index]);
                        };
                    }
                    catch (JsonReaderException ex)
                    {
                        Debug.Write($"\n[vMenu] An error occurred whie loading the teleport locations!\nReport the following error details to the server owner:\n{ex.Message}.\n");
                    }
                }
            }
            if (IsAllowed(Permission.MSClearArea))
            {
                menu.AddMenuItem(clearArea);
            }
            // always allowed, it just won't do anything if the server owner disabled the feature, but players can still toggle it.
            menu.AddMenuItem(respawnDefaultCharacter);
            if (IsAllowed(Permission.MSRestoreAppearance))
            {
                menu.AddMenuItem(restorePlayerAppearance);
            }
            if (IsAllowed(Permission.MSRestoreWeapons))
            {
                menu.AddMenuItem(restorePlayerWeapons);
            }

            // Always allowed
            menu.AddMenuItem(hideRadar);
            menu.AddMenuItem(hideHud);
            menu.AddMenuItem(lockCamX);
            menu.AddMenuItem(lockCamY);
            menu.AddMenuItem(saveSettings);

            // Handle checkbox changes.
            menu.OnCheckboxChange += (sender, item, index, _checked) =>
            {
                if (item == rightAlignMenu)
                {
                    try
                    {
                        MenuController.MenuAlignment    = _checked ? MenuController.MenuAlignmentOption.Right : MenuController.MenuAlignmentOption.Left;
                        MiscRightAlignMenu              = _checked;
                        UserDefaults.MiscRightAlignMenu = MiscRightAlignMenu;
                    }
                    catch (AspectRatioException)
                    {
                        Notify.Error(CommonErrors.RightAlignedNotSupported);
                        // (re)set the default to left just in case so they don't get this error again in the future.
                        MenuController.MenuAlignment    = MenuController.MenuAlignmentOption.Left;
                        MiscRightAlignMenu              = false;
                        UserDefaults.MiscRightAlignMenu = false;
                    }
                }
                if (item == speedKmh)
                {
                    ShowSpeedoKmh = _checked;
                }
                else if (item == speedMph)
                {
                    ShowSpeedoMph = _checked;
                }
                else if (item == coords)
                {
                    ShowCoordinates = _checked;
                }
                else if (item == hideHud)
                {
                    HideHud = _checked;
                    DisplayHud(!_checked);
                }
                else if (item == hideRadar)
                {
                    HideRadar = _checked;
                    if (!_checked)
                    {
                        DisplayRadar(true);
                    }
                }
                else if (item == showLocation)
                {
                    ShowLocation = _checked;
                }
                else if (item == drawTime)
                {
                    DrawTimeOnScreen = _checked;
                }
                else if (item == deathNotifs)
                {
                    DeathNotifications = _checked;
                }
                else if (item == joinQuitNotifs)
                {
                    JoinQuitNotifications = _checked;
                }
                else if (item == nightVision)
                {
                    SetNightvision(_checked);
                }
                else if (item == thermalVision)
                {
                    SetSeethrough(_checked);
                }
                else if (item == lockCamX)
                {
                    LockCameraX = _checked;
                }
                else if (item == lockCamY)
                {
                    LockCameraY = _checked;
                }
                else if (item == locationBlips)
                {
                    ToggleBlips(_checked);
                    ShowLocationBlips = _checked;
                }
                else if (item == playerBlips)
                {
                    ShowPlayerBlips = _checked;
                }
                else if (item == respawnDefaultCharacter)
                {
                    MiscRespawnDefaultCharacter = _checked;
                }
                else if (item == restorePlayerAppearance)
                {
                    RestorePlayerAppearance = _checked;
                }
                else if (item == restorePlayerWeapons)
                {
                    RestorePlayerWeapons = _checked;
                }
                else if (item == modelDimensions)
                {
                    ShowVehicleModelDimensions = _checked;
                }
            };

            // Handle button presses.
            menu.OnItemSelect += (sender, item, index) =>
            {
                // Teleport to waypoint.
                if (item == tptowp)
                {
                    TeleportToWp();
                }
                // save settings
                else if (item == saveSettings)
                {
                    UserDefaults.SaveSettings();
                }
                // clear area
                else if (item == clearArea)
                {
                    var pos = Game.PlayerPed.Position;
                    BaseScript.TriggerServerEvent("vMenu:ClearArea", pos.X, pos.Y, pos.Z);
                }
            };
        }
示例#10
0
        /// <summary>
        /// Creates the menu.
        /// </summary>
        private void CreateMenu()
        {
            MenuController.MenuAlignment = MiscRightAlignMenu ? MenuController.MenuAlignmentOption.Right : MenuController.MenuAlignmentOption.Left;
            if (MenuController.MenuAlignment != (MiscRightAlignMenu ? MenuController.MenuAlignmentOption.Right : MenuController.MenuAlignmentOption.Left))
            {
                Notify.Error(CommonErrors.RightAlignedNotSupported);

                // (re)set the default to left just in case so they don't get this error again in the future.
                MenuController.MenuAlignment    = MenuController.MenuAlignmentOption.Left;
                MiscRightAlignMenu              = false;
                UserDefaults.MiscRightAlignMenu = false;
            }

            // Create the menu.
            menu = new Menu(Game.Player.Name, "其它設定選單");
            teleportOptionsMenu = new Menu(Game.Player.Name, "瞬移設定");
            developerToolsMenu  = new Menu(Game.Player.Name, "開發者工具");

            // teleport menu
            Menu     teleportMenu    = new Menu(Game.Player.Name, "傳送地點");
            MenuItem teleportMenuBtn = new MenuItem("傳送地點", "傳送到伺服器添加的預配位置");

            MenuController.AddSubmenu(menu, teleportMenu);
            MenuController.BindMenuItem(menu, teleportMenu, teleportMenuBtn);

            // keybind settings menu
            Menu     keybindMenu    = new Menu(Game.Player.Name, "按鍵設定");
            MenuItem keybindMenuBtn = new MenuItem("按鍵設定", "開啟或關閉鍵盤綁定");

            MenuController.AddSubmenu(menu, keybindMenu);
            MenuController.BindMenuItem(menu, keybindMenu, keybindMenuBtn);

            // keybind settings menu items
            MenuCheckboxItem kbTpToWaypoint      = new MenuCheckboxItem("傳送到導航點", "", KbTpToWaypoint);
            MenuCheckboxItem kbDriftMode         = new MenuCheckboxItem("飄移模式", "按住鍵盤上的左移或者搖趕上的X鍵,能使車輛甩尾.", KbDriftMode);
            MenuCheckboxItem kbRecordKeys        = new MenuCheckboxItem("錄影控制", "開啟或關閉用鍵盤和搖桿控制 (Rockstar 編輯器) 熱鍵.", KbRecordKeys);
            MenuCheckboxItem kbRadarKeys         = new MenuCheckboxItem("小地圖控件", "按鍵盤上的z,控制器上的向下箭頭鍵在擴展雷達和普通雷達之間切換.", KbRadarKeys);
            MenuCheckboxItem kbPointKeysCheckbox = new MenuCheckboxItem("手指點控件", "", KbPointKeys);
            MenuItem         backBtn             = new MenuItem("返回");

            // Create the menu items.
            MenuCheckboxItem rightAlignMenu       = new MenuCheckboxItem("像右對齊選單", "", MiscRightAlignMenu);
            MenuCheckboxItem disablePms           = new MenuCheckboxItem("禁用私人訊息", "阻止其它人通過 '線上模式'選單像您發送私人訊息.", MiscDisablePrivateMessages);
            MenuCheckboxItem disableControllerKey = new MenuCheckboxItem("禁止控制器選單", "這將禁用控制器選單切換鍵不會禁用導航按鈕.", MiscDisableControllerSupport);
            MenuCheckboxItem speedKmh             = new MenuCheckboxItem("顯示儀表板KM/H", "視窗上顯示一個計速器,以KM/h為單位顯示速度", ShowSpeedoKmh);
            MenuCheckboxItem speedMph             = new MenuCheckboxItem("顯示速度MPH", "視窗上顯示一個計速器,以MPH為單位顯示速度", ShowSpeedoMph);
            MenuCheckboxItem coords       = new MenuCheckboxItem("顯示坐標", "視窗頂部顯示當前座標.", ShowCoordinates);
            MenuCheckboxItem hideRadar    = new MenuCheckboxItem("隱藏雷達", "隱藏雷達/小地圖", HideRadar);
            MenuCheckboxItem hideHud      = new MenuCheckboxItem("隱藏 Hud", "隱藏所有HUD元素.", HideHud);
            MenuCheckboxItem showLocation = new MenuCheckboxItem("位置顯示", "顯示您當前的位置和方向,以最近的交叉路口類似PLD. ~r~警告: 可能會降低FPS", ShowLocation)
            {
                LeftIcon = MenuItem.Icon.WARNING
            };
            MenuCheckboxItem drawTime     = new MenuCheckboxItem("顯示時間", "在視窗上顯示當前遊戲時間.", DrawTimeOnScreen);
            MenuItem         saveSettings = new MenuItem("保存個人設置", "保存當前設置。 所有保存都在客戶端完成,如果重新安裝Windows,則會丟失設置。 使用vMenu在所有服務器之間共享設置.")
            {
                RightIcon = MenuItem.Icon.TICK
            };
            MenuCheckboxItem joinQuitNotifs           = new MenuCheckboxItem("加入/離開通知", "有人加入或者離開伺服器都會收到通知.", JoinQuitNotifications);
            MenuCheckboxItem deathNotifs              = new MenuCheckboxItem("死亡通知", "有人死亡或者被殺都會收到通知.", DeathNotifications);
            MenuCheckboxItem nightVision              = new MenuCheckboxItem("開關夜視鏡", "開啟或關閉夜視鏡功能.", false);
            MenuCheckboxItem thermalVision            = new MenuCheckboxItem("開關熱感應", "開啟或關閉熱感應功能.", false);
            MenuCheckboxItem vehModelDimensions       = new MenuCheckboxItem("顯示載具尺寸", "當前靠近您的每輛載具都會有模型輪廓", ShowVehicleModelDimensions);
            MenuCheckboxItem propModelDimensions      = new MenuCheckboxItem("顯示道具尺寸", "當前靠近您的每個武器都會有道具輪廓", ShowPropModelDimensions);
            MenuCheckboxItem pedModelDimensions       = new MenuCheckboxItem("顯示人物尺寸", "當前靠近您的每個人都會有人物輪廓.", ShowPedModelDimensions);
            MenuCheckboxItem showEntityHandles        = new MenuCheckboxItem("顯示實體句炳", "繪製所有關閉實體的句炳 (必須啟用上面的功能,該功能才會有用).", ShowEntityHandles);
            MenuCheckboxItem showEntityModels         = new MenuCheckboxItem("顯示實體模型", "繪製所有閉合實體的模型(必須啟用上面的功能,該功能才會有用).", ShowEntityModels);
            MenuSliderItem   dimensionsDistanceSlider = new MenuSliderItem("顯示尺寸半徑", "顯示實體模型/手柄/尺寸繪製範圍.", 0, 20, 20, false);

            MenuItem         clearArea = new MenuItem("清空地區", "清除你周圍區域(100米)所有物件除了人");
            MenuCheckboxItem lockCamX  = new MenuCheckboxItem("鎖定相機水平翻轉", "鎖定相機水平翻轉.", false);
            MenuCheckboxItem lockCamY  = new MenuCheckboxItem("鎖定相機垂直翻轉", "鎖定相機垂直翻轉.", false);


            Menu     connectionSubmenu    = new Menu(Game.Player.Name, "連線選項");
            MenuItem connectionSubmenuBtn = new MenuItem("連線選項", "伺服器連接/遊戲退出選項");

            MenuItem quitSession          = new MenuItem("退出連線", "");
            MenuItem rejoinSession        = new MenuItem("重新加入連線", "");
            MenuItem quitGame             = new MenuItem("退出遊戲", "五秒後退出遊戲");
            MenuItem disconnectFromServer = new MenuItem("與伺服器段開連接", "");

            connectionSubmenu.AddMenuItem(quitSession);
            connectionSubmenu.AddMenuItem(rejoinSession);
            connectionSubmenu.AddMenuItem(quitGame);
            connectionSubmenu.AddMenuItem(disconnectFromServer);

            MenuCheckboxItem enableTimeCycle            = new MenuCheckboxItem("Enable Timecycle Modifier", "Enable or disable the timecycle modifier from the list below.", TimecycleEnabled);
            List <string>    timeCycleModifiersListData = TimeCycles.Timecycles.ToList();

            for (var i = 0; i < timeCycleModifiersListData.Count; i++)
            {
                timeCycleModifiersListData[i] += $" ({i + 1}/{timeCycleModifiersListData.Count})";
            }
            MenuListItem   timeCycles         = new MenuListItem("TM", timeCycleModifiersListData, MathUtil.Clamp(LastTimeCycleModifierIndex, 0, Math.Max(0, timeCycleModifiersListData.Count - 1)), "選擇一個倒數計時啟用上面的複選框.");
            MenuSliderItem timeCycleIntensity = new MenuSliderItem("時間週期修改器強度", "設置時間週期修改器強度.", 0, 20, LastTimeCycleModifierStrength, true);

            MenuCheckboxItem locationBlips           = new MenuCheckboxItem("位置提示", "在地圖上顯示位置提示.", ShowLocationBlips);
            MenuCheckboxItem playerBlips             = new MenuCheckboxItem("顯示玩家提示", "在地圖上顯示玩家提示.", ShowPlayerBlips);
            MenuCheckboxItem playerNames             = new MenuCheckboxItem("顯示玩家名字", "開啟或關閉玩家名字", MiscShowOverheadNames);
            MenuCheckboxItem respawnDefaultCharacter = new MenuCheckboxItem("重新生成為預設創建", "", MiscRespawnDefaultCharacter);
            MenuCheckboxItem restorePlayerAppearance = new MenuCheckboxItem("恢復玩家外觀", "死亡重生時恢復玩家的皮膚,重新加速伺服器時將不會恢復您以前的造型.", RestorePlayerAppearance);
            MenuCheckboxItem restorePlayerWeapons    = new MenuCheckboxItem("恢復玩家武器", "死亡重生時恢復玩家的武器,重新加速伺服器時將不會恢復您以前的武器.", RestorePlayerWeapons);

            MenuController.AddSubmenu(menu, connectionSubmenu);
            MenuController.BindMenuItem(menu, connectionSubmenu, connectionSubmenuBtn);

            keybindMenu.OnCheckboxChange += (sender, item, index, _checked) =>
            {
                if (item == kbTpToWaypoint)
                {
                    KbTpToWaypoint = _checked;
                }
                else if (item == kbDriftMode)
                {
                    KbDriftMode = _checked;
                }
                else if (item == kbRecordKeys)
                {
                    KbRecordKeys = _checked;
                }
                else if (item == kbRadarKeys)
                {
                    KbRadarKeys = _checked;
                }
                else if (item == kbPointKeysCheckbox)
                {
                    KbPointKeys = _checked;
                }
            };
            keybindMenu.OnItemSelect += (sender, item, index) =>
            {
                if (item == backBtn)
                {
                    keybindMenu.GoBack();
                }
            };

            connectionSubmenu.OnItemSelect += (sender, item, index) =>
            {
                if (item == quitGame)
                {
                    QuitGame();
                }
                else if (item == quitSession)
                {
                    if (NetworkIsSessionActive())
                    {
                        if (NetworkIsHost())
                        {
                            Notify.Error("抱歉,您不能在主持人後退出戰局。 這將阻止其他玩家加入/停留在服務器上。");
                        }
                        else
                        {
                            QuitSession();
                        }
                    }
                    else
                    {
                        Notify.Error("您目前沒有參加任何戰局.");
                    }
                }
                else if (item == rejoinSession)
                {
                    if (NetworkIsSessionActive())
                    {
                        Notify.Error("您已經連接到戰局.");
                    }
                    else
                    {
                        Notify.Info("嘗試重新加入戰局.");
                        NetworkSessionHost(-1, 32, false);
                    }
                }
                else if (item == disconnectFromServer)
                {
                    RegisterCommand("disconnect", new Action <dynamic, dynamic, dynamic>((a, b, c) => { }), false);
                    ExecuteCommand("disconnect");
                }
            };

            // Teleportation options
            if (IsAllowed(Permission.MSTeleportToWp) || IsAllowed(Permission.MSTeleportLocations) || IsAllowed(Permission.MSTeleportToCoord))
            {
                MenuItem teleportOptionsMenuBtn = new MenuItem("傳送選項", "各種傳送選擇.")
                {
                    Label = "→→→"
                };
                menu.AddMenuItem(teleportOptionsMenuBtn);
                MenuController.BindMenuItem(menu, teleportOptionsMenu, teleportOptionsMenuBtn);

                MenuItem tptowp          = new MenuItem("傳送到導航點", "傳送到地圖上的導航點");
                MenuItem tpToCoord       = new MenuItem("傳送到座標", "輸入 x, y, z 座標 您將被傳誦到該位置");
                MenuItem saveLocationBtn = new MenuItem("保存傳送位置", "將您當前的位置添加倒傳送位置選單中,並且保存到伺服器中");
                teleportOptionsMenu.OnItemSelect += async(sender, item, index) =>
                {
                    // Teleport to waypoint.
                    if (item == tptowp)
                    {
                        TeleportToWp();
                    }
                    else if (item == tpToCoord)
                    {
                        string x = await GetUserInput("輸入 X 座標.");

                        if (string.IsNullOrEmpty(x))
                        {
                            Notify.Error(CommonErrors.InvalidInput);
                            return;
                        }
                        string y = await GetUserInput("輸入 Y 座標.");

                        if (string.IsNullOrEmpty(y))
                        {
                            Notify.Error(CommonErrors.InvalidInput);
                            return;
                        }
                        string z = await GetUserInput("輸入 Z 座標.");

                        if (string.IsNullOrEmpty(z))
                        {
                            Notify.Error(CommonErrors.InvalidInput);
                            return;
                        }

                        float posX = 0f;
                        float posY = 0f;
                        float posZ = 0f;

                        if (!float.TryParse(x, out posX))
                        {
                            if (int.TryParse(x, out int intX))
                            {
                                posX = (float)intX;
                            }
                            else
                            {
                                Notify.Error("您輸入的不是一個有效的 X 座標.");
                                return;
                            }
                        }
                        if (!float.TryParse(y, out posY))
                        {
                            if (int.TryParse(y, out int intY))
                            {
                                posY = (float)intY;
                            }
                            else
                            {
                                Notify.Error("您輸入的不是一個有效的 Y 座標.");
                                return;
                            }
                        }
                        if (!float.TryParse(z, out posZ))
                        {
                            if (int.TryParse(z, out int intZ))
                            {
                                posZ = (float)intZ;
                            }
                            else
                            {
                                Notify.Error("您輸入的不是一個有效的 Z 座標.");
                                return;
                            }
                        }

                        await TeleportToCoords(new Vector3(posX, posY, posZ), true);
                    }
                    else if (item == saveLocationBtn)
                    {
                        SavePlayerLocationToLocationsFile();
                    }
                };

                if (IsAllowed(Permission.MSTeleportToWp))
                {
                    teleportOptionsMenu.AddMenuItem(tptowp);
                    keybindMenu.AddMenuItem(kbTpToWaypoint);
                }
                if (IsAllowed(Permission.MSTeleportToCoord))
                {
                    teleportOptionsMenu.AddMenuItem(tpToCoord);
                }
                if (IsAllowed(Permission.MSTeleportLocations))
                {
                    teleportOptionsMenu.AddMenuItem(teleportMenuBtn);

                    MenuController.AddSubmenu(teleportOptionsMenu, teleportMenu);
                    MenuController.BindMenuItem(teleportOptionsMenu, teleportMenu, teleportMenuBtn);
                    teleportMenuBtn.Label = "→→→";

                    teleportMenu.OnMenuOpen += (sender) =>
                    {
                        if (teleportMenu.Size != TpLocations.Count())
                        {
                            teleportMenu.ClearMenuItems();
                            foreach (var location in TpLocations)
                            {
                                var      x       = Math.Round(location.coordinates.X, 2);
                                var      y       = Math.Round(location.coordinates.Y, 2);
                                var      z       = Math.Round(location.coordinates.Z, 2);
                                var      heading = Math.Round(location.heading, 2);
                                MenuItem tpBtn   = new MenuItem(location.name, $"已經傳送到 ~y~{location.name}~n~~s~x: ~y~{x}~n~~s~y: ~y~{y}~n~~s~z: ~y~{z}~n~~s~heading: ~y~{heading}")
                                {
                                    ItemData = location
                                };
                                teleportMenu.AddMenuItem(tpBtn);
                            }
                        }
                    };

                    teleportMenu.OnItemSelect += async(sender, item, index) =>
                    {
                        if (item.ItemData is vMenuShared.ConfigManager.TeleportLocation tl)
                        {
                            await TeleportToCoords(tl.coordinates, true);

                            SetEntityHeading(Game.PlayerPed.Handle, tl.heading);
                            SetGameplayCamRelativeHeading(0f);
                        }
                    };

                    if (IsAllowed(Permission.MSTeleportSaveLocation))
                    {
                        teleportOptionsMenu.AddMenuItem(saveLocationBtn);
                    }
                }
            }

            #region dev tools menu

            MenuItem devToolsBtn = new MenuItem("開發者選項", "各種開發/調試工具.")
            {
                Label = "→→→"
            };
            menu.AddMenuItem(devToolsBtn);
            MenuController.AddSubmenu(menu, developerToolsMenu);
            MenuController.BindMenuItem(menu, developerToolsMenu, devToolsBtn);

            // clear area and coordinates
            if (IsAllowed(Permission.MSClearArea))
            {
                developerToolsMenu.AddMenuItem(clearArea);
            }
            if (IsAllowed(Permission.MSShowCoordinates))
            {
                developerToolsMenu.AddMenuItem(coords);
            }

            // model outlines
            if (!vMenuShared.ConfigManager.GetSettingsBool(vMenuShared.ConfigManager.Setting.vmenu_disable_entity_outlines_tool))
            {
                developerToolsMenu.AddMenuItem(vehModelDimensions);
                developerToolsMenu.AddMenuItem(propModelDimensions);
                developerToolsMenu.AddMenuItem(pedModelDimensions);
                developerToolsMenu.AddMenuItem(showEntityHandles);
                developerToolsMenu.AddMenuItem(showEntityModels);
                developerToolsMenu.AddMenuItem(dimensionsDistanceSlider);
            }


            // timecycle modifiers
            developerToolsMenu.AddMenuItem(timeCycles);
            developerToolsMenu.AddMenuItem(enableTimeCycle);
            developerToolsMenu.AddMenuItem(timeCycleIntensity);

            developerToolsMenu.OnSliderPositionChange += (sender, item, oldPos, newPos, itemIndex) =>
            {
                if (item == timeCycleIntensity)
                {
                    ClearTimecycleModifier();
                    if (TimecycleEnabled)
                    {
                        SetTimecycleModifier(TimeCycles.Timecycles[timeCycles.ListIndex]);
                        float intensity = ((float)newPos / 20f);
                        SetTimecycleModifierStrength(intensity);
                    }
                    UserDefaults.MiscLastTimeCycleModifierIndex    = timeCycles.ListIndex;
                    UserDefaults.MiscLastTimeCycleModifierStrength = timeCycleIntensity.Position;
                }
                else if (item == dimensionsDistanceSlider)
                {
                    FunctionsController.entityRange = ((float)newPos / 20f) * 2000f; // max radius = 2000f;
                }
            };

            developerToolsMenu.OnListIndexChange += (sender, item, oldIndex, newIndex, itemIndex) =>
            {
                if (item == timeCycles)
                {
                    ClearTimecycleModifier();
                    if (TimecycleEnabled)
                    {
                        SetTimecycleModifier(TimeCycles.Timecycles[timeCycles.ListIndex]);
                        float intensity = ((float)timeCycleIntensity.Position / 20f);
                        SetTimecycleModifierStrength(intensity);
                    }
                    UserDefaults.MiscLastTimeCycleModifierIndex    = timeCycles.ListIndex;
                    UserDefaults.MiscLastTimeCycleModifierStrength = timeCycleIntensity.Position;
                }
            };

            developerToolsMenu.OnItemSelect += (sender, item, index) =>
            {
                if (item == clearArea)
                {
                    var pos = Game.PlayerPed.Position;
                    BaseScript.TriggerServerEvent("vMenu:ClearArea", pos.X, pos.Y, pos.Z);
                }
            };

            developerToolsMenu.OnCheckboxChange += (sender, item, index, _checked) =>
            {
                if (item == vehModelDimensions)
                {
                    ShowVehicleModelDimensions = _checked;
                }
                else if (item == propModelDimensions)
                {
                    ShowPropModelDimensions = _checked;
                }
                else if (item == pedModelDimensions)
                {
                    ShowPedModelDimensions = _checked;
                }
                else if (item == showEntityHandles)
                {
                    ShowEntityHandles = _checked;
                }
                else if (item == showEntityModels)
                {
                    ShowEntityModels = _checked;
                }
                else if (item == enableTimeCycle)
                {
                    TimecycleEnabled = _checked;
                    ClearTimecycleModifier();
                    if (TimecycleEnabled)
                    {
                        SetTimecycleModifier(TimeCycles.Timecycles[timeCycles.ListIndex]);
                        float intensity = ((float)timeCycleIntensity.Position / 20f);
                        SetTimecycleModifierStrength(intensity);
                    }
                }
                else if (item == coords)
                {
                    ShowCoordinates = _checked;
                }
            };

            #endregion


            // Keybind options
            if (IsAllowed(Permission.MSDriftMode))
            {
                keybindMenu.AddMenuItem(kbDriftMode);
            }
            // always allowed keybind menu options
            keybindMenu.AddMenuItem(kbRecordKeys);
            keybindMenu.AddMenuItem(kbRadarKeys);
            keybindMenu.AddMenuItem(kbPointKeysCheckbox);
            keybindMenu.AddMenuItem(backBtn);

            // Always allowed
            menu.AddMenuItem(rightAlignMenu);
            menu.AddMenuItem(disablePms);
            menu.AddMenuItem(disableControllerKey);
            menu.AddMenuItem(speedKmh);
            menu.AddMenuItem(speedMph);
            menu.AddMenuItem(keybindMenuBtn);
            keybindMenuBtn.Label = "→→→";
            if (IsAllowed(Permission.MSConnectionMenu))
            {
                menu.AddMenuItem(connectionSubmenuBtn);
                connectionSubmenuBtn.Label = "→→→";
            }
            if (IsAllowed(Permission.MSShowLocation))
            {
                menu.AddMenuItem(showLocation);
            }
            menu.AddMenuItem(drawTime); // always allowed
            if (IsAllowed(Permission.MSJoinQuitNotifs))
            {
                menu.AddMenuItem(deathNotifs);
            }
            if (IsAllowed(Permission.MSDeathNotifs))
            {
                menu.AddMenuItem(joinQuitNotifs);
            }
            if (IsAllowed(Permission.MSNightVision))
            {
                menu.AddMenuItem(nightVision);
            }
            if (IsAllowed(Permission.MSThermalVision))
            {
                menu.AddMenuItem(thermalVision);
            }
            if (IsAllowed(Permission.MSLocationBlips))
            {
                menu.AddMenuItem(locationBlips);
                ToggleBlips(ShowLocationBlips);
            }
            if (IsAllowed(Permission.MSPlayerBlips))
            {
                menu.AddMenuItem(playerBlips);
            }
            if (IsAllowed(Permission.MSOverheadNames))
            {
                menu.AddMenuItem(playerNames);
            }
            // always allowed, it just won't do anything if the server owner disabled the feature, but players can still toggle it.
            menu.AddMenuItem(respawnDefaultCharacter);
            if (IsAllowed(Permission.MSRestoreAppearance))
            {
                menu.AddMenuItem(restorePlayerAppearance);
            }
            if (IsAllowed(Permission.MSRestoreWeapons))
            {
                menu.AddMenuItem(restorePlayerWeapons);
            }

            // Always allowed
            menu.AddMenuItem(hideRadar);
            menu.AddMenuItem(hideHud);
            menu.AddMenuItem(lockCamX);
            menu.AddMenuItem(lockCamY);
            menu.AddMenuItem(saveSettings);

            // Handle checkbox changes.
            menu.OnCheckboxChange += (sender, item, index, _checked) =>
            {
                if (item == rightAlignMenu)
                {
                    MenuController.MenuAlignment    = _checked ? MenuController.MenuAlignmentOption.Right : MenuController.MenuAlignmentOption.Left;
                    MiscRightAlignMenu              = _checked;
                    UserDefaults.MiscRightAlignMenu = MiscRightAlignMenu;

                    if (MenuController.MenuAlignment != (_checked ? MenuController.MenuAlignmentOption.Right : MenuController.MenuAlignmentOption.Left))
                    {
                        Notify.Error(CommonErrors.RightAlignedNotSupported);
                        // (re)set the default to left just in case so they don't get this error again in the future.
                        MenuController.MenuAlignment    = MenuController.MenuAlignmentOption.Left;
                        MiscRightAlignMenu              = false;
                        UserDefaults.MiscRightAlignMenu = false;
                    }
                }
                else if (item == disablePms)
                {
                    MiscDisablePrivateMessages = _checked;
                }
                else if (item == disableControllerKey)
                {
                    MiscDisableControllerSupport = _checked;
                    MenuController.EnableMenuToggleKeyOnController = !_checked;
                }
                else if (item == speedKmh)
                {
                    ShowSpeedoKmh = _checked;
                }
                else if (item == speedMph)
                {
                    ShowSpeedoMph = _checked;
                }
                else if (item == hideHud)
                {
                    HideHud = _checked;
                    DisplayHud(!_checked);
                }
                else if (item == hideRadar)
                {
                    HideRadar = _checked;
                    if (!_checked)
                    {
                        DisplayRadar(true);
                    }
                }
                else if (item == showLocation)
                {
                    ShowLocation = _checked;
                }
                else if (item == drawTime)
                {
                    DrawTimeOnScreen = _checked;
                }
                else if (item == deathNotifs)
                {
                    DeathNotifications = _checked;
                }
                else if (item == joinQuitNotifs)
                {
                    JoinQuitNotifications = _checked;
                }
                else if (item == nightVision)
                {
                    SetNightvision(_checked);
                }
                else if (item == thermalVision)
                {
                    SetSeethrough(_checked);
                }
                else if (item == lockCamX)
                {
                    LockCameraX = _checked;
                }
                else if (item == lockCamY)
                {
                    LockCameraY = _checked;
                }
                else if (item == locationBlips)
                {
                    ToggleBlips(_checked);
                    ShowLocationBlips = _checked;
                }
                else if (item == playerBlips)
                {
                    ShowPlayerBlips = _checked;
                }
                else if (item == playerNames)
                {
                    MiscShowOverheadNames = _checked;
                }
                else if (item == respawnDefaultCharacter)
                {
                    MiscRespawnDefaultCharacter = _checked;
                }
                else if (item == restorePlayerAppearance)
                {
                    RestorePlayerAppearance = _checked;
                }
                else if (item == restorePlayerWeapons)
                {
                    RestorePlayerWeapons = _checked;
                }
            };

            // Handle button presses.
            menu.OnItemSelect += (sender, item, index) =>
            {
                // save settings
                if (item == saveSettings)
                {
                    UserDefaults.SaveSettings();
                }
            };
        }
示例#11
0
        /// <summary>
        /// Creates the menu.
        /// </summary>
        private void CreateMenu()
        {
            // Create the menu.
            menu = new Menu(Game.Player.Name, LM.Get("Online Players"))
            {
            };
            menu.CounterPreText = LM.Get("Players: ");

            MenuController.AddSubmenu(menu, playerMenu);

            MenuItem sendMessage      = new MenuItem(LM.Get("Send Private Message"), LM.Get("Sends a private message to this player. ~r~Note: staff may be able to see all PM's."));
            MenuItem teleport         = new MenuItem(LM.Get("Teleport To Player"), LM.Get("Teleport to this player."));
            MenuItem teleportVeh      = new MenuItem(LM.Get("Teleport Into Player Vehicle"), LM.Get("Teleport into the vehicle of the player."));
            MenuItem summon           = new MenuItem(LM.Get("Summon Player"), LM.Get("Teleport the player to you."));
            MenuItem toggleGPS        = new MenuItem(LM.Get("Toggle GPS"), LM.Get("Enables or disables the GPS route on your radar to this player."));
            MenuItem spectate         = new MenuItem(LM.Get("Spectate Player"), LM.Get("Spectate this player. Click this button again to stop spectating."));
            MenuItem printIdentifiers = new MenuItem(LM.Get("Print Identifiers"), LM.Get("This will print the player's identifiers to the client console (F8). And also save it to the CitizenFX.log file."));
            MenuItem kill             = new MenuItem(LM.Get("~r~Kill Player"), LM.Get("Kill this player, note they will receive a notification saying that you killed them. It will also be logged in the Staff Actions log."));
            MenuItem kick             = new MenuItem(LM.Get("~r~Kick Player"), LM.Get("Kick the player from the server."));
            MenuItem ban     = new MenuItem(LM.Get("~r~Ban Player Permanently"), LM.Get("Ban this player permanently from the server. Are you sure you want to do this? You can specify the ban reason after clicking this button."));
            MenuItem tempban = new MenuItem(LM.Get("~r~Ban Player Temporarily"), LM.Get("Give this player a tempban of up to 30 days (max). You can specify duration and ban reason after clicking this button."));

            // always allowed
            playerMenu.AddMenuItem(sendMessage);
            // permissions specific
            if (IsAllowed(Permission.OPTeleport))
            {
                playerMenu.AddMenuItem(teleport);
                playerMenu.AddMenuItem(teleportVeh);
            }
            if (IsAllowed(Permission.OPSummon))
            {
                playerMenu.AddMenuItem(summon);
            }
            if (IsAllowed(Permission.OPSpectate))
            {
                playerMenu.AddMenuItem(spectate);
            }
            if (IsAllowed(Permission.OPWaypoint))
            {
                playerMenu.AddMenuItem(toggleGPS);
            }
            if (IsAllowed(Permission.OPIdentifiers))
            {
                playerMenu.AddMenuItem(printIdentifiers);
            }
            if (IsAllowed(Permission.OPKill))
            {
                playerMenu.AddMenuItem(kill);
            }
            if (IsAllowed(Permission.OPKick))
            {
                playerMenu.AddMenuItem(kick);
            }
            if (IsAllowed(Permission.OPTempBan))
            {
                playerMenu.AddMenuItem(tempban);
            }
            if (IsAllowed(Permission.OPPermBan))
            {
                playerMenu.AddMenuItem(ban);
                ban.LeftIcon = MenuItem.Icon.WARNING;
            }

            playerMenu.OnMenuClose += (sender) =>
            {
                playerMenu.RefreshIndex();
                ban.Label = "";
            };

            playerMenu.OnIndexChange += (sender, oldItem, newItem, oldIndex, newIndex) =>
            {
                ban.Label = "";
            };

            // handle button presses for the specific player's menu.
            playerMenu.OnItemSelect += async(sender, item, index) =>
            {
                // send message
                if (item == sendMessage)
                {
                    if (MainMenu.MiscSettingsMenu != null && !MainMenu.MiscSettingsMenu.MiscDisablePrivateMessages)
                    {
                        string message = await GetUserInput($"Private Message To {currentPlayer.Name}", 200);

                        if (string.IsNullOrEmpty(message))
                        {
                            Notify.Error(CommonErrors.InvalidInput);
                        }
                        else
                        {
                            TriggerServerEvent("vMenu:SendMessageToPlayer", currentPlayer.ServerId, message);
                            PrivateMessage(currentPlayer.ServerId.ToString(), message, true);
                        }
                    }
                    else
                    {
                        Notify.Error(LM.Get("You can't send a private message if you have private messages disabled yourself. Enable them in the Misc Settings menu and try again."));
                    }
                }
                // teleport (in vehicle) button
                else if (item == teleport || item == teleportVeh)
                {
                    if (Game.Player.Handle != currentPlayer.Handle)
                    {
                        TeleportToPlayer(currentPlayer.Handle, item == teleportVeh); // teleport to the player. optionally in the player's vehicle if that button was pressed.
                    }
                    else
                    {
                        Notify.Error(LM.Get("You can not teleport to yourself!"));
                    }
                }
                // summon button
                else if (item == summon)
                {
                    if (Game.Player.Handle != currentPlayer.Handle)
                    {
                        SummonPlayer(currentPlayer);
                    }
                    else
                    {
                        Notify.Error(LM.Get("You can't summon yourself."));
                    }
                }
                // spectating
                else if (item == spectate)
                {
                    SpectatePlayer(currentPlayer);
                }
                // kill button
                else if (item == kill)
                {
                    KillPlayer(currentPlayer);
                }
                // manage the gps route being clicked.
                else if (item == toggleGPS)
                {
                    bool selectedPedRouteAlreadyActive = false;
                    if (PlayersWaypointList.Count > 0)
                    {
                        if (PlayersWaypointList.Contains(currentPlayer.Handle))
                        {
                            selectedPedRouteAlreadyActive = true;
                        }
                        foreach (int playerId in PlayersWaypointList)
                        {
                            int playerPed = GetPlayerPed(playerId);
                            if (DoesEntityExist(playerPed) && DoesBlipExist(GetBlipFromEntity(playerPed)))
                            {
                                int oldBlip = GetBlipFromEntity(playerPed);
                                SetBlipRoute(oldBlip, false);
                                RemoveBlip(ref oldBlip);
                                Notify.Custom($"~g~GPS route to ~s~<C>{GetSafePlayerName(currentPlayer.Name)}</C>~g~ is now disabled.");
                            }
                        }
                        PlayersWaypointList.Clear();
                    }

                    if (!selectedPedRouteAlreadyActive)
                    {
                        if (currentPlayer.Handle != Game.Player.Handle)
                        {
                            int ped  = GetPlayerPed(currentPlayer.Handle);
                            int blip = GetBlipFromEntity(ped);
                            if (DoesBlipExist(blip))
                            {
                                SetBlipColour(blip, 58);
                                SetBlipRouteColour(blip, 58);
                                SetBlipRoute(blip, true);
                            }
                            else
                            {
                                blip = AddBlipForEntity(ped);
                                SetBlipColour(blip, 58);
                                SetBlipRouteColour(blip, 58);
                                SetBlipRoute(blip, true);
                            }
                            PlayersWaypointList.Add(currentPlayer.Handle);
                            Notify.Custom($"~g~GPS route to ~s~<C>{GetSafePlayerName(currentPlayer.Name)}</C>~g~ is now active, press the ~s~Toggle GPS Route~g~ button again to disable the route.");
                        }
                        else
                        {
                            Notify.Error(LM.Get("You can not set a waypoint to yourself."));
                        }
                    }
                }
                else if (item == printIdentifiers)
                {
                    Func <string, string> CallbackFunction = (data) =>
                    {
                        Debug.WriteLine(data);
                        string ids = "~s~";
                        foreach (string s in JsonConvert.DeserializeObject <string[]>(data))
                        {
                            ids += "~n~" + s;
                        }
                        Notify.Custom($"~y~<C>{GetSafePlayerName(currentPlayer.Name)}</C>~g~'s Identifiers: {ids}", false);
                        return(data);
                    };
                    BaseScript.TriggerServerEvent("vMenu:GetPlayerIdentifiers", currentPlayer.ServerId, CallbackFunction);
                }
                // kick button
                else if (item == kick)
                {
                    if (currentPlayer.Handle != Game.Player.Handle)
                    {
                        KickPlayer(currentPlayer, true);
                    }
                    else
                    {
                        Notify.Error(LM.Get("You cannot kick yourself!"));
                    }
                }
                // temp ban
                else if (item == tempban)
                {
                    BanPlayer(currentPlayer, false);
                }
                // perm ban
                else if (item == ban)
                {
                    if (ban.Label == LM.Get("Are you sure?"))
                    {
                        ban.Label = "";
                        UpdatePlayerlist();
                        playerMenu.GoBack();
                        BanPlayer(currentPlayer, true);
                    }
                    else
                    {
                        ban.Label = LM.Get("Are you sure?");
                    }
                }
            };

            // handle button presses in the player list.
            menu.OnItemSelect += (sender, item, index) =>
            {
                if (MainMenu.PlayersList.ToList().Any(p => p.ServerId.ToString() == item.Label.Replace(" →→→", "").Replace("Server #", "")))
                {
                    currentPlayer             = MainMenu.PlayersList.ToList().Find(p => p.ServerId.ToString() == item.Label.Replace(" →→→", "").Replace("Server #", ""));
                    playerMenu.MenuSubtitle   = $"~s~Player: ~y~{GetSafePlayerName(currentPlayer.Name)}";
                    playerMenu.CounterPreText = $"[Server ID: ~y~{currentPlayer.ServerId}~s~] ";
                }
                else
                {
                    playerMenu.GoBack();
                }
            };
        }
示例#12
0
        /// <summary>
        /// Creates the menu.
        /// </summary>
        private void CreateMenu()
        {
            string menuTitle = "YDDY:RP";

            #region Create menus and submenus
            // Create the menu.
            menu = new Menu(menuTitle, "Меню сохраненных автомобилей");

            MenuItem saveVehicle = new MenuItem("Сохранить текущий автомобиль", "");
            menu.AddMenuItem(saveVehicle);
            saveVehicle.LeftIcon = MenuItem.Icon.CAR;

            menu.OnItemSelect += (sender, item, index) =>
            {
                if (item == saveVehicle)
                {
                    if (Game.PlayerPed.IsInVehicle())
                    {
                        SaveVehicle();
                    }
                    else
                    {
                        Notify.Error("You are currently not in any vehicle. Please enter a vehicle before trying to save it.");
                    }
                }
            };


            for (int i = 0; i < 22; i++)
            {
                Menu categoryMenu = new Menu("Сохраненные", GetLabelText($"VEH_CLASS_{i}"));

                MenuItem categoryButton = new MenuItem(GetLabelText($"VEH_CLASS_{i}"), $"Все сохраненные автомобили категории {(GetLabelText($"VEH_CLASS_{i}"))}.");
                subMenus.Add(categoryMenu);
                MenuController.AddSubmenu(menu, categoryMenu);
                menu.AddMenuItem(categoryButton);
                categoryButton.Label = "→→→";
                MenuController.BindMenuItem(menu, categoryMenu, categoryButton);

                categoryMenu.OnMenuClose += (sender) =>
                {
                    UpdateMenuAvailableCategories();
                };

                categoryMenu.OnItemSelect += (sender, item, index) =>
                {
                    UpdateSelectedVehicleMenu(item, sender);
                };
            }

            MenuItem unavailableModels = new MenuItem("Недоступные сохраненные автомобили", "")
            {
                Label = "→→→"
            };

            menu.AddMenuItem(unavailableModels);
            MenuController.BindMenuItem(menu, unavailableVehiclesMenu, unavailableModels);
            MenuController.AddSubmenu(menu, unavailableVehiclesMenu);


            MenuController.AddMenu(selectedVehicleMenu);
            MenuItem spawnVehicle   = new MenuItem("Заспавнить", "");
            MenuItem renameVehicle  = new MenuItem("Переименовать", "");
            MenuItem replaceVehicle = new MenuItem("~r~Заменить текущим", "");
            MenuItem deleteVehicle  = new MenuItem("~r~Удалить", "");
            selectedVehicleMenu.AddMenuItem(spawnVehicle);
            selectedVehicleMenu.AddMenuItem(renameVehicle);
            selectedVehicleMenu.AddMenuItem(replaceVehicle);
            selectedVehicleMenu.AddMenuItem(deleteVehicle);

            selectedVehicleMenu.OnMenuClose += (sender) =>
            {
                selectedVehicleMenu.RefreshIndex();
                deleteButtonPressedCount = 0;
                deleteVehicle.Label      = "";
            };

            selectedVehicleMenu.OnItemSelect += async(sender, item, index) =>
            {
                if (item == spawnVehicle)
                {
                    if (MainMenu.VehicleSpawnerMenu != null)
                    {
                        SpawnVehicle(currentlySelectedVehicle.Value.model, MainMenu.VehicleSpawnerMenu.SpawnInVehicle, MainMenu.VehicleSpawnerMenu.ReplaceVehicle, false, vehicleInfo: currentlySelectedVehicle.Value, saveName: currentlySelectedVehicle.Key.Substring(4));
                    }
                    else
                    {
                        SpawnVehicle(currentlySelectedVehicle.Value.model, true, true, false, vehicleInfo: currentlySelectedVehicle.Value, saveName: currentlySelectedVehicle.Key.Substring(4));
                    }
                }
                else if (item == renameVehicle)
                {
                    string newName = await GetUserInput(windowTitle : "Enter a new name for this vehicle.", maxInputLength : 30);

                    if (string.IsNullOrEmpty(newName))
                    {
                        Notify.Error(CommonErrors.InvalidInput);
                    }
                    else
                    {
                        if (StorageManager.SaveVehicleInfo("veh_" + newName, currentlySelectedVehicle.Value, false))
                        {
                            DeleteResourceKvp(currentlySelectedVehicle.Key);
                            while (!selectedVehicleMenu.Visible)
                            {
                                await BaseScript.Delay(0);
                            }
                            Notify.Success("Your vehicle has successfully been renamed.");
                            UpdateMenuAvailableCategories();
                            selectedVehicleMenu.GoBack();
                            currentlySelectedVehicle = new KeyValuePair <string, VehicleInfo>(); // clear the old info
                        }
                        else
                        {
                            Notify.Error("This name is already in use or something unknown failed. Contact the server owner if you believe something is wrong.");
                        }
                    }
                }
                else if (item == replaceVehicle)
                {
                    if (Game.PlayerPed.IsInVehicle())
                    {
                        SaveVehicle(currentlySelectedVehicle.Key.Substring(4));
                        selectedVehicleMenu.GoBack();
                        Notify.Success("Your saved vehicle has been replaced with your current vehicle.");
                    }
                    else
                    {
                        Notify.Error("You need to be in a vehicle before you can relplace your old vehicle.");
                    }
                }
                else if (item == deleteVehicle)
                {
                    if (deleteButtonPressedCount == 0)
                    {
                        deleteButtonPressedCount = 1;
                        item.Label = "Press again to confirm.";
                        Notify.Alert("Are you sure you want to delete this vehicle? Press the button again to confirm.");
                    }
                    else
                    {
                        deleteButtonPressedCount = 0;
                        item.Label = "";
                        DeleteResourceKvp(currentlySelectedVehicle.Key);
                        UpdateMenuAvailableCategories();
                        selectedVehicleMenu.GoBack();
                        Notify.Success("Your saved vehicle has been deleted.");
                    }
                }
                if (item != deleteVehicle) // if any other button is pressed, restore the delete vehicle button pressed count.
                {
                    deleteButtonPressedCount = 0;
                    deleteVehicle.Label      = "";
                }
            };

            #endregion
        }
示例#13
0
        /// <summary>
        /// Creates the menu.
        /// </summary>
        private void CreateMenu()
        {
            #region create main weapon options menu and add items
            // Create the menu.
            menu = new Menu("YDDY:RP", "Оружие");

            MenuItem         getAllWeapons    = new MenuItem("Get All Weapons", "Get all weapons.");
            MenuItem         removeAllWeapons = new MenuItem("Убрать все оружие", "");
            MenuCheckboxItem unlimitedAmmo    = new MenuCheckboxItem("Unlimited Ammo", "Unlimited ammonition supply.", UnlimitedAmmo);
            MenuCheckboxItem noReload         = new MenuCheckboxItem("No Reload", "Never reload.", NoReload);
            MenuItem         setAmmo          = new MenuItem("Set All Ammo Count", "Set the amount of ammo in all your weapons.");
            MenuItem         refillMaxAmmo    = new MenuItem("Refill All Ammo", "Give all your weapons max ammo.");
            MenuItem         spawnByName      = new MenuItem("Spawn Weapon By Name", "Enter a weapon mode name to spawn.");

            // Add items based on permissions
            if (IsAllowed(Permission.WPGetAll))
            {
                menu.AddMenuItem(getAllWeapons);
            }
            if (IsAllowed(Permission.WPRemoveAll))
            {
                menu.AddMenuItem(removeAllWeapons);
            }
            if (IsAllowed(Permission.WPUnlimitedAmmo))
            {
                menu.AddMenuItem(unlimitedAmmo);
            }
            if (IsAllowed(Permission.WPNoReload))
            {
                menu.AddMenuItem(noReload);
            }
            if (IsAllowed(Permission.WPSetAllAmmo))
            {
                menu.AddMenuItem(setAmmo);
                menu.AddMenuItem(refillMaxAmmo);
            }
            if (IsAllowed(Permission.WPSpawnByName))
            {
                menu.AddMenuItem(spawnByName);
            }
            #endregion

            #region addonweapons submenu
            MenuItem addonWeaponsBtn  = new MenuItem("Аддоны", "");
            Menu     addonWeaponsMenu = new Menu("Аддоны", "Меню аддонов");
            menu.AddMenuItem(addonWeaponsBtn);

            #region manage creating and accessing addon weapons menu
            if (IsAllowed(Permission.WPSpawn) && AddonWeapons != null && AddonWeapons.Count > 0)
            {
                MenuController.BindMenuItem(menu, addonWeaponsMenu, addonWeaponsBtn);
                foreach (KeyValuePair <string, uint> weapon in AddonWeapons)
                {
                    string name  = weapon.Key.ToString();
                    uint   model = weapon.Value;
                    var    item  = new MenuItem(name, $"Click to add/remove this weapon ({name}) to/from your inventory.");
                    addonWeaponsMenu.AddMenuItem(item);
                    if (!IsWeaponValid(model))
                    {
                        item.Enabled     = false;
                        item.LeftIcon    = MenuItem.Icon.LOCK;
                        item.Description = "This model is not available. Please ask the server owner to verify it's being streamed correctly.";
                    }
                }
                addonWeaponsMenu.OnItemSelect += (sender, item, index) =>
                {
                    var weapon = AddonWeapons.ElementAt(index);
                    if (HasPedGotWeapon(Game.PlayerPed.Handle, weapon.Value, false))
                    {
                        RemoveWeaponFromPed(Game.PlayerPed.Handle, weapon.Value);
                    }
                    else
                    {
                        var maxAmmo = 200;
                        GetMaxAmmo(Game.PlayerPed.Handle, weapon.Value, ref maxAmmo);
                        GiveWeaponToPed(Game.PlayerPed.Handle, weapon.Value, maxAmmo, false, true);
                    }
                };
                addonWeaponsBtn.Label = "→→→";
            }
            else
            {
                addonWeaponsBtn.LeftIcon    = MenuItem.Icon.LOCK;
                addonWeaponsBtn.Enabled     = false;
                addonWeaponsBtn.Description = "This option is not available on this server because you don't have permission to use it, or it is not setup correctly.";
            }
            #endregion
            addonWeaponsMenu.RefreshIndex();
            #endregion

            #region parachute options menu

            if (IsAllowed(Permission.WPParachute))
            {
                // main parachute options menu setup
                Menu     parachuteMenu = new Menu("Парашюты", "Опции парашютов");
                MenuItem parachuteBtn  = new MenuItem("Парашюты", "")
                {
                    Label = "→→→"
                };

                MenuController.AddSubmenu(menu, parachuteMenu);
                menu.AddMenuItem(parachuteBtn);
                MenuController.BindMenuItem(menu, parachuteMenu, parachuteBtn);

                List <string> chutes = new List <string>()
                {
                    GetLabelText("PM_TINT0"),
                    GetLabelText("PM_TINT1"),
                    GetLabelText("PM_TINT2"),
                    GetLabelText("PM_TINT3"),
                    GetLabelText("PM_TINT4"),
                    GetLabelText("PM_TINT5"),
                    GetLabelText("PM_TINT6"),
                    GetLabelText("PM_TINT7"),

                    // broken in FiveM for some weird reason:
                    GetLabelText("PS_CAN_0"),
                    GetLabelText("PS_CAN_1"),
                    GetLabelText("PS_CAN_2"),
                    GetLabelText("PS_CAN_3"),
                    GetLabelText("PS_CAN_4"),
                    GetLabelText("PS_CAN_5")
                };
                List <string> chuteDescriptions = new List <string>()
                {
                    GetLabelText("PD_TINT0"),
                    GetLabelText("PD_TINT1"),
                    GetLabelText("PD_TINT2"),
                    GetLabelText("PD_TINT3"),
                    GetLabelText("PD_TINT4"),
                    GetLabelText("PD_TINT5"),
                    GetLabelText("PD_TINT6"),
                    GetLabelText("PD_TINT7"),

                    // broken in FiveM for some weird reason:
                    GetLabelText("PSD_CAN_0") + " ~r~For some reason this one doesn't seem to work in FiveM.",
                    GetLabelText("PSD_CAN_1") + " ~r~For some reason this one doesn't seem to work in FiveM.",
                    GetLabelText("PSD_CAN_2") + " ~r~For some reason this one doesn't seem to work in FiveM.",
                    GetLabelText("PSD_CAN_3") + " ~r~For some reason this one doesn't seem to work in FiveM.",
                    GetLabelText("PSD_CAN_4") + " ~r~For some reason this one doesn't seem to work in FiveM.",
                    GetLabelText("PSD_CAN_5") + " ~r~For some reason this one doesn't seem to work in FiveM."
                };

                MenuItem         togglePrimary       = new MenuItem("Основной парашют", "");
                MenuItem         toggleReserve       = new MenuItem("Резервный парашют", "");
                MenuListItem     primaryChutes       = new MenuListItem("Цвет основного", chutes, 0, $"Основной парашют: {chuteDescriptions[0]}");
                MenuListItem     secondaryChutes     = new MenuListItem("Цвет резервного", chutes, 0, $"Reserve chute: {chuteDescriptions[0]}");
                MenuCheckboxItem unlimitedParachutes = new MenuCheckboxItem("Бесконечные парашюты", "", UnlimitedParachutes);
                MenuCheckboxItem autoEquipParachutes = new MenuCheckboxItem("Автоматические парашюты", "Получите бесплатный парашют в самолете.", AutoEquipChute);

                // smoke color list
                List <string> smokeColorsList = new List <string>()
                {
                    GetLabelText("PM_TINT8"),  // no smoke
                    GetLabelText("PM_TINT9"),  // red
                    GetLabelText("PM_TINT10"), // orange
                    GetLabelText("PM_TINT11"), // yellow
                    GetLabelText("PM_TINT12"), // blue
                    GetLabelText("PM_TINT13"), // black
                };
                List <int[]> colors = new List <int[]>()
                {
                    new int[3] {
                        255, 255, 255
                    },
                    new int[3] {
                        255, 0, 0
                    },
                    new int[3] {
                        255, 165, 0
                    },
                    new int[3] {
                        255, 255, 0
                    },
                    new int[3] {
                        0, 0, 255
                    },
                    new int[3] {
                        20, 20, 20
                    },
                };

                MenuListItem smokeColors = new MenuListItem("Трейл", smokeColorsList, 0, "");

                parachuteMenu.AddMenuItem(togglePrimary);
                parachuteMenu.AddMenuItem(toggleReserve);
                parachuteMenu.AddMenuItem(autoEquipParachutes);
                parachuteMenu.AddMenuItem(unlimitedParachutes);
                parachuteMenu.AddMenuItem(smokeColors);
                parachuteMenu.AddMenuItem(primaryChutes);
                parachuteMenu.AddMenuItem(secondaryChutes);

                parachuteMenu.OnItemSelect += (sender, item, index) =>
                {
                    if (item == togglePrimary)
                    {
                        if (HasPedGotWeapon(Game.PlayerPed.Handle, (uint)GetHashKey("gadget_parachute"), false))
                        {
                            Subtitle.Custom("Primary parachute removed.");
                            RemoveWeaponFromPed(Game.PlayerPed.Handle, (uint)GetHashKey("gadget_parachute"));
                        }
                        else
                        {
                            Subtitle.Custom("Primary parachute added.");
                            GiveWeaponToPed(Game.PlayerPed.Handle, (uint)GetHashKey("gadget_parachute"), 0, false, false);
                        }
                    }
                    else if (item == toggleReserve)
                    {
                        SetPlayerHasReserveParachute(Game.Player.Handle);
                        Subtitle.Custom("Reserve parachute has been added.");
                    }
                };

                parachuteMenu.OnCheckboxChange += (sender, item, index, _checked) =>
                {
                    if (item == unlimitedParachutes)
                    {
                        UnlimitedParachutes = _checked;
                    }
                    else if (item == autoEquipParachutes)
                    {
                        AutoEquipChute = _checked;
                    }
                };

                bool switching = false;
                async void IndexChangedEventHandler(Menu sender, MenuListItem item, int oldIndex, int newIndex, int itemIndex)
                {
                    if (item == smokeColors && oldIndex == -1)
                    {
                        if (!switching)
                        {
                            switching = true;
                            SetPlayerCanLeaveParachuteSmokeTrail(Game.Player.Handle, false);
                            await Delay(4000);

                            int[] color = colors[newIndex];
                            SetPlayerParachuteSmokeTrailColor(Game.Player.Handle, color[0], color[1], color[2]);
                            SetPlayerCanLeaveParachuteSmokeTrail(Game.Player.Handle, newIndex != 0);
                            switching = false;
                        }
                    }
                    else if (item == primaryChutes)
                    {
                        item.Description = $"Основной парашют: {chuteDescriptions[newIndex]}";
                        SetPlayerParachuteTintIndex(Game.Player.Handle, newIndex);
                    }
                    else if (item == secondaryChutes)
                    {
                        item.Description = $"Резервный парашют: {chuteDescriptions[newIndex]}";
                        SetPlayerReserveParachuteTintIndex(Game.Player.Handle, newIndex);
                    }
                }

                parachuteMenu.OnListItemSelect  += (sender, item, index, itemIndex) => IndexChangedEventHandler(sender, item, -1, index, itemIndex);
                parachuteMenu.OnListIndexChange += IndexChangedEventHandler;
            }
            #endregion

            #region Create Weapon Category Submenus
            MenuItem spacer = GetSpacerMenuItem("↓ Категории ↓");
            menu.AddMenuItem(spacer);

            Menu     handGuns    = new Menu("Оружие", "Пистолеты");
            MenuItem handGunsBtn = new MenuItem("Пистолеты");

            Menu     rifles    = new Menu("Оружие", "Винтовки");
            MenuItem riflesBtn = new MenuItem("Винтовки");

            Menu     shotguns    = new Menu("Оружие", "Дробовики");
            MenuItem shotgunsBtn = new MenuItem("Дробовики");

            Menu     smgs    = new Menu("Оружие", "Пистолеты-пулеметы");
            MenuItem smgsBtn = new MenuItem("Пистолеты-пулеметы");

            Menu     throwables    = new Menu("Оружие", "Кидаемое");
            MenuItem throwablesBtn = new MenuItem("Кидаемое");

            Menu     melee    = new Menu("Оружие", "Ближнего боя");
            MenuItem meleeBtn = new MenuItem("Ближнего боя");

            Menu     heavy    = new Menu("Оружие", "Тяжелое");
            MenuItem heavyBtn = new MenuItem("Тяжелое");

            Menu     snipers    = new Menu("Оружие", "Снайперские винтовки");
            MenuItem snipersBtn = new MenuItem("Снайперские винтовки");

            MenuController.AddSubmenu(menu, handGuns);
            MenuController.AddSubmenu(menu, rifles);
            MenuController.AddSubmenu(menu, shotguns);
            MenuController.AddSubmenu(menu, smgs);
            MenuController.AddSubmenu(menu, throwables);
            MenuController.AddSubmenu(menu, melee);
            MenuController.AddSubmenu(menu, heavy);
            MenuController.AddSubmenu(menu, snipers);
            #endregion

            #region Setup weapon category buttons and submenus.
            handGunsBtn.Label = "→→→";
            menu.AddMenuItem(handGunsBtn);
            MenuController.BindMenuItem(menu, handGuns, handGunsBtn);

            riflesBtn.Label = "→→→";
            menu.AddMenuItem(riflesBtn);
            MenuController.BindMenuItem(menu, rifles, riflesBtn);

            shotgunsBtn.Label = "→→→";
            menu.AddMenuItem(shotgunsBtn);
            MenuController.BindMenuItem(menu, shotguns, shotgunsBtn);

            smgsBtn.Label = "→→→";
            menu.AddMenuItem(smgsBtn);
            MenuController.BindMenuItem(menu, smgs, smgsBtn);

            throwablesBtn.Label = "→→→";
            menu.AddMenuItem(throwablesBtn);
            MenuController.BindMenuItem(menu, throwables, throwablesBtn);

            meleeBtn.Label = "→→→";
            menu.AddMenuItem(meleeBtn);
            MenuController.BindMenuItem(menu, melee, meleeBtn);

            heavyBtn.Label = "→→→";
            menu.AddMenuItem(heavyBtn);
            MenuController.BindMenuItem(menu, heavy, heavyBtn);

            snipersBtn.Label = "→→→";
            menu.AddMenuItem(snipersBtn);
            MenuController.BindMenuItem(menu, snipers, snipersBtn);
            #endregion

            #region Loop through all weapons, create menus for them and add all menu items and handle events.
            foreach (ValidWeapon weapon in ValidWeapons.WeaponList)
            {
                uint cat = (uint)GetWeapontypeGroup(weapon.Hash);
                if (!string.IsNullOrEmpty(weapon.Name) && (IsAllowed(weapon.Perm) || IsAllowed(Permission.WPGetAll)))
                {
                    //Log($"[DEBUG LOG] [WEAPON-BUG] {weapon.Name} - {weapon.Perm} = {IsAllowed(weapon.Perm)} & All = {IsAllowed(Permission.WPGetAll)}");
                    #region Create menu for this weapon and add buttons
                    Menu     weaponMenu = new Menu("Опции", weapon.Name);
                    MenuItem weaponItem = new MenuItem(weapon.Name, $"Open the options for ~y~{weapon.Name.ToString()}~s~.")
                    {
                        Label    = "→→→",
                        LeftIcon = MenuItem.Icon.GUN
                    };

                    weaponInfo.Add(weaponMenu, weapon);

                    MenuItem getOrRemoveWeapon = new MenuItem("Взять/Убрать", "")
                    {
                        LeftIcon = MenuItem.Icon.GUN
                    };
                    weaponMenu.AddMenuItem(getOrRemoveWeapon);
                    if (!IsAllowed(Permission.WPSpawn))
                    {
                        getOrRemoveWeapon.Enabled     = false;
                        getOrRemoveWeapon.Description = "You do not have permission to use this option.";
                        getOrRemoveWeapon.LeftIcon    = MenuItem.Icon.LOCK;
                    }

                    MenuItem fillAmmo = new MenuItem("Пополнить боезапас", "")
                    {
                        LeftIcon = MenuItem.Icon.AMMO
                    };
                    weaponMenu.AddMenuItem(fillAmmo);

                    List <string> tints = new List <string>();
                    if (weapon.Name.Contains(" Mk II"))
                    {
                        foreach (var tint in ValidWeapons.WeaponTintsMkII)
                        {
                            tints.Add(tint.Key);
                        }
                    }
                    else
                    {
                        foreach (var tint in ValidWeapons.WeaponTints)
                        {
                            tints.Add(tint.Key);
                        }
                    }

                    MenuListItem weaponTints = new MenuListItem("Раскраски", tints, 0, "");
                    weaponMenu.AddMenuItem(weaponTints);
                    #endregion

                    #region Handle weapon specific list changes
                    weaponMenu.OnListIndexChange += (sender, item, oldIndex, newIndex, itemIndex) =>
                    {
                        if (item == weaponTints)
                        {
                            if (HasPedGotWeapon(Game.PlayerPed.Handle, weaponInfo[sender].Hash, false))
                            {
                                SetPedWeaponTintIndex(Game.PlayerPed.Handle, weaponInfo[sender].Hash, newIndex);
                            }
                            else
                            {
                                Notify.Error("You need to get the weapon first!");
                            }
                        }
                    };
                    #endregion

                    #region Handle weapon specific button presses
                    weaponMenu.OnItemSelect += (sender, item, index) =>
                    {
                        var  info = weaponInfo[sender];
                        uint hash = info.Hash;

                        SetCurrentPedWeapon(Game.PlayerPed.Handle, hash, true);

                        if (item == getOrRemoveWeapon)
                        {
                            if (HasPedGotWeapon(Game.PlayerPed.Handle, hash, false))
                            {
                                RemoveWeaponFromPed(Game.PlayerPed.Handle, hash);
                                Subtitle.Custom("Weapon removed.");
                            }
                            else
                            {
                                var ammo = 255;
                                GetMaxAmmo(Game.PlayerPed.Handle, hash, ref ammo);
                                GiveWeaponToPed(Game.PlayerPed.Handle, hash, ammo, false, true);
                                Subtitle.Custom("Weapon added.");
                            }
                        }
                        else if (item == fillAmmo)
                        {
                            if (HasPedGotWeapon(Game.PlayerPed.Handle, hash, false))
                            {
                                var ammo = 900;
                                GetMaxAmmo(Game.PlayerPed.Handle, hash, ref ammo);
                                SetPedAmmo(Game.PlayerPed.Handle, hash, ammo);
                            }
                            else
                            {
                                Notify.Error("You need to get the weapon first before re-filling ammo!");
                            }
                        }
                    };
                    #endregion

                    #region load components
                    if (weapon.Components != null)
                    {
                        if (weapon.Components.Count > 0)
                        {
                            foreach (var comp in weapon.Components)
                            {
                                //Log($"{weapon.Name} : {comp.Key}");
                                MenuItem compItem = new MenuItem(comp.Key, "Click to equip or remove this component.");
                                weaponComponents.Add(compItem, comp.Key);
                                weaponMenu.AddMenuItem(compItem);

                                #region Handle component button presses
                                weaponMenu.OnItemSelect += (sender, item, index) =>
                                {
                                    if (item == compItem)
                                    {
                                        var Weapon        = weaponInfo[sender];
                                        var componentHash = Weapon.Components[weaponComponents[item]];
                                        if (HasPedGotWeapon(Game.PlayerPed.Handle, Weapon.Hash, false))
                                        {
                                            SetCurrentPedWeapon(Game.PlayerPed.Handle, Weapon.Hash, true);
                                            if (HasPedGotWeaponComponent(Game.PlayerPed.Handle, Weapon.Hash, componentHash))
                                            {
                                                RemoveWeaponComponentFromPed(Game.PlayerPed.Handle, Weapon.Hash, componentHash);

                                                Subtitle.Custom("Component removed.");
                                            }
                                            else
                                            {
                                                int ammo = GetAmmoInPedWeapon(Game.PlayerPed.Handle, Weapon.Hash);

                                                int clipAmmo = GetMaxAmmoInClip(Game.PlayerPed.Handle, Weapon.Hash, false);
                                                GetAmmoInClip(Game.PlayerPed.Handle, Weapon.Hash, ref clipAmmo);

                                                GiveWeaponComponentToPed(Game.PlayerPed.Handle, Weapon.Hash, componentHash);

                                                SetAmmoInClip(Game.PlayerPed.Handle, Weapon.Hash, clipAmmo);

                                                SetPedAmmo(Game.PlayerPed.Handle, Weapon.Hash, ammo);
                                                Subtitle.Custom("Component equiped.");
                                            }
                                        }
                                        else
                                        {
                                            Notify.Error("You need to get the weapon first before you can modify it.");
                                        }
                                    }
                                };
                                #endregion
                            }
                        }
                    }
                    #endregion

                    // refresh and add to menu.
                    weaponMenu.RefreshIndex();

                    if (cat == 970310034) // 970310034 rifles
                    {
                        MenuController.AddSubmenu(rifles, weaponMenu);
                        MenuController.BindMenuItem(rifles, weaponMenu, weaponItem);
                        rifles.AddMenuItem(weaponItem);
                    }
                    else if (cat == 416676503 || cat == 690389602) // 416676503 hand guns // 690389602 stun gun
                    {
                        MenuController.AddSubmenu(handGuns, weaponMenu);
                        MenuController.BindMenuItem(handGuns, weaponMenu, weaponItem);
                        handGuns.AddMenuItem(weaponItem);
                    }
                    else if (cat == 860033945) // 860033945 shotguns
                    {
                        MenuController.AddSubmenu(shotguns, weaponMenu);
                        MenuController.BindMenuItem(shotguns, weaponMenu, weaponItem);
                        shotguns.AddMenuItem(weaponItem);
                    }
                    else if (cat == 3337201093 || cat == 1159398588) // 3337201093 sub machine guns // 1159398588 light machine guns
                    {
                        MenuController.AddSubmenu(smgs, weaponMenu);
                        MenuController.BindMenuItem(smgs, weaponMenu, weaponItem);
                        smgs.AddMenuItem(weaponItem);
                    }
                    else if (cat == 1548507267 || cat == 4257178988 || cat == 1595662460) // 1548507267 throwables // 4257178988 fire extinghuiser // jerry can
                    {
                        MenuController.AddSubmenu(throwables, weaponMenu);
                        MenuController.BindMenuItem(throwables, weaponMenu, weaponItem);
                        throwables.AddMenuItem(weaponItem);
                    }
                    else if (cat == 3566412244 || cat == 2685387236) // 3566412244 melee weapons // 2685387236 knuckle duster
                    {
                        MenuController.AddSubmenu(melee, weaponMenu);
                        MenuController.BindMenuItem(melee, weaponMenu, weaponItem);
                        melee.AddMenuItem(weaponItem);
                    }
                    else if (cat == 2725924767) // 2725924767 heavy weapons
                    {
                        MenuController.AddSubmenu(heavy, weaponMenu);
                        MenuController.BindMenuItem(heavy, weaponMenu, weaponItem);
                        heavy.AddMenuItem(weaponItem);
                    }
                    else if (cat == 3082541095) // 3082541095 sniper rifles
                    {
                        MenuController.AddSubmenu(snipers, weaponMenu);
                        MenuController.BindMenuItem(snipers, weaponMenu, weaponItem);
                        snipers.AddMenuItem(weaponItem);
                    }
                }
            }
            #endregion

            #region Disable submenus if no weapons in that category are allowed.
            if (handGuns.Size == 0)
            {
                handGunsBtn.LeftIcon    = MenuItem.Icon.LOCK;
                handGunsBtn.Description = "The server owner removed the permissions for all weapons in this category.";
                handGunsBtn.Enabled     = false;
            }
            if (rifles.Size == 0)
            {
                riflesBtn.LeftIcon    = MenuItem.Icon.LOCK;
                riflesBtn.Description = "The server owner removed the permissions for all weapons in this category.";
                riflesBtn.Enabled     = false;
            }
            if (shotguns.Size == 0)
            {
                shotgunsBtn.LeftIcon    = MenuItem.Icon.LOCK;
                shotgunsBtn.Description = "The server owner removed the permissions for all weapons in this category.";
                shotgunsBtn.Enabled     = false;
            }
            if (smgs.Size == 0)
            {
                smgsBtn.LeftIcon    = MenuItem.Icon.LOCK;
                smgsBtn.Description = "The server owner removed the permissions for all weapons in this category.";
                smgsBtn.Enabled     = false;
            }
            if (throwables.Size == 0)
            {
                throwablesBtn.LeftIcon    = MenuItem.Icon.LOCK;
                throwablesBtn.Description = "The server owner removed the permissions for all weapons in this category.";
                throwablesBtn.Enabled     = false;
            }
            if (melee.Size == 0)
            {
                meleeBtn.LeftIcon    = MenuItem.Icon.LOCK;
                meleeBtn.Description = "The server owner removed the permissions for all weapons in this category.";
                meleeBtn.Enabled     = false;
            }
            if (heavy.Size == 0)
            {
                heavyBtn.LeftIcon    = MenuItem.Icon.LOCK;
                heavyBtn.Description = "The server owner removed the permissions for all weapons in this category.";
                heavyBtn.Enabled     = false;
            }
            if (snipers.Size == 0)
            {
                snipersBtn.LeftIcon    = MenuItem.Icon.LOCK;
                snipersBtn.Description = "The server owner removed the permissions for all weapons in this category.";
                snipersBtn.Enabled     = false;
            }
            #endregion

            #region Handle button presses
            menu.OnItemSelect += (sender, item, index) =>
            {
                Ped ped = new Ped(Game.PlayerPed.Handle);
                if (item == getAllWeapons)
                {
                    foreach (ValidWeapon vw in ValidWeapons.WeaponList)
                    {
                        if (IsAllowed(vw.Perm))
                        {
                            GiveWeaponToPed(Game.PlayerPed.Handle, vw.Hash, vw.GetMaxAmmo, false, true);

                            int ammoInClip = GetMaxAmmoInClip(Game.PlayerPed.Handle, vw.Hash, false);
                            SetAmmoInClip(Game.PlayerPed.Handle, vw.Hash, ammoInClip);
                            int ammo = 0;
                            GetMaxAmmo(Game.PlayerPed.Handle, vw.Hash, ref ammo);
                            SetPedAmmo(Game.PlayerPed.Handle, vw.Hash, ammo);
                        }
                    }

                    SetCurrentPedWeapon(Game.PlayerPed.Handle, (uint)GetHashKey("weapon_unarmed"), true);
                }
                else if (item == removeAllWeapons)
                {
                    ped.Weapons.RemoveAll();
                }
                else if (item == setAmmo)
                {
                    SetAllWeaponsAmmo();
                }
                else if (item == refillMaxAmmo)
                {
                    foreach (ValidWeapon vw in ValidWeapons.WeaponList)
                    {
                        if (HasPedGotWeapon(Game.PlayerPed.Handle, vw.Hash, false))
                        {
                            int ammoInClip = GetMaxAmmoInClip(Game.PlayerPed.Handle, vw.Hash, false);
                            SetAmmoInClip(Game.PlayerPed.Handle, vw.Hash, ammoInClip);
                            int ammo = 0;
                            GetMaxAmmo(Game.PlayerPed.Handle, vw.Hash, ref ammo);
                            SetPedAmmo(Game.PlayerPed.Handle, vw.Hash, ammo);
                        }
                    }
                }
                else if (item == spawnByName)
                {
                    SpawnCustomWeapon();
                }
            };
            #endregion

            #region Handle checkbox changes
            menu.OnCheckboxChange += (sender, item, index, _checked) =>
            {
                if (item == noReload)
                {
                    NoReload = _checked;
                    Subtitle.Custom($"No reload is now {(_checked ? "enabled" : "disabled")}.");
                }
                else if (item == unlimitedAmmo)
                {
                    UnlimitedAmmo = _checked;
                    Subtitle.Custom($"Unlimited ammo is now {(_checked ? "enabled" : "disabled")}.");
                }
            };
            #endregion
        }
示例#14
0
        /// <summary>
        /// Creates the menu.
        /// </summary>
        private void CreateMenu()
        {
            string menuTitle = "儲存載具";

            #region Create menus and submenus
            // Create the menu.
            menu = new Menu(menuTitle, "管理已保存的載具");

            MenuItem saveVehicle = new MenuItem("保存當前載具", "保存您當前坐入之載具.");
            menu.AddMenuItem(saveVehicle);
            saveVehicle.LeftIcon = MenuItem.Icon.CAR;

            menu.OnItemSelect += (sender, item, index) =>
            {
                if (item == saveVehicle)
                {
                    if (Game.PlayerPed.IsInVehicle())
                    {
                        SaveVehicle();
                    }
                    else
                    {
                        Notify.Error("您目前不在任何車輛中。 請先輸入車輛再嘗試保存.");
                    }
                }
            };

            for (int i = 0; i < 22; i++)
            {
                Menu categoryMenu = new Menu("儲存車輛", GetLabelText($"VEH_CLASS_{i}"));

                MenuItem categoryButton = new MenuItem(GetLabelText($"VEH_CLASS_{i}"), $"從中保存的所有車輛 {(GetLabelText($"VEH_CLASS_{i}"))} 類型.");
                subMenus.Add(categoryMenu);
                MenuController.AddSubmenu(menu, categoryMenu);
                menu.AddMenuItem(categoryButton);
                categoryButton.Label = "→→→";
                MenuController.BindMenuItem(menu, categoryMenu, categoryButton);

                categoryMenu.OnMenuClose += (sender) =>
                {
                    UpdateMenuAvailableCategories();
                };

                categoryMenu.OnItemSelect += (sender, item, index) =>
                {
                    UpdateSelectedVehicleMenu(item, sender);
                };
            }

            MenuItem unavailableModels = new MenuItem("車輛遺失", "在遊戲文件中找不到該模組。可能原因這是一個附加載具,並且伺服器當前未對其進行處理.")
            {
                Label = "→→→"
            };

            menu.AddMenuItem(unavailableModels);
            MenuController.BindMenuItem(menu, unavailableVehiclesMenu, unavailableModels);
            MenuController.AddSubmenu(menu, unavailableVehiclesMenu);


            MenuController.AddMenu(selectedVehicleMenu);
            MenuItem spawnVehicle   = new MenuItem("生成車輛", "生成此已保存的車輛.");
            MenuItem renameVehicle  = new MenuItem("重命名車輛", "重命名您保存的車輛.");
            MenuItem replaceVehicle = new MenuItem("~r~更換車輛", "您保存的車輛將被您當前所坐的車輛代替。~r~警告:這無法撤消!");
            MenuItem deleteVehicle  = new MenuItem("~r~刪除車輛", "~r~這將刪除您保存的車輛。警告:這不能撤消!");
            selectedVehicleMenu.AddMenuItem(spawnVehicle);
            selectedVehicleMenu.AddMenuItem(renameVehicle);
            selectedVehicleMenu.AddMenuItem(replaceVehicle);
            selectedVehicleMenu.AddMenuItem(deleteVehicle);

            selectedVehicleMenu.OnMenuOpen += (sender) =>
            {
                spawnVehicle.Label = "(" + GetDisplayNameFromVehicleModel(currentlySelectedVehicle.Value.model).ToLower() + ")";
            };

            selectedVehicleMenu.OnMenuClose += (sender) =>
            {
                selectedVehicleMenu.RefreshIndex();
                deleteButtonPressedCount = 0;
                deleteVehicle.Label      = "";
            };

            selectedVehicleMenu.OnItemSelect += async(sender, item, index) =>
            {
                if (item == spawnVehicle)
                {
                    if (MainMenu.VehicleSpawnerMenu != null)
                    {
                        SpawnVehicle(currentlySelectedVehicle.Value.model, MainMenu.VehicleSpawnerMenu.SpawnInVehicle, MainMenu.VehicleSpawnerMenu.ReplaceVehicle, false, vehicleInfo: currentlySelectedVehicle.Value, saveName: currentlySelectedVehicle.Key.Substring(4));
                    }
                    else
                    {
                        SpawnVehicle(currentlySelectedVehicle.Value.model, true, true, false, vehicleInfo: currentlySelectedVehicle.Value, saveName: currentlySelectedVehicle.Key.Substring(4));
                    }
                }
                else if (item == renameVehicle)
                {
                    string newName = await GetUserInput(windowTitle : "輸入此車輛的新名稱.", maxInputLength : 30);

                    if (string.IsNullOrEmpty(newName))
                    {
                        Notify.Error(CommonErrors.InvalidInput);
                    }
                    else
                    {
                        if (StorageManager.SaveVehicleInfo("veh_" + newName, currentlySelectedVehicle.Value, false))
                        {
                            DeleteResourceKvp(currentlySelectedVehicle.Key);
                            while (!selectedVehicleMenu.Visible)
                            {
                                await BaseScript.Delay(0);
                            }
                            Notify.Success("您的車輛已成功重命名.");
                            UpdateMenuAvailableCategories();
                            selectedVehicleMenu.GoBack();
                            currentlySelectedVehicle = new KeyValuePair <string, VehicleInfo>(); // clear the old info
                        }
                        else
                        {
                            Notify.Error("此名稱已被使用或未知失敗。 如果您認為有問題,請與服務器所有者聯繫。");
                        }
                    }
                }
                else if (item == replaceVehicle)
                {
                    if (Game.PlayerPed.IsInVehicle())
                    {
                        SaveVehicle(currentlySelectedVehicle.Key.Substring(4));
                        selectedVehicleMenu.GoBack();
                        Notify.Success("您保存的車輛已替換為當前車輛.");
                    }
                    else
                    {
                        Notify.Error("您需要先上車才能更換舊車.");
                    }
                }
                else if (item == deleteVehicle)
                {
                    if (deleteButtonPressedCount == 0)
                    {
                        deleteButtonPressedCount = 1;
                        item.Label = "再按一次確認.";
                        Notify.Alert("您確定要刪除這輛車嗎? 再按一次按鈕確認.");
                    }
                    else
                    {
                        deleteButtonPressedCount = 0;
                        item.Label = "";
                        DeleteResourceKvp(currentlySelectedVehicle.Key);
                        UpdateMenuAvailableCategories();
                        selectedVehicleMenu.GoBack();
                        Notify.Success("您保存的車輛已被刪除.");
                    }
                }
                if (item != deleteVehicle) // if any other button is pressed, restore the delete vehicle button pressed count.
                {
                    deleteButtonPressedCount = 0;
                    deleteVehicle.Label      = "";
                }
            };
            unavailableVehiclesMenu.InstructionalButtons.Add(Control.FrontendDelete, "刪除載具!");

            unavailableVehiclesMenu.ButtonPressHandlers.Add(new Menu.ButtonPressHandler(Control.FrontendDelete, Menu.ControlPressCheckType.JUST_RELEASED, new Action <Menu, Control>((m, c) =>
            {
                if (m.Size > 0)
                {
                    int index = m.CurrentIndex;
                    if (index < m.Size)
                    {
                        MenuItem item = m.GetMenuItems().Find(i => i.Index == index);
                        if (item != null && (item.ItemData is KeyValuePair <string, VehicleInfo> sd))
                        {
                            if (item.Label == "~r~您確定嗎?")
                            {
                                Log("Unavailable saved vehicle deleted, data: " + JsonConvert.SerializeObject(sd));
                                DeleteResourceKvp(sd.Key);
                                unavailableVehiclesMenu.GoBack();
                                UpdateMenuAvailableCategories();
                            }
                            else
                            {
                                item.Label = "~r~您確定嗎?";
                            }
                        }
                        else
                        {
                            Notify.Error("不知何故找不到這輛車.");
                        }
                    }
                    else
                    {
                        Notify.Error("您以某種方式設法觸發了一個不存在的菜單項的刪除...?");
                    }
                }
示例#15
0
        /// <summary>
        /// Creates the menu.
        /// </summary>
        private void CreateMenu()
        {
            MenuController.MenuAlignment = MiscRightAlignMenu ? MenuController.MenuAlignmentOption.Right : MenuController.MenuAlignmentOption.Left;
            if (MenuController.MenuAlignment != (MiscRightAlignMenu ? MenuController.MenuAlignmentOption.Right : MenuController.MenuAlignmentOption.Left))
            {
                Notify.Error(CommonErrors.RightAlignedNotSupported);

                // (re)set the default to left just in case so they don't get this error again in the future.
                MenuController.MenuAlignment    = MenuController.MenuAlignmentOption.Left;
                MiscRightAlignMenu              = false;
                UserDefaults.MiscRightAlignMenu = false;
            }

            // Create the menu.
            menu = new Menu(Game.Player.Name, "Misc Settings");
            teleportOptionsMenu = new Menu(Game.Player.Name, "Teleport Options");
            developerToolsMenu  = new Menu(Game.Player.Name, "Development Tools");

            // teleport menu
            Menu     teleportMenu    = new Menu(Game.Player.Name, "Teleport Locations");
            MenuItem teleportMenuBtn = new MenuItem("Teleport Locations", "Teleport to pre-configured locations, added by the server owner.");

            MenuController.AddSubmenu(menu, teleportMenu);
            MenuController.BindMenuItem(menu, teleportMenu, teleportMenuBtn);

            // keybind settings menu
            Menu     keybindMenu    = new Menu(Game.Player.Name, "Keybind Settings");
            MenuItem keybindMenuBtn = new MenuItem("Keybind Settings", "Enable or disable keybinds for some options.");

            MenuController.AddSubmenu(menu, keybindMenu);
            MenuController.BindMenuItem(menu, keybindMenu, keybindMenuBtn);

            // keybind settings menu items
            MenuCheckboxItem kbTpToWaypoint      = new MenuCheckboxItem("Teleport To Waypoint", "Teleport to your waypoint when pressing the keybind. By default, this keybind is set to ~r~F7~s~, server owners are able to change this however so ask them if you don't know what it is.", KbTpToWaypoint);
            MenuCheckboxItem kbDriftMode         = new MenuCheckboxItem("Drift Mode", "Makes your vehicle have almost no traction while holding left shift on keyboard, or X on controller.", KbDriftMode);
            MenuCheckboxItem kbRecordKeys        = new MenuCheckboxItem("Recording Controls", "Enables or disables the recording (gameplay recording for the Rockstar editor) hotkeys on both keyboard and controller.", KbRecordKeys);
            MenuCheckboxItem kbRadarKeys         = new MenuCheckboxItem("Minimap Controls", "Press the Multiplayer Info (z on keyboard, down arrow on controller) key to switch between expanded radar and normal radar.", KbRadarKeys);
            MenuCheckboxItem kbPointKeysCheckbox = new MenuCheckboxItem("Finger Point Controls", "Enables the finger point toggle key. The default QWERTY keyboard mapping for this is 'B', or for controller quickly double tap the right analog stick.", KbPointKeys);
            MenuItem         backBtn             = new MenuItem("Back");

            // Create the menu items.
            MenuCheckboxItem rightAlignMenu       = new MenuCheckboxItem("Right Align Menu", "If you want vMenu to appear on the left side of your screen, disable this option. This option will be saved immediately. You don't need to click save preferences.", MiscRightAlignMenu);
            MenuCheckboxItem disablePms           = new MenuCheckboxItem("Disable Private Messages", "Prevent others from sending you a private message via the Online Players menu. This also prevents you from sending messages to other players.", MiscDisablePrivateMessages);
            MenuCheckboxItem disableControllerKey = new MenuCheckboxItem("Disable Controller Support", "This disables the controller menu toggle key. This does NOT disable the navigation buttons.", MiscDisableControllerSupport);
            MenuCheckboxItem speedKmh             = new MenuCheckboxItem("Show Speed KM/H", "Show a speedometer on your screen indicating your speed in KM/h.", ShowSpeedoKmh);
            MenuCheckboxItem speedMph             = new MenuCheckboxItem("Show Speed MPH", "Show a speedometer on your screen indicating your speed in MPH.", ShowSpeedoMph);
            MenuCheckboxItem coords       = new MenuCheckboxItem("Show Coordinates", "Show your current coordinates at the top of your screen.", ShowCoordinates);
            MenuCheckboxItem hideRadar    = new MenuCheckboxItem("Hide Radar", "Hide the radar/minimap.", HideRadar);
            MenuCheckboxItem hideHud      = new MenuCheckboxItem("Hide Hud", "Hide all hud elements.", HideHud);
            MenuCheckboxItem showLocation = new MenuCheckboxItem("Location Display", "Shows your current location and heading, as well as the nearest cross road. Similar like PLD. ~r~Warning: This feature (can) take(s) up to -4.6 FPS when running at 60 Hz.", ShowLocation)
            {
                LeftIcon = MenuItem.Icon.WARNING
            };
            MenuCheckboxItem drawTime     = new MenuCheckboxItem("Show Time On Screen", "Shows you the current time on screen.", DrawTimeOnScreen);
            MenuItem         saveSettings = new MenuItem("Save Personal Settings", "Save your current settings. All saving is done on the client side, if you re-install windows you will lose your settings. Settings are shared across all servers using vMenu.")
            {
                RightIcon = MenuItem.Icon.TICK
            };
            MenuItem         exportData               = new MenuItem("Export/Import Data", "Coming soon (TM): the ability to import and export your saved data.");
            MenuCheckboxItem joinQuitNotifs           = new MenuCheckboxItem("Join / Quit Notifications", "Receive notifications when someone joins or leaves the server.", JoinQuitNotifications);
            MenuCheckboxItem deathNotifs              = new MenuCheckboxItem("Death Notifications", "Receive notifications when someone dies or gets killed.", DeathNotifications);
            MenuCheckboxItem nightVision              = new MenuCheckboxItem("Toggle Night Vision", "Enable or disable night vision.", false);
            MenuCheckboxItem thermalVision            = new MenuCheckboxItem("Toggle Thermal Vision", "Enable or disable thermal vision.", false);
            MenuCheckboxItem vehModelDimensions       = new MenuCheckboxItem("Show Vehicle Dimensions", "Draws the model outlines for every vehicle that's currently close to you.", ShowVehicleModelDimensions);
            MenuCheckboxItem propModelDimensions      = new MenuCheckboxItem("Show Prop Dimensions", "Draws the model outlines for every prop that's currently close to you.", ShowPropModelDimensions);
            MenuCheckboxItem pedModelDimensions       = new MenuCheckboxItem("Show Ped Dimensions", "Draws the model outlines for every ped that's currently close to you.", ShowPedModelDimensions);
            MenuCheckboxItem showEntityHandles        = new MenuCheckboxItem("Show Entity Handles", "Draws the the entity handles for all close entities (you must enable the outline functions above for this to work).", ShowEntityHandles);
            MenuCheckboxItem showEntityModels         = new MenuCheckboxItem("Show Entity Models", "Draws the the entity models for all close entities (you must enable the outline functions above for this to work).", ShowEntityModels);
            MenuSliderItem   dimensionsDistanceSlider = new MenuSliderItem("Show Dimensions Radius", "Show entity model/handle/dimension draw range.", 0, 20, 20, false);

            MenuItem         clearArea = new MenuItem("Clear Area", "Clears the area around your player (100 meters). Damage, dirt, peds, props, vehicles, etc. Everything gets cleaned up, fixed and reset to the default world state.");
            MenuCheckboxItem lockCamX  = new MenuCheckboxItem("Lock Camera Horizontal Rotation", "Locks your camera horizontal rotation. Could be useful in helicopters I guess.", false);
            MenuCheckboxItem lockCamY  = new MenuCheckboxItem("Lock Camera Vertical Rotation", "Locks your camera vertical rotation. Could be useful in helicopters I guess.", false);


            Menu     connectionSubmenu    = new Menu(Game.Player.Name, "Connection Options");
            MenuItem connectionSubmenuBtn = new MenuItem("Connection Options", "Server connection/game quit options.");

            MenuItem quitSession          = new MenuItem("Quit Session", "Leaves you connected to the server, but quits the network session. ~r~Can not be used when you are the host.");
            MenuItem rejoinSession        = new MenuItem("Re-join Session", "This may not work in all cases, but you can try to use this if you want to re-join the previous session after clicking 'Quit Session'.");
            MenuItem quitGame             = new MenuItem("Quit Game", "Exits the game after 5 seconds.");
            MenuItem disconnectFromServer = new MenuItem("Disconnect From Server", "Disconnects you from the server and returns you to the serverlist. ~r~This feature is not recommended, quit the game completely instead and restart it for a better experience.");

            connectionSubmenu.AddMenuItem(quitSession);
            connectionSubmenu.AddMenuItem(rejoinSession);
            connectionSubmenu.AddMenuItem(quitGame);
            connectionSubmenu.AddMenuItem(disconnectFromServer);

            MenuCheckboxItem enableTimeCycle            = new MenuCheckboxItem("Enable Timecycle Modifier", "Enable or disable the timecycle modifier from the list below.", TimecycleEnabled);
            List <string>    timeCycleModifiersListData = TimeCycles.Timecycles.ToList();

            for (var i = 0; i < timeCycleModifiersListData.Count; i++)
            {
                timeCycleModifiersListData[i] += $" ({i + 1}/{timeCycleModifiersListData.Count})";
            }
            MenuListItem   timeCycles         = new MenuListItem("TM", timeCycleModifiersListData, MathUtil.Clamp(LastTimeCycleModifierIndex, 0, Math.Max(0, timeCycleModifiersListData.Count - 1)), "Select a timecycle modifier and enable the checkbox above.");
            MenuSliderItem timeCycleIntensity = new MenuSliderItem("Timecycle Modifier Intensity", "Set the timecycle modifier intensity.", 0, 20, LastTimeCycleModifierStrength, true);

            MenuCheckboxItem locationBlips           = new MenuCheckboxItem("Location Blips", "Shows blips on the map for some common locations.", ShowLocationBlips);
            MenuCheckboxItem playerBlips             = new MenuCheckboxItem("Show Player Blips", "Shows blips on the map for all players.", ShowPlayerBlips);
            MenuCheckboxItem playerNames             = new MenuCheckboxItem("Show Player Names", "Enables or disables player overhead names.", MiscShowOverheadNames);
            MenuCheckboxItem respawnDefaultCharacter = new MenuCheckboxItem("Respawn As Default MP Character", "If you enable this, then you will (re)spawn as your default saved MP character. Note the server owner can globally disable this option. To set your default character, go to one of your saved MP Characters and click the 'Set As Default Character' button.", MiscRespawnDefaultCharacter);
            MenuCheckboxItem restorePlayerAppearance = new MenuCheckboxItem("Restore Player Appearance", "Restore your player's skin whenever you respawn after being dead. Re-joining a server will not restore your previous skin.", RestorePlayerAppearance);
            MenuCheckboxItem restorePlayerWeapons    = new MenuCheckboxItem("Restore Player Weapons", "Restore your weapons whenever you respawn after being dead. Re-joining a server will not restore your previous weapons.", RestorePlayerWeapons);

            MenuController.AddSubmenu(menu, connectionSubmenu);
            MenuController.BindMenuItem(menu, connectionSubmenu, connectionSubmenuBtn);

            keybindMenu.OnCheckboxChange += (sender, item, index, _checked) =>
            {
                if (item == kbTpToWaypoint)
                {
                    KbTpToWaypoint = _checked;
                }
                else if (item == kbDriftMode)
                {
                    KbDriftMode = _checked;
                }
                else if (item == kbRecordKeys)
                {
                    KbRecordKeys = _checked;
                }
                else if (item == kbRadarKeys)
                {
                    KbRadarKeys = _checked;
                }
                else if (item == kbPointKeysCheckbox)
                {
                    KbPointKeys = _checked;
                }
            };
            keybindMenu.OnItemSelect += (sender, item, index) =>
            {
                if (item == backBtn)
                {
                    keybindMenu.GoBack();
                }
            };

            connectionSubmenu.OnItemSelect += (sender, item, index) =>
            {
                if (item == quitGame)
                {
                    QuitGame();
                }
                else if (item == quitSession)
                {
                    if (NetworkIsSessionActive())
                    {
                        if (NetworkIsHost())
                        {
                            Notify.Error("Sorry, you cannot leave the session when you are the host. This would prevent other players from joining/staying on the server.");
                        }
                        else
                        {
                            QuitSession();
                        }
                    }
                    else
                    {
                        Notify.Error("You are currently not in any session.");
                    }
                }
                else if (item == rejoinSession)
                {
                    if (NetworkIsSessionActive())
                    {
                        Notify.Error("You are already connected to a session.");
                    }
                    else
                    {
                        Notify.Info("Attempting to re-join the session.");
                        NetworkSessionHost(-1, 32, false);
                    }
                }
                else if (item == disconnectFromServer)
                {
                    RegisterCommand("disconnect", new Action <dynamic, dynamic, dynamic>((a, b, c) => { }), false);
                    ExecuteCommand("disconnect");
                }
            };

            // Teleportation options
            if (IsAllowed(Permission.MSTeleportToWp) || IsAllowed(Permission.MSTeleportLocations) || IsAllowed(Permission.MSTeleportToCoord))
            {
                MenuItem teleportOptionsMenuBtn = new MenuItem("Teleport Options", "Various teleport options.")
                {
                    Label = "→→→"
                };
                menu.AddMenuItem(teleportOptionsMenuBtn);
                MenuController.BindMenuItem(menu, teleportOptionsMenu, teleportOptionsMenuBtn);

                MenuItem tptowp          = new MenuItem("Teleport To Waypoint", "Teleport to the waypoint on your map.");
                MenuItem tpToCoord       = new MenuItem("Teleport To Coords", "Enter x, y, z coordinates and you will be teleported to that location.");
                MenuItem saveLocationBtn = new MenuItem("Save Teleport Location", "Adds your current location to the teleport locations menu and saves it on the server.");
                teleportOptionsMenu.OnItemSelect += async(sender, item, index) =>
                {
                    // Teleport to waypoint.
                    if (item == tptowp)
                    {
                        TeleportToWp();
                    }
                    else if (item == tpToCoord)
                    {
                        string x = await GetUserInput("Enter X coordinate.");

                        if (string.IsNullOrEmpty(x))
                        {
                            Notify.Error(CommonErrors.InvalidInput);
                            return;
                        }
                        string y = await GetUserInput("Enter Y coordinate.");

                        if (string.IsNullOrEmpty(y))
                        {
                            Notify.Error(CommonErrors.InvalidInput);
                            return;
                        }
                        string z = await GetUserInput("Enter Z coordinate.");

                        if (string.IsNullOrEmpty(z))
                        {
                            Notify.Error(CommonErrors.InvalidInput);
                            return;
                        }

                        float posX = 0f;
                        float posY = 0f;
                        float posZ = 0f;

                        if (!float.TryParse(x, out posX))
                        {
                            if (int.TryParse(x, out int intX))
                            {
                                posX = (float)intX;
                            }
                            else
                            {
                                Notify.Error("You did not enter a valid X coordinate.");
                                return;
                            }
                        }
                        if (!float.TryParse(y, out posY))
                        {
                            if (int.TryParse(y, out int intY))
                            {
                                posY = (float)intY;
                            }
                            else
                            {
                                Notify.Error("You did not enter a valid Y coordinate.");
                                return;
                            }
                        }
                        if (!float.TryParse(z, out posZ))
                        {
                            if (int.TryParse(z, out int intZ))
                            {
                                posZ = (float)intZ;
                            }
                            else
                            {
                                Notify.Error("You did not enter a valid Z coordinate.");
                                return;
                            }
                        }

                        await TeleportToCoords(new Vector3(posX, posY, posZ), true);
                    }
                    else if (item == saveLocationBtn)
                    {
                        SavePlayerLocationToLocationsFile();
                    }
                };

                if (IsAllowed(Permission.MSTeleportToWp))
                {
                    teleportOptionsMenu.AddMenuItem(tptowp);
                    keybindMenu.AddMenuItem(kbTpToWaypoint);
                }
                if (IsAllowed(Permission.MSTeleportToCoord))
                {
                    teleportOptionsMenu.AddMenuItem(tpToCoord);
                }
                if (IsAllowed(Permission.MSTeleportLocations))
                {
                    teleportOptionsMenu.AddMenuItem(teleportMenuBtn);

                    MenuController.AddSubmenu(teleportOptionsMenu, teleportMenu);
                    MenuController.BindMenuItem(teleportOptionsMenu, teleportMenu, teleportMenuBtn);
                    teleportMenuBtn.Label = "→→→";

                    teleportMenu.OnMenuOpen += (sender) =>
                    {
                        if (teleportMenu.Size != TpLocations.Count())
                        {
                            teleportMenu.ClearMenuItems();
                            foreach (var location in TpLocations)
                            {
                                var      x       = Math.Round(location.coordinates.X, 2);
                                var      y       = Math.Round(location.coordinates.Y, 2);
                                var      z       = Math.Round(location.coordinates.Z, 2);
                                var      heading = Math.Round(location.heading, 2);
                                MenuItem tpBtn   = new MenuItem(location.name, $"Teleport to ~y~{location.name}~n~~s~x: ~y~{x}~n~~s~y: ~y~{y}~n~~s~z: ~y~{z}~n~~s~heading: ~y~{heading}")
                                {
                                    ItemData = location
                                };
                                teleportMenu.AddMenuItem(tpBtn);
                            }
                        }
                    };

                    teleportMenu.OnItemSelect += async(sender, item, index) =>
                    {
                        if (item.ItemData is vMenuShared.ConfigManager.TeleportLocation tl)
                        {
                            await TeleportToCoords(tl.coordinates, true);

                            SetEntityHeading(Game.PlayerPed.Handle, tl.heading);
                            SetGameplayCamRelativeHeading(0f);
                        }
                    };

                    if (IsAllowed(Permission.MSTeleportSaveLocation))
                    {
                        teleportOptionsMenu.AddMenuItem(saveLocationBtn);
                    }
                }
            }

            #region dev tools menu

            MenuItem devToolsBtn = new MenuItem("Developer Tools", "Various development/debug tools.")
            {
                Label = "→→→"
            };
            menu.AddMenuItem(devToolsBtn);
            MenuController.AddSubmenu(menu, developerToolsMenu);
            MenuController.BindMenuItem(menu, developerToolsMenu, devToolsBtn);

            // clear area and coordinates
            if (IsAllowed(Permission.MSClearArea))
            {
                developerToolsMenu.AddMenuItem(clearArea);
            }
            if (IsAllowed(Permission.MSShowCoordinates))
            {
                developerToolsMenu.AddMenuItem(coords);
            }

            // model outlines
            if (!vMenuShared.ConfigManager.GetSettingsBool(vMenuShared.ConfigManager.Setting.vmenu_disable_entity_outlines_tool))
            {
                developerToolsMenu.AddMenuItem(vehModelDimensions);
                developerToolsMenu.AddMenuItem(propModelDimensions);
                developerToolsMenu.AddMenuItem(pedModelDimensions);
                developerToolsMenu.AddMenuItem(showEntityHandles);
                developerToolsMenu.AddMenuItem(showEntityModels);
                developerToolsMenu.AddMenuItem(dimensionsDistanceSlider);
            }


            // timecycle modifiers
            developerToolsMenu.AddMenuItem(timeCycles);
            developerToolsMenu.AddMenuItem(enableTimeCycle);
            developerToolsMenu.AddMenuItem(timeCycleIntensity);

            developerToolsMenu.OnSliderPositionChange += (sender, item, oldPos, newPos, itemIndex) =>
            {
                if (item == timeCycleIntensity)
                {
                    ClearTimecycleModifier();
                    if (TimecycleEnabled)
                    {
                        SetTimecycleModifier(TimeCycles.Timecycles[timeCycles.ListIndex]);
                        float intensity = ((float)newPos / 20f);
                        SetTimecycleModifierStrength(intensity);
                    }
                    UserDefaults.MiscLastTimeCycleModifierIndex    = timeCycles.ListIndex;
                    UserDefaults.MiscLastTimeCycleModifierStrength = timeCycleIntensity.Position;
                }
                else if (item == dimensionsDistanceSlider)
                {
                    FunctionsController.entityRange = ((float)newPos / 20f) * 2000f; // max radius = 2000f;
                }
            };

            developerToolsMenu.OnListIndexChange += (sender, item, oldIndex, newIndex, itemIndex) =>
            {
                if (item == timeCycles)
                {
                    ClearTimecycleModifier();
                    if (TimecycleEnabled)
                    {
                        SetTimecycleModifier(TimeCycles.Timecycles[timeCycles.ListIndex]);
                        float intensity = ((float)timeCycleIntensity.Position / 20f);
                        SetTimecycleModifierStrength(intensity);
                    }
                    UserDefaults.MiscLastTimeCycleModifierIndex    = timeCycles.ListIndex;
                    UserDefaults.MiscLastTimeCycleModifierStrength = timeCycleIntensity.Position;
                }
            };

            developerToolsMenu.OnItemSelect += (sender, item, index) =>
            {
                if (item == clearArea)
                {
                    var pos = Game.PlayerPed.Position;
                    BaseScript.TriggerServerEvent("vMenu:ClearArea", pos.X, pos.Y, pos.Z);
                }
            };

            developerToolsMenu.OnCheckboxChange += (sender, item, index, _checked) =>
            {
                if (item == vehModelDimensions)
                {
                    ShowVehicleModelDimensions = _checked;
                }
                else if (item == propModelDimensions)
                {
                    ShowPropModelDimensions = _checked;
                }
                else if (item == pedModelDimensions)
                {
                    ShowPedModelDimensions = _checked;
                }
                else if (item == showEntityHandles)
                {
                    ShowEntityHandles = _checked;
                }
                else if (item == showEntityModels)
                {
                    ShowEntityModels = _checked;
                }
                else if (item == enableTimeCycle)
                {
                    TimecycleEnabled = _checked;
                    ClearTimecycleModifier();
                    if (TimecycleEnabled)
                    {
                        SetTimecycleModifier(TimeCycles.Timecycles[timeCycles.ListIndex]);
                        float intensity = ((float)timeCycleIntensity.Position / 20f);
                        SetTimecycleModifierStrength(intensity);
                    }
                }
                else if (item == coords)
                {
                    ShowCoordinates = _checked;
                }
            };

            #endregion


            // Keybind options
            if (IsAllowed(Permission.MSDriftMode))
            {
                keybindMenu.AddMenuItem(kbDriftMode);
            }
            // always allowed keybind menu options
            keybindMenu.AddMenuItem(kbRecordKeys);
            keybindMenu.AddMenuItem(kbRadarKeys);
            keybindMenu.AddMenuItem(kbPointKeysCheckbox);
            keybindMenu.AddMenuItem(backBtn);

            // Always allowed
            menu.AddMenuItem(rightAlignMenu);
            menu.AddMenuItem(disablePms);
            menu.AddMenuItem(disableControllerKey);
            menu.AddMenuItem(speedKmh);
            menu.AddMenuItem(speedMph);
            menu.AddMenuItem(keybindMenuBtn);
            keybindMenuBtn.Label = "→→→";
            if (IsAllowed(Permission.MSConnectionMenu))
            {
                menu.AddMenuItem(connectionSubmenuBtn);
                connectionSubmenuBtn.Label = "→→→";
            }
            if (IsAllowed(Permission.MSShowLocation))
            {
                menu.AddMenuItem(showLocation);
            }
            menu.AddMenuItem(drawTime); // always allowed
            if (IsAllowed(Permission.MSJoinQuitNotifs))
            {
                menu.AddMenuItem(deathNotifs);
            }
            if (IsAllowed(Permission.MSDeathNotifs))
            {
                menu.AddMenuItem(joinQuitNotifs);
            }
            if (IsAllowed(Permission.MSNightVision))
            {
                menu.AddMenuItem(nightVision);
            }
            if (IsAllowed(Permission.MSThermalVision))
            {
                menu.AddMenuItem(thermalVision);
            }
            if (IsAllowed(Permission.MSLocationBlips))
            {
                menu.AddMenuItem(locationBlips);
                ToggleBlips(ShowLocationBlips);
            }
            if (IsAllowed(Permission.MSPlayerBlips))
            {
                menu.AddMenuItem(playerBlips);
            }
            if (IsAllowed(Permission.MSOverheadNames))
            {
                menu.AddMenuItem(playerNames);
            }
            // always allowed, it just won't do anything if the server owner disabled the feature, but players can still toggle it.
            menu.AddMenuItem(respawnDefaultCharacter);
            if (IsAllowed(Permission.MSRestoreAppearance))
            {
                menu.AddMenuItem(restorePlayerAppearance);
            }
            if (IsAllowed(Permission.MSRestoreWeapons))
            {
                menu.AddMenuItem(restorePlayerWeapons);
            }

            // Always allowed
            menu.AddMenuItem(hideRadar);
            menu.AddMenuItem(hideHud);
            menu.AddMenuItem(lockCamX);
            menu.AddMenuItem(lockCamY);
            menu.AddMenuItem(exportData);
            menu.AddMenuItem(saveSettings);

            // Handle checkbox changes.
            menu.OnCheckboxChange += (sender, item, index, _checked) =>
            {
                if (item == rightAlignMenu)
                {
                    MenuController.MenuAlignment    = _checked ? MenuController.MenuAlignmentOption.Right : MenuController.MenuAlignmentOption.Left;
                    MiscRightAlignMenu              = _checked;
                    UserDefaults.MiscRightAlignMenu = MiscRightAlignMenu;

                    if (MenuController.MenuAlignment != (_checked ? MenuController.MenuAlignmentOption.Right : MenuController.MenuAlignmentOption.Left))
                    {
                        Notify.Error(CommonErrors.RightAlignedNotSupported);
                        // (re)set the default to left just in case so they don't get this error again in the future.
                        MenuController.MenuAlignment    = MenuController.MenuAlignmentOption.Left;
                        MiscRightAlignMenu              = false;
                        UserDefaults.MiscRightAlignMenu = false;
                    }
                }
                else if (item == disablePms)
                {
                    MiscDisablePrivateMessages = _checked;
                }
                else if (item == disableControllerKey)
                {
                    MiscDisableControllerSupport = _checked;
                    MenuController.EnableMenuToggleKeyOnController = !_checked;
                }
                else if (item == speedKmh)
                {
                    ShowSpeedoKmh = _checked;
                }
                else if (item == speedMph)
                {
                    ShowSpeedoMph = _checked;
                }
                else if (item == hideHud)
                {
                    HideHud = _checked;
                    DisplayHud(!_checked);
                }
                else if (item == hideRadar)
                {
                    HideRadar = _checked;
                    if (!_checked)
                    {
                        DisplayRadar(true);
                    }
                }
                else if (item == showLocation)
                {
                    ShowLocation = _checked;
                }
                else if (item == drawTime)
                {
                    DrawTimeOnScreen = _checked;
                }
                else if (item == deathNotifs)
                {
                    DeathNotifications = _checked;
                }
                else if (item == joinQuitNotifs)
                {
                    JoinQuitNotifications = _checked;
                }
                else if (item == nightVision)
                {
                    SetNightvision(_checked);
                }
                else if (item == thermalVision)
                {
                    SetSeethrough(_checked);
                }
                else if (item == lockCamX)
                {
                    LockCameraX = _checked;
                }
                else if (item == lockCamY)
                {
                    LockCameraY = _checked;
                }
                else if (item == locationBlips)
                {
                    ToggleBlips(_checked);
                    ShowLocationBlips = _checked;
                }
                else if (item == playerBlips)
                {
                    ShowPlayerBlips = _checked;
                }
                else if (item == playerNames)
                {
                    MiscShowOverheadNames = _checked;
                }
                else if (item == respawnDefaultCharacter)
                {
                    MiscRespawnDefaultCharacter = _checked;
                }
                else if (item == restorePlayerAppearance)
                {
                    RestorePlayerAppearance = _checked;
                }
                else if (item == restorePlayerWeapons)
                {
                    RestorePlayerWeapons = _checked;
                }
            };

            // Handle button presses.
            menu.OnItemSelect += (sender, item, index) =>
            {
                // export data
                if (item == exportData)
                {
                    var vehicles       = GetSavedVehicles();
                    var normalPeds     = StorageManager.GetSavedPeds();
                    var mpPeds         = StorageManager.GetSavedMpPeds();
                    var weaponLoadouts = WeaponLoadouts.GetSavedWeapons();
                    //SetNuiFocus(true, true);
                    //SendNuiMessage(JsonConvert.SerializeObject(new
                    //var data = JsonConvert.SerializeObject(new
                    //{
                    //    saved_vehicles = vehicles,
                    //    normal_peds = normalPeds,
                    //    mp_characters = mpPeds,
                    //    weapon_loadouts = weaponLoadouts
                    //});
                    //Debug.WriteLine(data.Length + "\n" + data);
                    //TriggerServerEvent("test", data);
                }
                // save settings
                else if (item == saveSettings)
                {
                    UserDefaults.SaveSettings();
                }
            };
        }
示例#16
0
        /// <summary>
        /// Manage all vehicle related tasks.
        /// </summary>
        /// <returns></returns>
        private async Task VehicleOptions()
        {
            // Vehicle options. Only run vehicle options if the vehicle options menu has actually been created.
            if (MainMenu.VehicleOptionsMenu != null && cf.IsAllowed(Permission.VOMenu))
            {
                // When the player is in a valid vehicle:
                if (DoesEntityExist(cf.GetVehicle()))
                {
                    // Create a new vehicle object.
                    Vehicle vehicle = new Vehicle(cf.GetVehicle());

                    // God mode
                    bool god = MainMenu.VehicleOptionsMenu.VehicleGodMode && cf.IsAllowed(Permission.VOGod);
                    vehicle.CanBeVisiblyDamaged = !god;
                    vehicle.CanEngineDegrade    = !god;
                    vehicle.CanTiresBurst       = !god;
                    vehicle.CanWheelsBreak      = !god;
                    vehicle.IsAxlesStrong       = god;
                    vehicle.IsBulletProof       = god;
                    vehicle.IsCollisionProof    = god;
                    vehicle.IsExplosionProof    = god;
                    vehicle.IsFireProof         = god;
                    vehicle.IsInvincible        = god;
                    vehicle.IsMeleeProof        = god;
                    foreach (VehicleDoor vd in vehicle.Doors.GetAll())
                    {
                        vd.CanBeBroken = !god;
                    }
                    bool specialgod = MainMenu.VehicleOptionsMenu.VehicleSpecialGodMode && cf.IsAllowed(Permission.VOSpecialGod);
                    if (specialgod && vehicle.EngineHealth < 1000)
                    {
                        vehicle.Repair(); // repair vehicle if special god mode is on and the vehicle is not full health.
                    }

                    // Freeze Vehicle Position (if enabled).
                    if (MainMenu.VehicleOptionsMenu.VehicleFrozen && cf.IsAllowed(Permission.VOFreeze))
                    {
                        FreezeEntityPosition(vehicle.Handle, true);
                    }


                    // If the torque multiplier is enabled and the player is allowed to use it.
                    if (MainMenu.VehicleOptionsMenu.VehicleTorqueMultiplier && cf.IsAllowed(Permission.VOTorqueMultiplier))
                    {
                        // Set the torque multiplier to the selected value by the player.
                        // no need for an "else" to reset this value, because when it's not called every frame, nothing happens.
                        SetVehicleEngineTorqueMultiplier(vehicle.Handle, MainMenu.VehicleOptionsMenu.VehicleTorqueMultiplierAmount);
                    }
                    // If the player has switched to a new vehicle, and the vehicle engine power multiplier is turned on. Set the new value.
                    if (SwitchedVehicle)
                    {
                        // Only needs to be set once.
                        SwitchedVehicle = false;

                        // Vehicle engine power multiplier. Enable it once the player switched vehicles.
                        // Only do this if the option is enabled AND the player has permissions for it.
                        if (MainMenu.VehicleOptionsMenu.VehiclePowerMultiplier && cf.IsAllowed(Permission.VOPowerMultiplier))
                        {
                            SetVehicleEnginePowerMultiplier(vehicle.Handle, MainMenu.VehicleOptionsMenu.VehiclePowerMultiplierAmount);
                        }
                        // If the player switched vehicles and the option is turned off or the player has no permissions for it
                        // Then reset the power multiplier ONCE.
                        else
                        {
                            SetVehicleEnginePowerMultiplier(vehicle.Handle, 1f);
                        }

                        // No Siren Toggle
                        vehicle.IsSirenSilent = MainMenu.VehicleOptionsMenu.VehicleNoSiren && cf.IsAllowed(Permission.VONoSiren);
                    }

                    // Manage "no helmet"
                    var ped = new Ped(PlayerPedId());
                    // If the no helmet feature is turned on, disalbe "ped can wear helmet"
                    if (MainMenu.VehicleOptionsMenu.VehicleNoBikeHelemet && cf.IsAllowed(Permission.VONoHelmet))
                    {
                        ped.CanWearHelmet = false;
                    }
                    // otherwise, allow helmets.
                    else if (!MainMenu.VehicleOptionsMenu.VehicleNoBikeHelemet || !cf.IsAllowed(Permission.VONoHelmet))
                    {
                        ped.CanWearHelmet = true;
                    }
                    // If the player is still wearing a helmet, even if the option is set to: no helmet, then remove the helmet.
                    if (ped.IsWearingHelmet && MainMenu.VehicleOptionsMenu.VehicleNoBikeHelemet && cf.IsAllowed(Permission.VONoHelmet))
                    {
                        ped.RemoveHelmet(true);
                    }

                    if (MainMenu.VehicleOptionsMenu.FlashHighbeamsOnHonk && vehicle.Driver == Game.PlayerPed && !IsPauseMenuActive())
                    {
                        // turn on high beams when honking.
                        if (Game.IsControlPressed(0, Control.VehicleHorn))
                        {
                            vehicle.AreHighBeamsOn = true;
                        }
                        // turn high beams back off when just stopped honking.
                        if (Game.IsControlJustReleased(0, Control.VehicleHorn))
                        {
                            vehicle.AreHighBeamsOn = false;
                        }
                    }
                }
                // When the player is not inside a vehicle:
                else
                {
                    UIMenu[] vehicleSubmenus = new UIMenu[6];
                    vehicleSubmenus[0] = MainMenu.VehicleOptionsMenu.VehicleModMenu;
                    vehicleSubmenus[1] = MainMenu.VehicleOptionsMenu.VehicleLiveriesMenu;
                    vehicleSubmenus[2] = MainMenu.VehicleOptionsMenu.VehicleColorsMenu;
                    vehicleSubmenus[3] = MainMenu.VehicleOptionsMenu.VehicleDoorsMenu;
                    vehicleSubmenus[4] = MainMenu.VehicleOptionsMenu.VehicleWindowsMenu;
                    vehicleSubmenus[5] = MainMenu.VehicleOptionsMenu.VehicleComponentsMenu;
                    foreach (UIMenu m in vehicleSubmenus)
                    {
                        if (m.Visible)
                        {
                            MainMenu.VehicleOptionsMenu.GetMenu().Visible = true;
                            m.Visible = false;
                            Notify.Error(CommonErrors.NoVehicle, placeholderValue: "to access this menu");
                        }
                    }
                }

                // Manage vehicle engine always on.
                if ((MainMenu.VehicleOptionsMenu.VehicleEngineAlwaysOn && DoesEntityExist(cf.GetVehicle(lastVehicle: true)) &&
                     !IsPedInAnyVehicle(PlayerPedId(), false)) && (cf.IsAllowed(Permission.VOEngineAlwaysOn)))
                {
                    await Delay(100);

                    SetVehicleEngineOn(cf.GetVehicle(lastVehicle: true), true, true, true);
                }
            }
            else
            {
                await Delay(0);
            }
        }
示例#17
0
        /// <summary>
        /// Creates the menu.
        /// </summary>
        private void CreateMenu()
        {
            string menuTitle = "Saved Vehicles";

            #region Create menus and submenus
            // Create the menu.
            menu = new Menu(menuTitle, "Manage Saved Vehicles");

            MenuItem saveVehicle = new MenuItem("Save Current Vehicle", "Save the vehicle you are currently sitting in.");
            menu.AddMenuItem(saveVehicle);
            saveVehicle.LeftIcon = MenuItem.Icon.CAR;

            menu.OnItemSelect += (sender, item, index) =>
            {
                if (item == saveVehicle)
                {
                    if (Game.PlayerPed.IsInVehicle())
                    {
                        SaveVehicle();
                    }
                    else
                    {
                        Notify.Error("You are currently not in any vehicle. Please enter a vehicle before trying to save it.");
                    }
                }
            };


            for (int i = 0; i < 22; i++)
            {
                Menu categoryMenu = new Menu("Saved Vehicles", GetLabelText($"VEH_CLASS_{i}"));

                MenuItem categoryButton = new MenuItem(GetLabelText($"VEH_CLASS_{i}"), $"All saved vehicles from the {(GetLabelText($"VEH_CLASS_{i}"))} category.");
                subMenus.Add(categoryMenu);
                MenuController.AddSubmenu(menu, categoryMenu);
                menu.AddMenuItem(categoryButton);
                categoryButton.Label = "→→→";
                MenuController.BindMenuItem(menu, categoryMenu, categoryButton);

                categoryMenu.OnMenuClose += (sender) =>
                {
                    UpdateMenuAvailableCategories();
                };

                categoryMenu.OnItemSelect += (sender, item, index) =>
                {
                    UpdateSelectedVehicleMenu(item, sender);
                };
            }

            MenuItem unavailableModels = new MenuItem("Unavailable Saved Vehicles", "These vehicles are currently unavailable because the models are not present in the game. These vehicles are most likely not being streamed from the server.");

            unavailableModels.Label = "→→→";

            menu.AddMenuItem(unavailableModels);
            MenuController.BindMenuItem(menu, unavailableVehiclesMenu, unavailableModels);
            MenuController.AddSubmenu(menu, unavailableVehiclesMenu);


            MenuController.AddMenu(selectedVehicleMenu);
            MenuItem spawnVehicle   = new MenuItem("Spawn Vehicle", "Spawn this saved vehicle.");
            MenuItem renameVehicle  = new MenuItem("Rename Vehicle", "Rename your saved vehicle.");
            MenuItem replaceVehicle = new MenuItem("~r~Replace Vehicle", "Your saved vehicle will be replaced with the vehicle you are currently sitting in. ~r~Warning: this can NOT be undone!");
            MenuItem deleteVehicle  = new MenuItem("~r~Delete Vehicle", "~r~This will delete your saved vehicle. Warning: this can NOT be undone!");
            selectedVehicleMenu.AddMenuItem(spawnVehicle);
            selectedVehicleMenu.AddMenuItem(renameVehicle);
            selectedVehicleMenu.AddMenuItem(replaceVehicle);
            selectedVehicleMenu.AddMenuItem(deleteVehicle);

            selectedVehicleMenu.OnMenuClose += (sender) =>
            {
                selectedVehicleMenu.RefreshIndex();
                deleteButtonPressedCount = 0;
                deleteVehicle.Label      = "";
            };

            selectedVehicleMenu.OnItemSelect += async(sender, item, index) =>
            {
                if (item == spawnVehicle)
                {
                    if (MainMenu.VehicleSpawnerMenu != null)
                    {
                        SpawnVehicle(currentlySelectedVehicle.Value.model, MainMenu.VehicleSpawnerMenu.SpawnInVehicle, MainMenu.VehicleSpawnerMenu.ReplaceVehicle, false, vehicleInfo: currentlySelectedVehicle.Value, saveName: currentlySelectedVehicle.Key.Substring(4));
                    }
                    else
                    {
                        SpawnVehicle(currentlySelectedVehicle.Value.model, true, true, false, vehicleInfo: currentlySelectedVehicle.Value, saveName: currentlySelectedVehicle.Key.Substring(4));
                    }
                }
                else if (item == renameVehicle)
                {
                    string newName = await GetUserInput(windowTitle : "Enter a new name for this vehicle.", maxInputLength : 30);

                    if (string.IsNullOrEmpty(newName))
                    {
                        Notify.Error(CommonErrors.InvalidInput);
                    }
                    else
                    {
                        if (StorageManager.SaveVehicleInfo("veh_" + newName, currentlySelectedVehicle.Value, false))
                        {
                            DeleteResourceKvp(currentlySelectedVehicle.Key);
                            while (!selectedVehicleMenu.Visible)
                            {
                                await BaseScript.Delay(0);
                            }
                            Notify.Success("Your vehicle has successfully been renamed.");
                            UpdateMenuAvailableCategories();
                            selectedVehicleMenu.GoBack();
                            currentlySelectedVehicle = new KeyValuePair <string, VehicleInfo>(); // clear the old info
                        }
                        else
                        {
                            Notify.Error("This name is already in use or something unknown failed. Contact the server owner if you believe something is wrong.");
                        }
                    }
                }
                else if (item == replaceVehicle)
                {
                    if (Game.PlayerPed.IsInVehicle())
                    {
                        SaveVehicle(currentlySelectedVehicle.Key.Substring(4));
                        selectedVehicleMenu.GoBack();
                        Notify.Success("Your saved vehicle has been replaced with your current vehicle.");
                    }
                    else
                    {
                        Notify.Error("You need to be in a vehicle before you can relplace your old vehicle.");
                    }
                }
                else if (item == deleteVehicle)
                {
                    if (deleteButtonPressedCount == 0)
                    {
                        deleteButtonPressedCount = 1;
                        item.Label = "Press again to confirm.";
                        Notify.Alert("Are you sure you want to delete this vehicle? Press the button again to confirm.");
                    }
                    else
                    {
                        deleteButtonPressedCount = 0;
                        item.Label = "";
                        DeleteResourceKvp(currentlySelectedVehicle.Key);
                        UpdateMenuAvailableCategories();
                        selectedVehicleMenu.GoBack();
                        Notify.Success("Your saved vehicle has been deleted.");
                    }
                }
                if (item != deleteVehicle) // if any other button is pressed, restore the delete vehicle button pressed count.
                {
                    deleteButtonPressedCount = 0;
                    deleteVehicle.Label      = "";
                }
            };

            #endregion
        }
示例#18
0
        /// <summary>
        /// Creates the menu.
        /// </summary>
        private void CreateMenu()
        {
            // Menu
            menu = new Menu(GetSafePlayerName(Game.Player.Name), "車輛管理");

            // menu items
            MenuItem setVehice = new MenuItem("設定擁有載具", "Sets your current vehicle as your personal vehicle. If you already have a personal vehicle set then this will override your selection.")
            {
                Label = "Current Vehicle: None"
            };
            MenuItem     toggleEngine = new MenuItem("啟動引勤", "Toggles the engine on or off, even when you're not inside of the vehicle. This does not work if someone else is currently using your vehicle.");
            MenuListItem toggleLights = new MenuListItem("設定車燈", new List <string>()
            {
                "Force On", "Force Off", "Reset"
            }, 0, "This will enable or disable your vehicle headlights, the engine of your vehicle needs to be running for this to work.");
            MenuItem kickAllPassengers = new MenuItem("踢除乘客", "This will remove all passengers from your personal vehicle.");
            //MenuItem
            MenuItem lockDoors    = new MenuItem("鎖上車門", "This will lock all your vehicle doors for all players. Anyone already inside will always be able to leave the vehicle, even if the doors are locked.");
            MenuItem unlockDoors  = new MenuItem("解鎖車門", "This will unlock all your vehicle doors for all players.");
            MenuItem doorsMenuBtn = new MenuItem("車門", "Open, close, remove and restore vehicle doors here.")
            {
                Label = "→→→"
            };
            MenuItem         soundHorn   = new MenuItem("喇叭", "Sounds the horn of the vehicle.");
            MenuItem         toggleAlarm = new MenuItem("切換喇叭音效", "Toggles the vehicle alarm sound on or off. This does not set an alarm. It only toggles the current sounding status of the alarm.");
            MenuCheckboxItem enableBlip  = new MenuCheckboxItem("Add Blip For Personal Vehicle", "Enables or disables the blip that gets added when you mark a vehicle as your personal vehicle.", EnableVehicleBlip)
            {
                Style = MenuCheckboxItem.CheckboxStyle.Cross
            };
            MenuCheckboxItem exclusiveDriver = new MenuCheckboxItem("Exclusive Driver", "If enabled, then you will be the only one that can enter the drivers seat. Other players will not be able to drive the car. They can still be passengers.", false)
            {
                Style = MenuCheckboxItem.CheckboxStyle.Cross
            };

            //submenu
            VehicleDoorsMenu = new Menu("車門", "Vehicle Doors Management");
            MenuController.AddSubmenu(menu, VehicleDoorsMenu);
            MenuController.BindMenuItem(menu, VehicleDoorsMenu, doorsMenuBtn);

            // This is always allowed if this submenu is created/allowed.
            menu.AddMenuItem(setVehice);

            // Add conditional features.

            // Toggle engine.
            if (IsAllowed(Permission.PVToggleEngine))
            {
                menu.AddMenuItem(toggleEngine);
            }

            // Toggle lights
            if (IsAllowed(Permission.PVToggleLights))
            {
                menu.AddMenuItem(toggleLights);
            }

            // Kick vehicle passengers
            if (IsAllowed(Permission.PVKickPassengers))
            {
                menu.AddMenuItem(kickAllPassengers);
            }

            // Lock and unlock vehicle doors
            if (IsAllowed(Permission.PVLockDoors))
            {
                menu.AddMenuItem(lockDoors);
                menu.AddMenuItem(unlockDoors);
            }

            if (IsAllowed(Permission.PVDoors))
            {
                menu.AddMenuItem(doorsMenuBtn);
            }

            // Sound horn
            if (IsAllowed(Permission.PVSoundHorn))
            {
                menu.AddMenuItem(soundHorn);
            }

            // Toggle alarm sound
            if (IsAllowed(Permission.PVToggleAlarm))
            {
                menu.AddMenuItem(toggleAlarm);
            }

            // Enable blip for personal vehicle
            if (IsAllowed(Permission.PVAddBlip))
            {
                menu.AddMenuItem(enableBlip);
            }

            if (IsAllowed(Permission.PVExclusiveDriver))
            {
                menu.AddMenuItem(exclusiveDriver);
            }


            // Handle list presses
            menu.OnListItemSelect += (sender, item, itemIndex, index) =>
            {
                var veh = CurrentPersonalVehicle;
                if (veh != null && veh.Exists())
                {
                    if (!NetworkHasControlOfEntity(CurrentPersonalVehicle.Handle))
                    {
                        if (!NetworkRequestControlOfEntity(CurrentPersonalVehicle.Handle))
                        {
                            Notify.Error("You currently can't control this vehicle. Is someone else currently driving your car? Please try again after making sure other players are not controlling your vehicle.");
                            return;
                        }
                    }

                    if (item == toggleLights)
                    {
                        PressKeyFob(CurrentPersonalVehicle);
                        if (itemIndex == 0)
                        {
                            SetVehicleLights(CurrentPersonalVehicle.Handle, 3);
                        }
                        else if (itemIndex == 1)
                        {
                            SetVehicleLights(CurrentPersonalVehicle.Handle, 1);
                        }
                        else
                        {
                            SetVehicleLights(CurrentPersonalVehicle.Handle, 0);
                        }
                    }
                }
                else
                {
                    Notify.Error("You have not yet selected a personal vehicle, or your vehicle has been deleted. Set a personal vehicle before you can use these options.");
                }
            };

            // Handle checkbox changes
            menu.OnCheckboxChange += (sender, item, index, _checked) =>
            {
                if (item == enableBlip)
                {
                    EnableVehicleBlip = _checked;
                    if (EnableVehicleBlip)
                    {
                        if (CurrentPersonalVehicle != null && CurrentPersonalVehicle.Exists())
                        {
                            if (CurrentPersonalVehicle.AttachedBlip == null || !CurrentPersonalVehicle.AttachedBlip.Exists())
                            {
                                CurrentPersonalVehicle.AttachBlip();
                            }
                            CurrentPersonalVehicle.AttachedBlip.Sprite = BlipSprite.PersonalVehicleCar;
                            CurrentPersonalVehicle.AttachedBlip.Name   = "Personal Vehicle";
                        }
                        else
                        {
                            Notify.Error("You have not yet selected a personal vehicle, or your vehicle has been deleted. Set a personal vehicle before you can use these options.");
                        }
                    }
                    else
                    {
                        if (CurrentPersonalVehicle != null && CurrentPersonalVehicle.Exists() && CurrentPersonalVehicle.AttachedBlip != null && CurrentPersonalVehicle.AttachedBlip.Exists())
                        {
                            CurrentPersonalVehicle.AttachedBlip.Delete();
                        }
                    }
                }
                else if (item == exclusiveDriver)
                {
                    if (CurrentPersonalVehicle != null && CurrentPersonalVehicle.Exists())
                    {
                        if (NetworkRequestControlOfEntity(CurrentPersonalVehicle.Handle))
                        {
                            if (_checked)
                            {
                                SetVehicleExclusiveDriver(CurrentPersonalVehicle.Handle, Game.PlayerPed.Handle);
                                SetVehicleExclusiveDriver_2(CurrentPersonalVehicle.Handle, Game.PlayerPed.Handle, 1);
                            }
                            else
                            {
                                SetVehicleExclusiveDriver(CurrentPersonalVehicle.Handle, 0);
                                SetVehicleExclusiveDriver_2(CurrentPersonalVehicle.Handle, 0, 1);
                            }
                        }
                        else
                        {
                            item.Checked = !_checked;
                            Notify.Error("You currently can't control this vehicle. Is someone else currently driving your car? Please try again after making sure other players are not controlling your vehicle.");
                        }
                    }
                }
            };

            // Handle button presses.
            menu.OnItemSelect += (sender, item, index) =>
            {
                if (item == setVehice)
                {
                    if (Game.PlayerPed.IsInVehicle())
                    {
                        var veh = GetVehicle();
                        if (veh != null && veh.Exists())
                        {
                            if (Game.PlayerPed == veh.Driver)
                            {
                                CurrentPersonalVehicle      = veh;
                                veh.PreviouslyOwnedByPlayer = true;
                                veh.IsPersistent            = true;
                                if (EnableVehicleBlip && IsAllowed(Permission.PVAddBlip))
                                {
                                    if (veh.AttachedBlip == null || !veh.AttachedBlip.Exists())
                                    {
                                        veh.AttachBlip();
                                    }
                                    veh.AttachedBlip.Sprite = BlipSprite.PersonalVehicleCar;
                                    veh.AttachedBlip.Name   = "Personal Vehicle";
                                }
                                var name = GetLabelText(veh.DisplayName);
                                if (string.IsNullOrEmpty(name) || name.ToLower() == "null")
                                {
                                    name = veh.DisplayName;
                                }
                                item.Label = $"Current Vehicle: {name}";
                            }
                            else
                            {
                                Notify.Error(CommonErrors.NeedToBeTheDriver);
                            }
                        }
                        else
                        {
                            Notify.Error(CommonErrors.NoVehicle);
                        }
                    }
                    else
                    {
                        Notify.Error(CommonErrors.NoVehicle);
                    }
                }
                else if (CurrentPersonalVehicle != null && CurrentPersonalVehicle.Exists())
                {
                    if (item == kickAllPassengers)
                    {
                        if (CurrentPersonalVehicle.Occupants.Count() > 0 && CurrentPersonalVehicle.Occupants.Any(p => p != Game.PlayerPed))
                        {
                            var netId = VehToNet(CurrentPersonalVehicle.Handle);
                            TriggerServerEvent("vMenu:GetOutOfCar", netId, Game.Player.ServerId);
                        }
                        else
                        {
                            Notify.Info("There are no other players in your vehicle that need to be kicked out.");
                        }
                    }
                    else
                    {
                        if (!NetworkHasControlOfEntity(CurrentPersonalVehicle.Handle))
                        {
                            if (!NetworkRequestControlOfEntity(CurrentPersonalVehicle.Handle))
                            {
                                Notify.Error("You currently can't control this vehicle. Is someone else currently driving your car? Please try again after making sure other players are not controlling your vehicle.");
                                return;
                            }
                        }

                        if (item == toggleEngine)
                        {
                            PressKeyFob(CurrentPersonalVehicle);
                            SetVehicleEngineOn(CurrentPersonalVehicle.Handle, !CurrentPersonalVehicle.IsEngineRunning, true, true);
                        }

                        else if (item == lockDoors || item == unlockDoors)
                        {
                            PressKeyFob(CurrentPersonalVehicle);
                            bool _lock = item == lockDoors;
                            LockOrUnlockDoors(CurrentPersonalVehicle, _lock);
                        }

                        else if (item == soundHorn)
                        {
                            PressKeyFob(CurrentPersonalVehicle);
                            SoundHorn(CurrentPersonalVehicle);
                        }

                        else if (item == toggleAlarm)
                        {
                            PressKeyFob(CurrentPersonalVehicle);
                            ToggleVehicleAlarm(CurrentPersonalVehicle);
                        }
                    }
                }
                else
                {
                    Notify.Error("You have not yet selected a personal vehicle, or your vehicle has been deleted. Set a personal vehicle before you can use these options.");
                }
            };

            #region Doors submenu
            MenuItem openAll  = new MenuItem("Open All Doors", "Open all vehicle doors.");
            MenuItem closeAll = new MenuItem("Close All Doors", "Close all vehicle doors.");
            MenuItem LF       = new MenuItem("Left Front Door", "Open/close the left front door.");
            MenuItem RF       = new MenuItem("Right Front Door", "Open/close the right front door.");
            MenuItem LR       = new MenuItem("Left Rear Door", "Open/close the left rear door.");
            MenuItem RR       = new MenuItem("Right Rear Door", "Open/close the right rear door.");
            MenuItem HD       = new MenuItem("Hood", "Open/close the hood.");
            MenuItem TR       = new MenuItem("Trunk", "Open/close the trunk.");
            MenuItem E1       = new MenuItem("Extra 1", "Open/close the extra door (#1). Note this door is not present on most vehicles.");
            MenuItem E2       = new MenuItem("Extra 2", "Open/close the extra door (#2). Note this door is not present on most vehicles.");
            MenuItem BB       = new MenuItem("Bomb Bay", "Open/close the bomb bay. Only available on some planes.");
            var      doors    = new List <string>()
            {
                "Front Left", "Front Right", "Rear Left", "Rear Right", "Hood", "Trunk", "Extra 1", "Extra 2", "Bomb Bay"
            };
            MenuListItem     removeDoorList = new MenuListItem("Remove Door", doors, 0, "Remove a specific vehicle door completely.");
            MenuCheckboxItem deleteDoors    = new MenuCheckboxItem("Delete Removed Doors", "When enabled, doors that you remove using the list above will be deleted from the world. If disabled, then the doors will just fall on the ground.", false);

            VehicleDoorsMenu.AddMenuItem(LF);
            VehicleDoorsMenu.AddMenuItem(RF);
            VehicleDoorsMenu.AddMenuItem(LR);
            VehicleDoorsMenu.AddMenuItem(RR);
            VehicleDoorsMenu.AddMenuItem(HD);
            VehicleDoorsMenu.AddMenuItem(TR);
            VehicleDoorsMenu.AddMenuItem(E1);
            VehicleDoorsMenu.AddMenuItem(E2);
            VehicleDoorsMenu.AddMenuItem(BB);
            VehicleDoorsMenu.AddMenuItem(openAll);
            VehicleDoorsMenu.AddMenuItem(closeAll);
            VehicleDoorsMenu.AddMenuItem(removeDoorList);
            VehicleDoorsMenu.AddMenuItem(deleteDoors);

            VehicleDoorsMenu.OnListItemSelect += (sender, item, index, itemIndex) =>
            {
                Vehicle veh = CurrentPersonalVehicle;
                if (veh != null && veh.Exists())
                {
                    if (!NetworkHasControlOfEntity(CurrentPersonalVehicle.Handle))
                    {
                        if (!NetworkRequestControlOfEntity(CurrentPersonalVehicle.Handle))
                        {
                            Notify.Error("You currently can't control this vehicle. Is someone else currently driving your car? Please try again after making sure other players are not controlling your vehicle.");
                            return;
                        }
                    }

                    if (item == removeDoorList)
                    {
                        PressKeyFob(veh);
                        SetVehicleDoorBroken(veh.Handle, index, deleteDoors.Checked);
                    }
                }
            };

            VehicleDoorsMenu.OnItemSelect += (sender, item, index) =>
            {
                Vehicle veh = CurrentPersonalVehicle;
                if (veh != null && veh.Exists() && !veh.IsDead)
                {
                    if (!NetworkHasControlOfEntity(CurrentPersonalVehicle.Handle))
                    {
                        if (!NetworkRequestControlOfEntity(CurrentPersonalVehicle.Handle))
                        {
                            Notify.Error("You currently can't control this vehicle. Is someone else currently driving your car? Please try again after making sure other players are not controlling your vehicle.");
                            return;
                        }
                    }

                    if (index < 8)
                    {
                        bool open = GetVehicleDoorAngleRatio(veh.Handle, index) > 0.1f;
                        PressKeyFob(veh);
                        if (open)
                        {
                            SetVehicleDoorShut(veh.Handle, index, false);
                        }
                        else
                        {
                            SetVehicleDoorOpen(veh.Handle, index, false, false);
                        }
                    }
                    else if (item == openAll)
                    {
                        PressKeyFob(veh);
                        for (var door = 0; door < 8; door++)
                        {
                            SetVehicleDoorOpen(veh.Handle, door, false, false);
                        }
                    }
                    else if (item == closeAll)
                    {
                        PressKeyFob(veh);
                        for (var door = 0; door < 8; door++)
                        {
                            SetVehicleDoorShut(veh.Handle, door, false);
                        }
                    }
                    else if (item == BB && veh.HasBombBay)
                    {
                        PressKeyFob(veh);
                        bool bombBayOpen = AreBombBayDoorsOpen(veh.Handle);
                        if (bombBayOpen)
                        {
                            veh.CloseBombBay();
                        }
                        else
                        {
                            veh.OpenBombBay();
                        }
                    }
                    else
                    {
                        Notify.Error("You have not yet selected a personal vehicle, or your vehicle has been deleted. Set a personal vehicle before you can use these options.");
                    }
                }
            };
            #endregion
        }
示例#19
0
        /// <summary>
        /// Creates the menu(s).
        /// </summary>
        private void CreateMenu()
        {
            // Create the menu.
            menu = new Menu(Game.Player.Name, "Player Appearance");
            spawnSavedPedMenu    = new Menu("Saved Peds", "Spawn Saved Ped");
            deleteSavedPedMenu   = new Menu("Saved Peds", "Delete Saved Ped");
            pedCustomizationMenu = new Menu("Ped Customization", "Customize Saved Ped");

            // Add the (submenus) to the menu pool.
            MenuController.AddSubmenu(menu, pedCustomizationMenu);
            MenuController.AddSubmenu(menu, spawnSavedPedMenu);
            MenuController.AddSubmenu(menu, deleteSavedPedMenu);

            // Create the menu items.
            MenuItem pedCustomization = new MenuItem("Ped Customization", "Modify your ped's appearance.")
            {
                Label = "→→→"
            };
            MenuItem savePed = new MenuItem("Save Current Ped", "Save your current ped and clothes.")
            {
                RightIcon = MenuItem.Icon.TICK
            };
            MenuItem spawnSavedPed = new MenuItem("Spawn Saved Ped", "Spawn one of your saved peds.")
            {
                Label = "→→→"
            };
            MenuItem deleteSavedPed = new MenuItem("Delete Saved Ped", "Delete one of your saved peds.")
            {
                Label    = "→→→",
                LeftIcon = MenuItem.Icon.WARNING
            };
            MenuItem      spawnByName = new MenuItem("Spawn Ped By Name", "Enter a model name of a custom ped you want to spawn.");
            List <string> walkstyles  = new List <string>()
            {
                "Normal", "Injured", "Tough Guy", "Femme", "Gangster", "Posh", "Sexy", "Business", "Drunk", "Hipster"
            };
            MenuListItem walkingStyle = new MenuListItem("Walking Style", walkstyles, 0, "Change the walking style of your current ped. " +
                                                         "You need to re-apply this each time you change player model or load a saved ped.");
            List <string> clothingGlowAnimations = new List <string>()
            {
                "On", "Off", "Fade", "Flash"
            };
            MenuListItem clothingGlowType = new MenuListItem("Illuminated Clothing Style", clothingGlowAnimations, ClothingAnimationType, "Set the style of the animation used on your player's illuminated clothing items.");

            // Add items to the menu.
            menu.AddMenuItem(pedCustomization);
            menu.AddMenuItem(savePed);
            menu.AddMenuItem(spawnSavedPed);
            menu.AddMenuItem(deleteSavedPed);
            menu.AddMenuItem(walkingStyle);
            menu.AddMenuItem(clothingGlowType);

            if (IsAllowed(Permission.PACustomize))
            {
                MenuController.BindMenuItem(menu, pedCustomizationMenu, pedCustomization);
            }
            else
            {
                pedCustomization.Enabled     = false;
                pedCustomization.LeftIcon    = MenuItem.Icon.LOCK;
                pedCustomization.Description = "~r~This option has been disabled by the server owner.";
            }

            if (IsAllowed(Permission.PASpawnSaved))
            {
                MenuController.BindMenuItem(menu, spawnSavedPedMenu, spawnSavedPed);
            }
            else
            {
                spawnSavedPed.Enabled     = false;
                spawnSavedPed.LeftIcon    = MenuItem.Icon.LOCK;
                spawnSavedPed.Description = "~r~This option has been disabled by the server owner.";
            }

            MenuController.BindMenuItem(menu, deleteSavedPedMenu, deleteSavedPed);

            Menu addonPeds = new Menu("Model Spawner", "Spawn Addon Ped");

            MenuItem addonPedsBtn = new MenuItem("Addon Peds", "Choose a player skin from the addons list available on this server.");

            menu.AddMenuItem(addonPedsBtn);
            MenuController.AddSubmenu(menu, addonPeds);

            if (AddonPeds != null)
            {
                if (AddonPeds.Count > 0)
                {
                    addonPedsBtn.Label = "→→→";
                    foreach (KeyValuePair <string, uint> ped in AddonPeds)
                    {
                        var button = new MenuItem(ped.Key, "Click to use this ped.");
                        addonPeds.AddMenuItem(button);
                        if (!IsModelAPed(ped.Value) || !IsModelInCdimage(ped.Value))
                        {
                            button.Enabled     = false;
                            button.LeftIcon    = MenuItem.Icon.LOCK;
                            button.Description = "This ped is not available on this server. Are you sure the model is valid?";
                        }
                    }
                    addonPeds.OnItemSelect += async(sender, item, index) =>
                    {
                        if (item.Enabled)
                        {
                            await SetPlayerSkin(AddonPeds.ElementAt(index).Value, new PedInfo()
                            {
                                version = -1
                            });
                        }
                        else
                        {
                            Notify.Error("This ped is not available. Please ask the server owner to verify this addon ped.");
                        }
                    };
                    MenuController.BindMenuItem(menu, addonPeds, addonPedsBtn);
                }
                else
                {
                    addonPedsBtn.Enabled     = false;
                    addonPedsBtn.Description = "This server does not have any addon peds available.";
                    addonPedsBtn.LeftIcon    = MenuItem.Icon.LOCK;
                }
            }
            else
            {
                addonPedsBtn.Enabled     = false;
                addonPedsBtn.Description = "This server does not have any addon peds available.";
                addonPedsBtn.LeftIcon    = MenuItem.Icon.LOCK;
            }

            addonPeds.RefreshIndex();
            //addonPeds.UpdateScaleform();

            // Add the spawn by name button after the addon peds menu item.
            menu.AddMenuItem(spawnByName);



            // Loop through all the modelNames and create lists of max 50 ped names each.
            for (int i = 0; i < (modelNames.Count / 50) + 1; i++)
            {
                List <string> pedList = new List <string>();
                for (int ii = 0; ii < 50; ii++)
                {
                    int index = ((i * 50) + ii);
                    if (index >= modelNames.Count)
                    {
                        break;
                    }
                    int max = ((modelNames.Count / 50) != i) ? 50 : modelNames.Count % 50;
                    pedList.Add(modelNames[index] + $" ({(ii + 1).ToString()}/{max.ToString()})");
                }
                MenuListItem pedl = new MenuListItem("Peds #" + (i + 1).ToString(), pedList, 0);

                menu.AddMenuItem(pedl);
                if (!IsAllowed(Permission.PASpawnNew))
                {
                    pedl.Enabled     = false;
                    pedl.LeftIcon    = MenuItem.Icon.LOCK;
                    pedl.Description = "This option has been disabled by the server owner.";
                }
            }

            // Handle list selections.
            menu.OnListItemSelect += async(sender, item, listIndex, itemIndex) =>
            {
                if (item == walkingStyle)
                {
                    if (MainMenu.DebugMode)
                    {
                        Subtitle.Custom("Ped is: " + IsPedMale(Game.PlayerPed.Handle));
                    }
                    SetWalkingStyle(walkstyles[listIndex].ToString());
                }
                else if (item == clothingGlowType)
                {
                    ClothingAnimationType = item.ListIndex;
                }
                else
                {
                    int    i         = ((itemIndex - 8) * 50) + listIndex;
                    string modelName = modelNames[i];
                    if (IsAllowed(Permission.PASpawnNew))
                    {
                        await SetPlayerSkin(modelName, new PedInfo()
                        {
                            version = -1
                        });
                    }
                }
            };

            // Handle button presses.
            menu.OnItemSelect += (sender, item, index) =>
            {
                if (item == pedCustomization)
                {
                    RefreshCustomizationMenu();
                }
                else if (item == spawnSavedPed)
                {
                    RefreshSpawnSavedPedMenu();
                }
                else if (item == deleteSavedPed)
                {
                    RefreshDeleteSavedPedMenu();
                }
                else if (item == savePed)
                {
                    SavePed();
                }
                else if (item == spawnByName)
                {
                    SpawnPedByName();
                }
            };

            // Handle saved ped spawning.
            spawnSavedPedMenu.OnItemSelect += (sender, item, idex) =>
            {
                var name = item.Text.ToString();
                LoadSavedPed(name, true);
            };

            #region ped drawable list changes
            // Manage list changes.
            pedCustomizationMenu.OnListIndexChange += (sender, item, oldListIndex, newListIndex, itemIndex) =>
            {
                if (drawablesMenuListItems.ContainsKey(item))
                {
                    int drawableID = drawablesMenuListItems[item];
                    SetPedComponentVariation(Game.PlayerPed.Handle, drawableID, newListIndex, 0, 0);
                }
                else if (propsMenuListItems.ContainsKey(item))
                {
                    int propID = propsMenuListItems[item];
                    if (newListIndex == 0)
                    {
                        SetPedPropIndex(Game.PlayerPed.Handle, propID, newListIndex - 1, 0, false);
                        ClearPedProp(Game.PlayerPed.Handle, propID);
                    }
                    else
                    {
                        SetPedPropIndex(Game.PlayerPed.Handle, propID, newListIndex - 1, 0, true);
                    }
                    if (propID == 0)
                    {
                        int component = GetPedPropIndex(Game.PlayerPed.Handle, 0);                        // helmet index
                        int texture   = GetPedPropTextureIndex(Game.PlayerPed.Handle, 0);                 // texture
                        int compHash  = GetHashNameForProp(Game.PlayerPed.Handle, 0, component, texture); // prop combination hash
                        if (N_0xd40aac51e8e4c663(compHash) > 0)                                           // helmet has visor.
                        {
                            if (!IsHelpMessageBeingDisplayed())
                            {
                                BeginTextCommandDisplayHelp("TWOSTRINGS");
                                AddTextComponentSubstringPlayerName("Hold ~INPUT_SWITCH_VISOR~ to flip your helmet visor open or closed");
                                AddTextComponentSubstringPlayerName("when on foot or on a motorcycle and when vMenu is closed.");
                                EndTextCommandDisplayHelp(0, false, true, 6000);
                            }
                        }
                    }
                }
            };

            // Manage list selections.
            pedCustomizationMenu.OnListItemSelect += (sender, item, listIndex, itemIndex) =>
            {
                if (drawablesMenuListItems.ContainsKey(item)) // drawable
                {
                    int currentDrawableID   = drawablesMenuListItems[item];
                    int currentTextureIndex = GetPedTextureVariation(Game.PlayerPed.Handle, currentDrawableID);
                    int maxDrawableTextures = GetNumberOfPedTextureVariations(Game.PlayerPed.Handle, currentDrawableID, listIndex) - 1;

                    if (currentTextureIndex == -1)
                    {
                        currentTextureIndex = 0;
                    }

                    int newTexture = currentTextureIndex < maxDrawableTextures ? currentTextureIndex + 1 : 0;

                    SetPedComponentVariation(Game.PlayerPed.Handle, currentDrawableID, listIndex, newTexture, 0);
                }
                else if (propsMenuListItems.ContainsKey(item)) // prop
                {
                    int currentPropIndex            = propsMenuListItems[item];
                    int currentPropVariationIndex   = GetPedPropIndex(Game.PlayerPed.Handle, currentPropIndex);
                    int currentPropTextureVariation = GetPedPropTextureIndex(Game.PlayerPed.Handle, currentPropIndex);
                    int maxPropTextureVariations    = GetNumberOfPedPropTextureVariations(Game.PlayerPed.Handle, currentPropIndex, currentPropVariationIndex) - 1;

                    int newPropTextureVariationIndex = currentPropTextureVariation < maxPropTextureVariations ? currentPropTextureVariation + 1 : 0;
                    SetPedPropIndex(Game.PlayerPed.Handle, currentPropIndex, currentPropVariationIndex, newPropTextureVariationIndex, true);
                }
            };
            #endregion
        }
示例#20
0
        /// <summary>
        /// Creates the menu.
        /// </summary>
        private void CreateMenu()
        {
            // Menu
            menu = new Menu(GetSafePlayerName(Game.Player.Name), "個人載具選項");

            // menu items
            MenuItem setVehice = new MenuItem("設定載具", "將您當前的載具設置為您的個人載具。 如果您已經有個人交通工具,那麼它將覆蓋您的選擇.")
            {
                Label = "目前載具: 無"
            };
            MenuItem     toggleEngine = new MenuItem("開關引擎", "即使您不在載具內,也可以打開或關閉引擎。 如果其他人當前正在使用您的載具,這將不起作用.");
            MenuListItem toggleLights = new MenuListItem("開關載具燈", new List <string>()
            {
                "強制開啟", "強制關閉", "重置"
            }, 0, "這將啟用或禁用您的載具前燈(但是必須先發動載具才能使用此功能).");
            MenuItem kickAllPassengers = new MenuItem("踢出乘客", "把所有乘車踢出載具外.");
            //MenuItem
            MenuItem lockDoors    = new MenuItem("鎖門", "鎖載具門,即使有鎖門,在載具裡面的人依然還是能夠離開車輛.");
            MenuItem unlockDoors  = new MenuItem("解鎖門", "解鎖載具的門.");
            MenuItem doorsMenuBtn = new MenuItem("載具門", "編輯載具門")
            {
                Label = "→→→"
            };
            MenuItem         soundHorn   = new MenuItem("喇叭聲音", "發出載具的喇叭聲音");
            MenuItem         toggleAlarm = new MenuItem("開關警報器", "開關載具警報聲音。 這不會設置警報。 它僅發出當前警報聲音的狀態.");
            MenuCheckboxItem enableBlip  = new MenuCheckboxItem("個人載具光點", "開啟或關閉 個人載具標記光點.", EnableVehicleBlip)
            {
                Style = MenuCheckboxItem.CheckboxStyle.Cross
            };
            MenuCheckboxItem exclusiveDriver = new MenuCheckboxItem("私人載具", "如果開啟的話其他玩家不能開您的載具.", false)
            {
                Style = MenuCheckboxItem.CheckboxStyle.Cross
            };

            //submenu
            VehicleDoorsMenu = new Menu("載具門", "載具門管理");
            MenuController.AddSubmenu(menu, VehicleDoorsMenu);
            MenuController.BindMenuItem(menu, VehicleDoorsMenu, doorsMenuBtn);

            // This is always allowed if this submenu is created/allowed.
            menu.AddMenuItem(setVehice);

            // Add conditional features.

            // Toggle engine.
            if (IsAllowed(Permission.PVToggleEngine))
            {
                menu.AddMenuItem(toggleEngine);
            }

            // Toggle lights
            if (IsAllowed(Permission.PVToggleLights))
            {
                menu.AddMenuItem(toggleLights);
            }

            // Kick vehicle passengers
            if (IsAllowed(Permission.PVKickPassengers))
            {
                menu.AddMenuItem(kickAllPassengers);
            }

            // Lock and unlock vehicle doors
            if (IsAllowed(Permission.PVLockDoors))
            {
                menu.AddMenuItem(lockDoors);
                menu.AddMenuItem(unlockDoors);
            }

            if (IsAllowed(Permission.PVDoors))
            {
                menu.AddMenuItem(doorsMenuBtn);
            }

            // Sound horn
            if (IsAllowed(Permission.PVSoundHorn))
            {
                menu.AddMenuItem(soundHorn);
            }

            // Toggle alarm sound
            if (IsAllowed(Permission.PVToggleAlarm))
            {
                menu.AddMenuItem(toggleAlarm);
            }

            // Enable blip for personal vehicle
            if (IsAllowed(Permission.PVAddBlip))
            {
                menu.AddMenuItem(enableBlip);
            }

            if (IsAllowed(Permission.PVExclusiveDriver))
            {
                menu.AddMenuItem(exclusiveDriver);
            }


            // Handle list presses
            menu.OnListItemSelect += (sender, item, itemIndex, index) =>
            {
                var veh = CurrentPersonalVehicle;
                if (veh != null && veh.Exists())
                {
                    if (!NetworkHasControlOfEntity(CurrentPersonalVehicle.Handle))
                    {
                        if (!NetworkRequestControlOfEntity(CurrentPersonalVehicle.Handle))
                        {
                            Notify.Error("您目前無法控制這輛載具。可能有其他玩家控制您的載具,請重試.");
                            return;
                        }
                    }

                    if (item == toggleLights)
                    {
                        PressKeyFob(CurrentPersonalVehicle);
                        if (itemIndex == 0)
                        {
                            SetVehicleLights(CurrentPersonalVehicle.Handle, 3);
                        }
                        else if (itemIndex == 1)
                        {
                            SetVehicleLights(CurrentPersonalVehicle.Handle, 1);
                        }
                        else
                        {
                            SetVehicleLights(CurrentPersonalVehicle.Handle, 0);
                        }
                    }
                }
                else
                {
                    Notify.Error("您尚未選擇個人載具,或者您的載具已被刪除。 在使用這些選項之前,請先設置個人交通工具.");
                }
            };

            // Handle checkbox changes
            menu.OnCheckboxChange += (sender, item, index, _checked) =>
            {
                if (item == enableBlip)
                {
                    EnableVehicleBlip = _checked;
                    if (EnableVehicleBlip)
                    {
                        if (CurrentPersonalVehicle != null && CurrentPersonalVehicle.Exists())
                        {
                            if (CurrentPersonalVehicle.AttachedBlip == null || !CurrentPersonalVehicle.AttachedBlip.Exists())
                            {
                                CurrentPersonalVehicle.AttachBlip();
                            }
                            CurrentPersonalVehicle.AttachedBlip.Sprite = BlipSprite.PersonalVehicleCar;
                            CurrentPersonalVehicle.AttachedBlip.Name   = "私人載具";
                        }
                        else
                        {
                            Notify.Error("您尚未選擇個人載具,或者您的載具已被刪除。 在使用這些選項之前,請先設置個人交通工具.");
                        }
                    }
                    else
                    {
                        if (CurrentPersonalVehicle != null && CurrentPersonalVehicle.Exists() && CurrentPersonalVehicle.AttachedBlip != null && CurrentPersonalVehicle.AttachedBlip.Exists())
                        {
                            CurrentPersonalVehicle.AttachedBlip.Delete();
                        }
                    }
                }
                else if (item == exclusiveDriver)
                {
                    if (CurrentPersonalVehicle != null && CurrentPersonalVehicle.Exists())
                    {
                        if (NetworkRequestControlOfEntity(CurrentPersonalVehicle.Handle))
                        {
                            if (_checked)
                            {
                                SetVehicleExclusiveDriver(CurrentPersonalVehicle.Handle, Game.PlayerPed.Handle);
                                SetVehicleExclusiveDriver_2(CurrentPersonalVehicle.Handle, Game.PlayerPed.Handle, 1);
                            }
                            else
                            {
                                SetVehicleExclusiveDriver(CurrentPersonalVehicle.Handle, 0);
                                SetVehicleExclusiveDriver_2(CurrentPersonalVehicle.Handle, 0, 1);
                            }
                        }
                        else
                        {
                            item.Checked = !_checked;
                            Notify.Error("您目前無法控制這輛載具。可能有其他玩家控制您的載具,請重試.");
                        }
                    }
                }
            };

            // Handle button presses.
            menu.OnItemSelect += (sender, item, index) =>
            {
                if (item == setVehice)
                {
                    if (Game.PlayerPed.IsInVehicle())
                    {
                        var veh = GetVehicle();
                        if (veh != null && veh.Exists())
                        {
                            if (Game.PlayerPed == veh.Driver)
                            {
                                CurrentPersonalVehicle      = veh;
                                veh.PreviouslyOwnedByPlayer = true;
                                veh.IsPersistent            = true;
                                if (EnableVehicleBlip && IsAllowed(Permission.PVAddBlip))
                                {
                                    if (veh.AttachedBlip == null || !veh.AttachedBlip.Exists())
                                    {
                                        veh.AttachBlip();
                                    }
                                    veh.AttachedBlip.Sprite = BlipSprite.PersonalVehicleCar;
                                    veh.AttachedBlip.Name   = "私人載具";
                                }
                                var name = GetLabelText(veh.DisplayName);
                                if (string.IsNullOrEmpty(name) || name.ToLower() == "null")
                                {
                                    name = veh.DisplayName;
                                }
                                item.Label = $"目前載具: {name}";
                            }
                            else
                            {
                                Notify.Error(CommonErrors.NeedToBeTheDriver);
                            }
                        }
                        else
                        {
                            Notify.Error(CommonErrors.NoVehicle);
                        }
                    }
                    else
                    {
                        Notify.Error(CommonErrors.NoVehicle);
                    }
                }
                else if (CurrentPersonalVehicle != null && CurrentPersonalVehicle.Exists())
                {
                    if (item == kickAllPassengers)
                    {
                        if (CurrentPersonalVehicle.Occupants.Count() > 0 && CurrentPersonalVehicle.Occupants.Any(p => p != Game.PlayerPed))
                        {
                            var netId = VehToNet(CurrentPersonalVehicle.Handle);
                            TriggerServerEvent("vMenu:GetOutOfCar", netId, Game.Player.ServerId);
                        }
                        else
                        {
                            Notify.Info("您的載具目前沒有乘客無法使用該功能.");
                        }
                    }
                    else
                    {
                        if (!NetworkHasControlOfEntity(CurrentPersonalVehicle.Handle))
                        {
                            if (!NetworkRequestControlOfEntity(CurrentPersonalVehicle.Handle))
                            {
                                Notify.Error("您目前無法控制這輛載具。可能有其他玩家控制您的載具,請重試.");
                                return;
                            }
                        }

                        if (item == toggleEngine)
                        {
                            PressKeyFob(CurrentPersonalVehicle);
                            SetVehicleEngineOn(CurrentPersonalVehicle.Handle, !CurrentPersonalVehicle.IsEngineRunning, true, true);
                        }

                        else if (item == lockDoors || item == unlockDoors)
                        {
                            PressKeyFob(CurrentPersonalVehicle);
                            bool _lock = item == lockDoors;
                            LockOrUnlockDoors(CurrentPersonalVehicle, _lock);
                        }

                        else if (item == soundHorn)
                        {
                            PressKeyFob(CurrentPersonalVehicle);
                            SoundHorn(CurrentPersonalVehicle);
                        }

                        else if (item == toggleAlarm)
                        {
                            PressKeyFob(CurrentPersonalVehicle);
                            ToggleVehicleAlarm(CurrentPersonalVehicle);
                        }
                    }
                }
                else
                {
                    Notify.Error("您尚未選擇個人載具,或者您的載具已被刪除。 在使用這些選項之前,請先設置個人交通工具.");
                }
            };

            #region Doors submenu
            MenuItem openAll  = new MenuItem("打開所有載具門", "打開所有載具門.");
            MenuItem closeAll = new MenuItem("關閉所有載具門", "關閉所有載具門.");
            MenuItem LF       = new MenuItem("左前門", "開啟/關閉 左前門.");
            MenuItem RF       = new MenuItem("右前門", "開啟/關閉 右前門.");
            MenuItem LR       = new MenuItem("左後門", "開啟/關閉 左後門.");
            MenuItem RR       = new MenuItem("右後門", "開啟/關閉 右後門.");
            MenuItem HD       = new MenuItem("引擎蓋", "開啟/關閉 引擎蓋.");
            MenuItem TR       = new MenuItem("後車廂", "開啟/關閉 後車廂.");
            MenuItem E1       = new MenuItem("附加 1", "開啟/關閉 附加 (#1). 請注意:大多數的載具沒有此功能.");
            MenuItem E2       = new MenuItem("附加 2", "開啟/關閉 附加 (#2). 請注意:大多數的載具沒有此功能.");
            MenuItem BB       = new MenuItem("炸彈艙", "開啟/關閉 炸彈艙。僅能在某些飛機上使用.");
            var      doors    = new List <string>()
            {
                "Front Left", "Front Right", "Rear Left", "Rear Right", "Hood", "Trunk", "Extra 1", "Extra 2", "Bomb Bay"
            };
            MenuListItem     removeDoorList = new MenuListItem("移除門", doors, 0, "完成卸下特定的載具門.");
            MenuCheckboxItem deleteDoors    = new MenuCheckboxItem("刪除已拆除的門", "啟用後上述列表的門將被刪除。如果是禁用的話門只會掉在地上.", false);

            VehicleDoorsMenu.AddMenuItem(LF);
            VehicleDoorsMenu.AddMenuItem(RF);
            VehicleDoorsMenu.AddMenuItem(LR);
            VehicleDoorsMenu.AddMenuItem(RR);
            VehicleDoorsMenu.AddMenuItem(HD);
            VehicleDoorsMenu.AddMenuItem(TR);
            VehicleDoorsMenu.AddMenuItem(E1);
            VehicleDoorsMenu.AddMenuItem(E2);
            VehicleDoorsMenu.AddMenuItem(BB);
            VehicleDoorsMenu.AddMenuItem(openAll);
            VehicleDoorsMenu.AddMenuItem(closeAll);
            VehicleDoorsMenu.AddMenuItem(removeDoorList);
            VehicleDoorsMenu.AddMenuItem(deleteDoors);

            VehicleDoorsMenu.OnListItemSelect += (sender, item, index, itemIndex) =>
            {
                Vehicle veh = CurrentPersonalVehicle;
                if (veh != null && veh.Exists())
                {
                    if (!NetworkHasControlOfEntity(CurrentPersonalVehicle.Handle))
                    {
                        if (!NetworkRequestControlOfEntity(CurrentPersonalVehicle.Handle))
                        {
                            Notify.Error("您目前無法控制這輛載具。可能有其他玩家控制您的載具,請重試.");
                            return;
                        }
                    }

                    if (item == removeDoorList)
                    {
                        PressKeyFob(veh);
                        SetVehicleDoorBroken(veh.Handle, index, deleteDoors.Checked);
                    }
                }
            };

            VehicleDoorsMenu.OnItemSelect += (sender, item, index) =>
            {
                Vehicle veh = CurrentPersonalVehicle;
                if (veh != null && veh.Exists() && !veh.IsDead)
                {
                    if (!NetworkHasControlOfEntity(CurrentPersonalVehicle.Handle))
                    {
                        if (!NetworkRequestControlOfEntity(CurrentPersonalVehicle.Handle))
                        {
                            Notify.Error("您目前無法控制這輛載具。可能有其他玩家控制您的載具,請重試.");
                            return;
                        }
                    }

                    if (index < 8)
                    {
                        bool open = GetVehicleDoorAngleRatio(veh.Handle, index) > 0.1f;
                        PressKeyFob(veh);
                        if (open)
                        {
                            SetVehicleDoorShut(veh.Handle, index, false);
                        }
                        else
                        {
                            SetVehicleDoorOpen(veh.Handle, index, false, false);
                        }
                    }
                    else if (item == openAll)
                    {
                        PressKeyFob(veh);
                        for (var door = 0; door < 8; door++)
                        {
                            SetVehicleDoorOpen(veh.Handle, door, false, false);
                        }
                    }
                    else if (item == closeAll)
                    {
                        PressKeyFob(veh);
                        for (var door = 0; door < 8; door++)
                        {
                            SetVehicleDoorShut(veh.Handle, door, false);
                        }
                    }
                    else if (item == BB && veh.HasBombBay)
                    {
                        PressKeyFob(veh);
                        bool bombBayOpen = AreBombBayDoorsOpen(veh.Handle);
                        if (bombBayOpen)
                        {
                            veh.CloseBombBay();
                        }
                        else
                        {
                            veh.OpenBombBay();
                        }
                    }
                    else
                    {
                        Notify.Error("您尚未選擇個人載具,或者您的載具已被刪除。 在使用這些選項之前,請先設置個人交通工具.");
                    }
                }
            };
            #endregion
        }
示例#21
0
        /// <summary>
        /// Creates the menu.
        /// </summary>
        private void CreateMenu()
        {
            MenuController.MenuAlignment = MiscRightAlignMenu ? MenuController.MenuAlignmentOption.Right : MenuController.MenuAlignmentOption.Left;
            // Create the menu.
            menu = new Menu(Game.Player.Name, "Misc Settings");

            // teleport menu
            Menu     teleportMenu    = new Menu(Game.Player.Name, "Teleport Locations");
            MenuItem teleportMenuBtn = new MenuItem("Teleport Locations", "Teleport to pre-configured locations, added by the server owner.");

            MenuController.AddSubmenu(menu, teleportMenu);
            MenuController.BindMenuItem(menu, teleportMenu, teleportMenuBtn);

            // keybind settings menu
            Menu     keybindMenu    = new Menu(Game.Player.Name, "Keybind Settings");
            MenuItem keybindMenuBtn = new MenuItem("Keybind Settings", "Enable or disable keybinds for some options.");

            MenuController.AddSubmenu(menu, keybindMenu);
            MenuController.BindMenuItem(menu, keybindMenu, keybindMenuBtn);

            // keybind settings menu items
            MenuCheckboxItem kbTpToWaypoint = new MenuCheckboxItem("Teleport To Waypoint", "Teleport to your waypoint when pressing the keybind. By default, this keybind is set to ~r~F7~s~, server owners are able to change this however so ask them if you don't know what it is.", KbTpToWaypoint);
            MenuCheckboxItem kbDriftMode    = new MenuCheckboxItem("Drift Mode", "Makes your vehicle have almost no traction while holding left shift on keyboard, or X on controller.", KbDriftMode);
            MenuItem         backBtn        = new MenuItem("Back");

            // Create the menu items.
            MenuItem         tptowp         = new MenuItem("Teleport To Waypoint", "Teleport to the waypoint on your map.");
            MenuCheckboxItem rightAlignMenu = new MenuCheckboxItem("Right Align Menu", "If you want vMenu to appear on the left side of your screen, disable this option. This option will be saved immediately. You don't need to click save preferences.", MiscRightAlignMenu);
            MenuCheckboxItem speedKmh       = new MenuCheckboxItem("Show Speed KM/H", "Show a speedometer on your screen indicating your speed in KM/h.", ShowSpeedoKmh);
            MenuCheckboxItem speedMph       = new MenuCheckboxItem("Show Speed MPH", "Show a speedometer on your screen indicating your speed in MPH.", ShowSpeedoMph);
            MenuCheckboxItem coords         = new MenuCheckboxItem("Show Coordinates", "Show your current coordinates at the top of your screen.", ShowCoordinates);
            MenuCheckboxItem hideRadar      = new MenuCheckboxItem("Hide Radar", "Hide the radar/minimap.", HideRadar);
            MenuCheckboxItem hideHud        = new MenuCheckboxItem("Hide Hud", "Hide all hud elements.", HideHud);
            MenuCheckboxItem showLocation   = new MenuCheckboxItem("Location Display", "Shows your current location and heading, as well as the nearest cross road. Similar like PLD. ~r~Warning: This feature (can) take about 1.6 FPS when running at 60 Hz.", ShowLocation)
            {
                LeftIcon = MenuItem.Icon.WARNING
            };
            MenuCheckboxItem drawTime     = new MenuCheckboxItem("Show Time On Screen", "Shows you the current time on screen.", DrawTimeOnScreen);
            MenuItem         saveSettings = new MenuItem("Save Personal Settings", "Save your current settings. All saving is done on the client side, if you re-install windows you will lose your settings. Settings are shared across all servers using vMenu.");

            saveSettings.RightIcon = MenuItem.Icon.TICK;
            MenuCheckboxItem joinQuitNotifs  = new MenuCheckboxItem("Join / Quit Notifications", "Receive notifications when someone joins or leaves the server.", JoinQuitNotifications);
            MenuCheckboxItem deathNotifs     = new MenuCheckboxItem("Death Notifications", "Receive notifications when someone dies or gets killed.", DeathNotifications);
            MenuCheckboxItem nightVision     = new MenuCheckboxItem("Toggle Night Vision", "Enable or disable night vision.", false);
            MenuCheckboxItem thermalVision   = new MenuCheckboxItem("Toggle Thermal Vision", "Enable or disable thermal vision.", false);
            MenuCheckboxItem modelDimensions = new MenuCheckboxItem("Show Vehicle Dimensions", "Draws lines for the model dimensions of your vehicle (debug function).", ShowVehicleModelDimensions);

            MenuItem         clearArea = new MenuItem("Clear Area", "Clears the area around your player (100 meters). Damage, dirt, peds, props, vehicles, etc. Everything gets cleaned up, fixed and reset to the default world state.");
            MenuCheckboxItem lockCamX  = new MenuCheckboxItem("Lock Camera Horizontal Rotation", "Locks your camera horizontal rotation. Could be useful in helicopters I guess.", false);
            MenuCheckboxItem lockCamY  = new MenuCheckboxItem("Lock Camera Vertical Rotation", "Locks your camera vertical rotation. Could be useful in helicopters I guess.", false);

            Menu     connectionSubmenu    = new Menu(Game.Player.Name, "Connection Options");
            MenuItem connectionSubmenuBtn = new MenuItem("Connection Options", "Server connection/game quit options.");
            MenuItem quitSession          = new MenuItem("Quit Session", "Leaves you connected to the server, but quits the network session. " +
                                                         "Use this if you need to have addons streamed but want to use the rockstar editor.");
            MenuItem quitGame             = new MenuItem("Quit Game", "Exits the game after 5 seconds.");
            MenuItem disconnectFromServer = new MenuItem("Disconnect From Server", "Disconnects you from the server and returns you to the serverlist. " +
                                                         "~r~This feature is not recommended, quit the game instead for a better experience.");

            connectionSubmenu.AddMenuItem(quitSession);
            connectionSubmenu.AddMenuItem(quitGame);
            connectionSubmenu.AddMenuItem(disconnectFromServer);

            MenuCheckboxItem locationBlips           = new MenuCheckboxItem("Location Blips", "Shows blips on the map for some common locations.", ShowLocationBlips);
            MenuCheckboxItem playerBlips             = new MenuCheckboxItem("Show Player Blips", "Shows blips on the map for all players.", ShowPlayerBlips);
            MenuCheckboxItem respawnDefaultCharacter = new MenuCheckboxItem("Respawn As Default MP Character", "If you enable this, then you will (re)spawn as your default saved MP character. Note the server owner can globally disable this option. To set your default character, go to one of your saved MP Characters and click the 'Set As Default Character' button.", MiscRespawnDefaultCharacter);
            MenuCheckboxItem restorePlayerAppearance = new MenuCheckboxItem("Restore Player Appearance", "Restore your player's skin whenever you respawn after being dead. Re-joining a server will not restore your previous skin.", RestorePlayerAppearance);
            MenuCheckboxItem restorePlayerWeapons    = new MenuCheckboxItem("Restore Player Weapons", "Restore your weapons whenever you respawn after being dead. Re-joining a server will not restore your previous weapons.", RestorePlayerWeapons);

            MenuController.AddSubmenu(menu, connectionSubmenu);
            MenuController.BindMenuItem(menu, connectionSubmenu, connectionSubmenuBtn);
            //MainMenu.Mp.Add(connectionSubmenu);
            //connectionSubmenu.RefreshIndex();
            //connectionSubmenu.UpdateScaleform();
            //menu.BindMenuToItem(connectionSubmenu, connectionSubmenuBtn);

            keybindMenu.OnCheckboxChange += (sender, item, index, _checked) =>
            {
                if (item == kbTpToWaypoint)
                {
                    KbTpToWaypoint = _checked;
                }
                else if (item == kbDriftMode)
                {
                    KbDriftMode = _checked;
                }
            };
            keybindMenu.OnItemSelect += (sender, item, index) =>
            {
                if (item == backBtn)
                {
                    keybindMenu.GoBack();
                }
            };

            connectionSubmenu.OnItemSelect += (sender, item, index) =>
            {
                if (item == quitGame)
                {
                    QuitGame();
                }
                else if (item == quitSession)
                {
                    QuitSession();
                }
                else if (item == disconnectFromServer)
                {
                    BaseScript.TriggerServerEvent("vMenu:DisconnectSelf");
                }
            };

            // Add menu items to the menu.
            if (IsAllowed(Permission.MSTeleportToWp))
            {
                menu.AddMenuItem(tptowp);
                keybindMenu.AddMenuItem(kbTpToWaypoint);
            }

            if (IsAllowed(Permission.MSDriftMode))
            {
                keybindMenu.AddMenuItem(kbDriftMode);
            }

            keybindMenu.AddMenuItem(backBtn);

            // Always allowed
            menu.AddMenuItem(rightAlignMenu);
            menu.AddMenuItem(speedKmh);
            menu.AddMenuItem(speedMph);
            menu.AddMenuItem(modelDimensions);
            menu.AddMenuItem(keybindMenuBtn);
            keybindMenuBtn.Label = "→→→";
            if (IsAllowed(Permission.MSConnectionMenu))
            {
                menu.AddMenuItem(connectionSubmenuBtn);
                connectionSubmenuBtn.Label = "→→→";
            }
            if (IsAllowed(Permission.MSShowCoordinates))
            {
                menu.AddMenuItem(coords);
            }
            if (IsAllowed(Permission.MSShowLocation))
            {
                menu.AddMenuItem(showLocation);
            }
            menu.AddMenuItem(drawTime); // always allowed
            if (IsAllowed(Permission.MSJoinQuitNotifs))
            {
                menu.AddMenuItem(deathNotifs);
            }
            if (IsAllowed(Permission.MSDeathNotifs))
            {
                menu.AddMenuItem(joinQuitNotifs);
            }
            if (IsAllowed(Permission.MSNightVision))
            {
                menu.AddMenuItem(nightVision);
            }
            if (IsAllowed(Permission.MSThermalVision))
            {
                menu.AddMenuItem(thermalVision);
            }
            if (IsAllowed(Permission.MSLocationBlips))
            {
                menu.AddMenuItem(locationBlips);
                ToggleBlips(ShowLocationBlips);
            }
            if (IsAllowed(Permission.MSPlayerBlips))
            {
                menu.AddMenuItem(playerBlips);
            }
            if (IsAllowed(Permission.MSTeleportLocations))
            {
                menu.AddMenuItem(teleportMenuBtn);
                teleportMenuBtn.Label = "→→→";

                string json = LoadResourceFile(GetCurrentResourceName(), "config/locations.json");
                if (string.IsNullOrEmpty(json))
                {
                    Notify.Error("An error occurred while loading the locations file.");
                }
                else
                {
                    try
                    {
                        Newtonsoft.Json.Linq.JObject data = JsonConvert.DeserializeObject <Newtonsoft.Json.Linq.JObject>(json);
                        foreach (Newtonsoft.Json.Linq.JToken teleport in data["teleports"])
                        {
                            string   name        = teleport["name"].ToString();
                            float    heading     = (float)teleport["heading"];
                            Vector3  coordinates = new Vector3((float)teleport["coordinates"]["x"], (float)teleport["coordinates"]["y"], (float)teleport["coordinates"]["z"]);
                            MenuItem tpBtn       = new MenuItem(name, $"Teleport to X: {(int)coordinates.X} Y: {(int)coordinates.Y} Z: {(int)coordinates.Z} HEADING: {(int)heading}.");
                            teleportMenu.AddMenuItem(tpBtn);
                            tpLocations.Add(coordinates);
                            tpLocationsHeading.Add(heading);
                        }
                        teleportMenu.OnItemSelect += async(sender, item, index) =>
                        {
                            await TeleportToCoords(tpLocations[index], true);

                            SetEntityHeading(Game.PlayerPed.Handle, tpLocationsHeading[index]);
                        };
                    }
                    catch (JsonReaderException ex)
                    {
                        Debug.Write($"\n[vMenu] An error occurred whie loading the teleport locations!\nReport the following error details to the server owner:\n{ex.Message}.\n");
                    }
                }
            }
            if (IsAllowed(Permission.MSClearArea))
            {
                menu.AddMenuItem(clearArea);
            }
            // always allowed, it just won't do anything if the server owner disabled the feature, but players can still toggle it.
            menu.AddMenuItem(respawnDefaultCharacter);
            if (IsAllowed(Permission.MSRestoreAppearance))
            {
                menu.AddMenuItem(restorePlayerAppearance);
            }
            if (IsAllowed(Permission.MSRestoreWeapons))
            {
                menu.AddMenuItem(restorePlayerWeapons);
            }

            // Always allowed
            menu.AddMenuItem(hideRadar);
            menu.AddMenuItem(hideHud);
            menu.AddMenuItem(lockCamX);
            menu.AddMenuItem(lockCamY);
            menu.AddMenuItem(saveSettings);

            // Handle checkbox changes.
            menu.OnCheckboxChange += (sender, item, index, _checked) =>
            {
                if (item == rightAlignMenu)
                {
                    MiscRightAlignMenu = _checked;
                    UserDefaults.MiscRightAlignMenu = MiscRightAlignMenu;
                    MenuController.MenuAlignment    = MiscRightAlignMenu ? MenuController.MenuAlignmentOption.Right : MenuController.MenuAlignmentOption.Left;
                    //Notify.Alert("You must restart your game before this option takes affect.");
                }
                if (item == speedKmh)
                {
                    ShowSpeedoKmh = _checked;
                }
                else if (item == speedMph)
                {
                    ShowSpeedoMph = _checked;
                }
                else if (item == coords)
                {
                    ShowCoordinates = _checked;
                }
                else if (item == hideHud)
                {
                    HideHud = _checked;
                    DisplayHud(!_checked);
                }
                else if (item == hideRadar)
                {
                    HideRadar = _checked;
                    if (!_checked)
                    {
                        DisplayRadar(true);
                    }
                }
                else if (item == showLocation)
                {
                    ShowLocation = _checked;
                }
                else if (item == drawTime)
                {
                    DrawTimeOnScreen = _checked;
                }
                else if (item == deathNotifs)
                {
                    DeathNotifications = _checked;
                }
                else if (item == joinQuitNotifs)
                {
                    JoinQuitNotifications = _checked;
                }
                else if (item == nightVision)
                {
                    SetNightvision(_checked);
                }
                else if (item == thermalVision)
                {
                    SetSeethrough(_checked);
                }
                else if (item == lockCamX)
                {
                    LockCameraX = _checked;
                }
                else if (item == lockCamY)
                {
                    LockCameraY = _checked;
                }
                else if (item == locationBlips)
                {
                    ToggleBlips(_checked);
                    ShowLocationBlips = _checked;
                }
                else if (item == playerBlips)
                {
                    ShowPlayerBlips = _checked;
                }
                else if (item == respawnDefaultCharacter)
                {
                    MiscRespawnDefaultCharacter = _checked;
                }
                else if (item == restorePlayerAppearance)
                {
                    RestorePlayerAppearance = _checked;
                }
                else if (item == restorePlayerWeapons)
                {
                    RestorePlayerWeapons = _checked;
                }
                else if (item == modelDimensions)
                {
                    ShowVehicleModelDimensions = _checked;
                }
            };

            // Handle button presses.
            menu.OnItemSelect += (sender, item, index) =>
            {
                // Teleport to waypoint.
                if (item == tptowp)
                {
                    TeleportToWp();
                }
                // save settings
                else if (item == saveSettings)
                {
                    UserDefaults.SaveSettings();
                }
                // clear area
                else if (item == clearArea)
                {
                    var pos = Game.PlayerPed.Position;
                    BaseScript.TriggerServerEvent("vMenu:ClearArea", pos.X, pos.Y, pos.Z);
                }
            };
        }
示例#22
0
        /// <summary>
        /// Creates the menu.
        /// </summary>
        private void CreateMenu()
        {
            menu = new Menu(Game.Player.Name, "Banned Players Management");

            bannedPlayer.AddMenuItem(new MenuItem("Player Name"));
            bannedPlayer.AddMenuItem(new MenuItem("Banned By"));
            bannedPlayer.AddMenuItem(new MenuItem("Banned Until"));
            bannedPlayer.AddMenuItem(new MenuItem("Player Identifiers"));
            bannedPlayer.AddMenuItem(new MenuItem("Banned For"));
            bannedPlayer.AddMenuItem(new MenuItem("~r~Unban", "~r~Warning, unbanning the player can NOT be undone. You will NOT be able to ban them agian until they re-join the server. Are you absolutely sure you want to unban this player? ~s~Tip: Tempbanned players will automatically get unbanned if they log on to the server after their ban date has expired."));

            // should be enough for now to cover all possible identifiers.
            List <string> colors = new List <string>()
            {
                "~r~", "~g~", "~b~", "~o~", "~y~", "~p~", "~s~", "~t~",
            };

            bannedPlayer.OnMenuClose += (sender) =>
            {
                BaseScript.TriggerServerEvent("vMenu:RequestBanList", Game.Player.Handle);
                bannedPlayer.GetMenuItems()[5].Label = "";
                UpdateBans();
            };

            bannedPlayer.OnIndexChange += (sender, oldItem, newItem, oldIndex, newIndex) =>
            {
                bannedPlayer.GetMenuItems()[5].Label = "";
            };

            bannedPlayer.OnItemSelect += (sender, item, index) =>
            {
                if (index == 5 && IsAllowed(Permission.OPUnban))
                {
                    if (item.Label == "Are you sure?")
                    {
                        if (banlist.Contains(currentRecord))
                        {
                            UnbanPlayer(banlist.IndexOf(currentRecord));
                            bannedPlayer.GetMenuItems()[5].Label = "";
                            bannedPlayer.GoBack();
                        }
                        else
                        {
                            Notify.Error("Somehow you managed to click the unban button but this ban record you're apparently viewing does not even exist. Weird...");
                        }
                    }
                    else
                    {
                        item.Label = "Are you sure?";
                    }
                }
                else
                {
                    bannedPlayer.GetMenuItems()[5].Label = "";
                }
            };

            menu.OnItemSelect += (sender, item, index) =>
            {
                if (index < banlist.Count)
                {
                    currentRecord             = banlist[index];
                    bannedPlayer.MenuSubtitle = "Ban Record: ~y~" + currentRecord.playerName;
                    var nameItem              = bannedPlayer.GetMenuItems()[0];
                    var bannedByItem          = bannedPlayer.GetMenuItems()[1];
                    var bannedUntilItem       = bannedPlayer.GetMenuItems()[2];
                    var playerIdentifiersItem = bannedPlayer.GetMenuItems()[3];
                    var banReasonItem         = bannedPlayer.GetMenuItems()[4];
                    nameItem.Label           = currentRecord.playerName;
                    nameItem.Description     = "Player name: ~y~" + currentRecord.playerName;
                    bannedByItem.Label       = currentRecord.bannedBy;
                    bannedByItem.Description = "Player banned by: ~y~" + currentRecord.bannedBy;
                    if (currentRecord.bannedUntil.Date.Year == 3000)
                    {
                        bannedUntilItem.Label = "Forever";
                    }
                    else
                    {
                        bannedUntilItem.Label = currentRecord.bannedUntil.Date.ToString();
                    }
                    bannedUntilItem.Description       = "This player is banned until: " + currentRecord.bannedUntil.Date.ToString();
                    playerIdentifiersItem.Description = "";

                    int i = 0;
                    foreach (string id in currentRecord.identifiers)
                    {
                        // only (admins) people that can unban players are allowed to view IP's.
                        // this is just a slight 'safety' feature in case someone who doesn't know what they're doing
                        // gave builtin.everyone access to view the banlist.
                        if (id.StartsWith("ip:") && !IsAllowed(Permission.OPUnban))
                        {
                            playerIdentifiersItem.Description += $"{colors[i]}ip: (hidden) ";
                        }
                        else
                        {
                            playerIdentifiersItem.Description += $"{colors[i]}{id.Replace(":", ": ")} ";
                        }
                        i++;
                    }
                    banReasonItem.Description = "Banned for: " + currentRecord.banReason;

                    var unbanPlayerBtn = bannedPlayer.GetMenuItems()[5];
                    unbanPlayerBtn.Label = "";
                    if (!IsAllowed(Permission.OPUnban))
                    {
                        unbanPlayerBtn.Enabled     = false;
                        unbanPlayerBtn.Description = "You are not allowed to unban players. You are only allowed to view their ban record.";
                        unbanPlayerBtn.LeftIcon    = MenuItem.Icon.LOCK;
                    }

                    bannedPlayer.RefreshIndex();
                    //bannedPlayer.UpdateScaleform();
                }
            };
            MenuController.AddMenu(bannedPlayer);
        }
示例#23
0
        /// <summary>
        /// Creates the menu.
        /// </summary>
        private void CreateMenu()
        {
            // Create the menu.
            menu = new UIMenu("BigFam Crew", "Misc Settings", true)
            {
                ScaleWithSafezone       = false,
                MouseControlsEnabled    = false,
                MouseEdgeEnabled        = false,
                ControlDisablingEnabled = false
            };

            UIMenu teleportMenu = new UIMenu("BigFam Crew", "Teleport Locations", true)
            {
                ScaleWithSafezone       = false,
                MouseControlsEnabled    = false,
                MouseEdgeEnabled        = false,
                ControlDisablingEnabled = false
            };
            UIMenuItem teleportMenuBtn = new UIMenuItem("Teleport Locations", "Teleport to pre-configured locations, added by the server owner.");

            menu.BindMenuToItem(teleportMenu, teleportMenuBtn);
            MainMenu.Mp.Add(teleportMenu);

            // Create the menu items.
            UIMenuItem         tptowp       = new UIMenuItem("Teleport To Waypoint", "Teleport to the waypoint on your map.");
            UIMenuCheckboxItem speedKmh     = new UIMenuCheckboxItem("Show Speed KM/H", ShowSpeedoKmh, "Show a speedometer on your screen indicating your speed in KM/h.");
            UIMenuCheckboxItem speedMph     = new UIMenuCheckboxItem("Show Speed MPH", ShowSpeedoMph, "Show a speedometer on your screen indicating your speed in MPH.");
            UIMenuCheckboxItem coords       = new UIMenuCheckboxItem("Show Coordinates", ShowCoordinates, "Show your current coordinates at the top of your screen.");
            UIMenuCheckboxItem hideRadar    = new UIMenuCheckboxItem("Hide Radar", HideRadar, "Hide the radar/minimap.");
            UIMenuCheckboxItem hideHud      = new UIMenuCheckboxItem("Hide Hud", HideHud, "Hide all hud elements.");
            UIMenuCheckboxItem showLocation = new UIMenuCheckboxItem("Location Display", ShowLocation, "Shows your current location and heading, as well as the nearest cross road. Just like PLD.");
            UIMenuItem         saveSettings = new UIMenuItem("Save Personal Settings", "Save your current settings. All saving is done on the client side, if you re-install windows you will lose your settings. Settings are shared across all servers using vMenu.");

            saveSettings.SetRightBadge(UIMenuItem.BadgeStyle.Tick);
            UIMenuCheckboxItem joinQuitNotifs = new UIMenuCheckboxItem("Join / Quit Notifications", JoinQuitNotifications, "Receive notifications when someone joins or leaves the server.");
            UIMenuCheckboxItem deathNotifs    = new UIMenuCheckboxItem("Death Notifications", DeathNotifications, "Receive notifications when someone dies or gets killed.");
            UIMenuCheckboxItem nightVision    = new UIMenuCheckboxItem("Toggle Night Vision", false, "Enable or disable night vision.");
            UIMenuCheckboxItem thermalVision  = new UIMenuCheckboxItem("Toggle Thermal Vision", false, "Enable or disable thermal vision.");

            UIMenuItem         clearArea = new UIMenuItem("Clear Area", "Clears the area around your player (100 meters) of everything! Damage, dirt, peds, props, vehicles, etc. Everything gets cleaned up and reset.");
            UIMenuCheckboxItem lockCamX  = new UIMenuCheckboxItem("Lock Camera Horizontal Rotation", false, "Locks your camera horizontal rotation. Could be useful in helicopters I guess.");
            UIMenuCheckboxItem lockCamY  = new UIMenuCheckboxItem("Lock Camera Vertical Rotation", false, "Locks your camera vertical rotation. Could be useful in helicopters I guess.");

            UIMenu connectionSubmenu = new UIMenu(GetPlayerName(PlayerId()), "Connection Options", true)
            {
                ScaleWithSafezone       = false,
                MouseControlsEnabled    = false,
                MouseEdgeEnabled        = false,
                ControlDisablingEnabled = false
            };
            UIMenuItem connectionSubmenuBtn = new UIMenuItem("Connection Options", "Server connection/game quit options.");
            UIMenuItem quitSession          = new UIMenuItem("Quit Session", "Leaves you connected to the server, but quits the network session. " +
                                                             "Use this if you need to have addons streamed but want to use the rockstar editor.");
            UIMenuItem quitGame             = new UIMenuItem("Quit Game", "Exits the game after 5 seconds.");
            UIMenuItem disconnectFromServer = new UIMenuItem("Disconnect From Server", "Disconnects you from the server and returns you to the serverlist. " +
                                                             "~r~This feature is not recommended, quit the game instead for a better experience.");

            connectionSubmenu.AddItem(quitSession);
            connectionSubmenu.AddItem(quitGame);
            connectionSubmenu.AddItem(disconnectFromServer);

            UIMenuCheckboxItem locationBlips = new UIMenuCheckboxItem("Location Blips", ShowLocationBlips, "Shows blips on the map for some common locations.");
            UIMenuCheckboxItem playerBlips   = new UIMenuCheckboxItem("Show Player Blips", ShowPlayerBlips, "Shows blips on the map for all players.");

            MainMenu.Mp.Add(connectionSubmenu);
            connectionSubmenu.RefreshIndex();
            connectionSubmenu.UpdateScaleform();
            menu.BindMenuToItem(connectionSubmenu, connectionSubmenuBtn);

            connectionSubmenu.OnItemSelect += (sender, item, index) =>
            {
                if (item == quitGame)
                {
                    cf.QuitGame();
                }
                else if (item == quitSession)
                {
                    cf.QuitSession();
                }
                else if (item == disconnectFromServer)
                {
                    BaseScript.TriggerServerEvent("vMenu:DisconnectSelf");
                }
            };

            // Add menu items to the menu.
            if (cf.IsAllowed(Permission.MSTeleportToWp))
            {
                menu.AddItem(tptowp);
            }

            // Always allowed
            // menu.AddItem(speedKmh);
            // menu.AddItem(speedMph);
            if (cf.IsAllowed(Permission.MSConnectionMenu))
            {
                menu.AddItem(connectionSubmenuBtn);
                connectionSubmenuBtn.SetRightLabel("→→→");
            }
            if (cf.IsAllowed(Permission.MSShowCoordinates))
            {
                menu.AddItem(coords);
            }
            if (cf.IsAllowed(Permission.MSShowLocation))
            {
                menu.AddItem(showLocation);
            }
            if (cf.IsAllowed(Permission.MSJoinQuitNotifs))
            {
                menu.AddItem(deathNotifs);
            }
            if (cf.IsAllowed(Permission.MSDeathNotifs))
            {
                menu.AddItem(joinQuitNotifs);
            }
            if (cf.IsAllowed(Permission.MSNightVision))
            {
                menu.AddItem(nightVision);
            }
            if (cf.IsAllowed(Permission.MSThermalVision))
            {
                menu.AddItem(thermalVision);
            }
            if (cf.IsAllowed(Permission.MSLocationBlips))
            {
                menu.AddItem(locationBlips);
                ToggleBlips(ShowLocationBlips);
            }
            if (cf.IsAllowed(Permission.MSPlayerBlips))
            {
                menu.AddItem(playerBlips);
            }
            if (cf.IsAllowed(Permission.MSTeleportLocations))
            {
                menu.AddItem(teleportMenuBtn);
                teleportMenuBtn.SetRightLabel("→→→");

                string json = LoadResourceFile(GetCurrentResourceName(), "config/locations.json");
                if (string.IsNullOrEmpty(json))
                {
                    Notify.Error("An error occurred while loading the locations file.");
                }
                else
                {
                    try
                    {
                        Newtonsoft.Json.Linq.JObject data = JsonConvert.DeserializeObject <Newtonsoft.Json.Linq.JObject>(json);
                        foreach (Newtonsoft.Json.Linq.JToken teleport in data["teleports"])
                        {
                            string     name        = teleport["name"].ToString();
                            float      heading     = (float)teleport["heading"];
                            Vector3    coordinates = new Vector3((float)teleport["coordinates"]["x"], (float)teleport["coordinates"]["y"], (float)teleport["coordinates"]["z"]);
                            UIMenuItem tpBtn       = new UIMenuItem(name, $"Teleport to X: {(int)coordinates.X} Y: {(int)coordinates.Y} Z: {(int)coordinates.Z} HEADING: {(int)heading}.");
                            teleportMenu.AddItem(tpBtn);
                            tpLocations.Add(coordinates);
                            tpLocationsHeading.Add(heading);
                        }
                        teleportMenu.OnItemSelect += async(sender, item, index) =>
                        {
                            await cf.TeleportToCoords(tpLocations[index], true);

                            SetEntityHeading(PlayerPedId(), tpLocationsHeading[index]);
                        };
                    }
                    catch (JsonReaderException ex)
                    {
                        Debug.Write($"\n[vMenu] An error occurred whie loading the teleport locations!\nReport the following error details to the server owner:\n{ex.Message}.\n");
                    }
                }
            }
            if (cf.IsAllowed(Permission.MSClearArea))
            {
                menu.AddItem(clearArea);
            }

            // Always allowed
            // menu.AddItem(hideRadar);
            menu.AddItem(hideHud);
            menu.AddItem(lockCamX);
            // menu.AddItem(lockCamY);
            menu.AddItem(saveSettings);

            // Handle checkbox changes.
            menu.OnCheckboxChange += (sender, item, _checked) =>
            {
                if (item == speedKmh)
                {
                    ShowSpeedoKmh = _checked;
                }
                else if (item == speedMph)
                {
                    ShowSpeedoMph = _checked;
                }
                else if (item == coords)
                {
                    ShowCoordinates = _checked;
                }
                else if (item == hideHud)
                {
                    HideHud = _checked;
                }
                else if (item == hideRadar)
                {
                    HideRadar = _checked;
                    if (!_checked)
                    {
                        DisplayRadar(true);
                    }
                }
                else if (item == showLocation)
                {
                    ShowLocation = _checked;
                }
                else if (item == deathNotifs)
                {
                    DeathNotifications = _checked;
                }
                else if (item == joinQuitNotifs)
                {
                    JoinQuitNotifications = _checked;
                }
                else if (item == nightVision)
                {
                    SetNightvision(_checked);
                }
                else if (item == thermalVision)
                {
                    SetSeethrough(_checked);
                }
                else if (item == lockCamX)
                {
                    LockCameraX = _checked;
                }
                else if (item == lockCamY)
                {
                    LockCameraY = _checked;
                }
                else if (item == locationBlips)
                {
                    ToggleBlips(_checked);
                    ShowLocationBlips = _checked;
                }
                else if (item == playerBlips)
                {
                    ShowPlayerBlips = _checked;
                }
            };

            // Handle button presses.
            menu.OnItemSelect += (sender, item, index) =>
            {
                // Teleport to waypoint.
                if (item == tptowp)
                {
                    cf.TeleportToWp();
                }
                // save settings
                else if (item == saveSettings)
                {
                    UserDefaults.SaveSettings();
                }
                // clear area
                else if (item == clearArea)
                {
                    var pos = Game.PlayerPed.Position;
                    ClearAreaOfEverything(pos.X, pos.Y, pos.Z, 100f, false, false, false, false);
                }
            };
        }
示例#24
0
        /// <summary>
        /// Creates the menu.
        /// </summary>
        private void CreateMenu()
        {
            // Menu
            menu = new Menu(GetSafePlayerName(Game.Player.Name), "Personal Vehicle Options");

            // menu items
            MenuItem setVehice = new MenuItem("Set Vehicle", "Sets your current vehicle as your personal vehicle. If you already have a personal vehicle set then this will override your selection.")
            {
                Label = "Current Vehicle: None"
            };
            MenuItem     toggleEngine = new MenuItem("Toggle Engine", "Toggles the engine on or off, even when you're not inside of the vehicle. This does not work if someone else is currently using your vehicle.");
            MenuListItem toggleLights = new MenuListItem("Set Vehicle Lights", new List <string>()
            {
                "Force On", "Force Off", "Reset"
            }, 0, "This will enable or disable your vehicle headlights, the engine of your vehicle needs to be running for this to work.");
            MenuItem kickAllPassengers = new MenuItem("Kick Passengers", "This will remove all passengers from your personal vehicle.");
            //MenuItem
            MenuItem         lockDoors   = new MenuItem("Lock Vehicle Doors", "This will lock all your vehicle doors for all players. Anyone already inside will always be able to leave the vehicle, even if the doors are locked.");
            MenuItem         unlockDoors = new MenuItem("Unlock Vehicle Doors", "This will unlock all your vehicle doors for all players.");
            MenuItem         soundHorn   = new MenuItem("Sound Horn", "Sounds the horn of the vehicle.");
            MenuItem         toggleAlarm = new MenuItem("Toggle Alarm Sound", "Toggles the vehicle alarm sound on or off. This does not set an alarm. It only toggles the current sounding status of the alarm.");
            MenuCheckboxItem enableBlip  = new MenuCheckboxItem("Add Blip For Personal Vehicle", "Enables or disables the blip that gets added when you mark a vehicle as your personal vehicle.", EnableVehicleBlip)
            {
                Style = MenuCheckboxItem.CheckboxStyle.Cross
            };
            MenuCheckboxItem exclusiveDriver = new MenuCheckboxItem("Exclusive Driver", "If enabled, then you will be the only one that can enter the drivers seat. Other players will not be able to drive the car. They can still be passengers.", false)
            {
                Style = MenuCheckboxItem.CheckboxStyle.Cross
            };

            // This is always allowed if this submenu is created/allowed.
            menu.AddMenuItem(setVehice);

            // Add conditional features.

            // Toggle engine.
            if (IsAllowed(Permission.PVToggleEngine))
            {
                menu.AddMenuItem(toggleEngine);
            }

            // Toggle lights
            if (IsAllowed(Permission.PVToggleLights))
            {
                menu.AddMenuItem(toggleLights);
            }

            // Kick vehicle passengers
            if (IsAllowed(Permission.PVKickPassengers))
            {
                menu.AddMenuItem(kickAllPassengers);
            }

            // Lock and unlock vehicle doors
            if (IsAllowed(Permission.PVLockDoors))
            {
                menu.AddMenuItem(lockDoors);
                menu.AddMenuItem(unlockDoors);
            }

            // Sound horn
            if (IsAllowed(Permission.PVSoundHorn))
            {
                menu.AddMenuItem(soundHorn);
            }

            // Toggle alarm sound
            if (IsAllowed(Permission.PVToggleAlarm))
            {
                menu.AddMenuItem(toggleAlarm);
            }

            // Enable blip for personal vehicle
            if (IsAllowed(Permission.PVAddBlip))
            {
                menu.AddMenuItem(enableBlip);
            }

            if (IsAllowed(Permission.PVExclusiveDriver))
            {
                menu.AddMenuItem(exclusiveDriver);
            }


            // Handle list presses
            menu.OnListItemSelect += (sender, item, itemIndex, index) =>
            {
                var veh = CurrentPersonalVehicle;
                if (veh != null && veh.Exists())
                {
                    if (!NetworkHasControlOfEntity(CurrentPersonalVehicle.Handle))
                    {
                        if (!NetworkRequestControlOfEntity(CurrentPersonalVehicle.Handle))
                        {
                            Notify.Error("You currently can't control this vehicle. Is someone else currently driving your car? Please try again after making sure other players are not controlling your vehicle.");
                            return;
                        }
                    }

                    if (item == toggleLights)
                    {
                        if (itemIndex == 0)
                        {
                            SetVehicleLights(CurrentPersonalVehicle.Handle, 3);
                        }
                        else if (itemIndex == 1)
                        {
                            SetVehicleLights(CurrentPersonalVehicle.Handle, 1);
                        }
                        else
                        {
                            SetVehicleLights(CurrentPersonalVehicle.Handle, 0);
                        }
                    }
                }
                else
                {
                    Notify.Error("You have not yet selected a personal vehicle, or your vehicle has been deleted. Set a personal vehicle before you can use these options.");
                }
            };

            // Handle checkbox changes
            menu.OnCheckboxChange += (sender, item, index, _checked) =>
            {
                if (item == enableBlip)
                {
                    EnableVehicleBlip = _checked;
                    if (EnableVehicleBlip)
                    {
                        if (CurrentPersonalVehicle != null && CurrentPersonalVehicle.Exists())
                        {
                            if (CurrentPersonalVehicle.AttachedBlip == null || !CurrentPersonalVehicle.AttachedBlip.Exists())
                            {
                                CurrentPersonalVehicle.AttachBlip();
                            }
                            CurrentPersonalVehicle.AttachedBlip.Sprite = BlipSprite.PersonalVehicleCar;
                            CurrentPersonalVehicle.AttachedBlip.Name   = "Personal Vehicle";
                        }
                        else
                        {
                            Notify.Error("You have not yet selected a personal vehicle, or your vehicle has been deleted. Set a personal vehicle before you can use these options.");
                        }
                    }
                    else
                    {
                        if (CurrentPersonalVehicle != null && CurrentPersonalVehicle.Exists() && CurrentPersonalVehicle.AttachedBlip != null && CurrentPersonalVehicle.AttachedBlip.Exists())
                        {
                            CurrentPersonalVehicle.AttachedBlip.Delete();
                        }
                    }
                }
                else if (item == exclusiveDriver)
                {
                    if (CurrentPersonalVehicle != null && CurrentPersonalVehicle.Exists())
                    {
                        if (NetworkRequestControlOfEntity(CurrentPersonalVehicle.Handle))
                        {
                            if (_checked)
                            {
                                SetVehicleExclusiveDriver(CurrentPersonalVehicle.Handle, Game.PlayerPed.Handle);
                                SetVehicleExclusiveDriver_2(CurrentPersonalVehicle.Handle, Game.PlayerPed.Handle, 1);
                            }
                            else
                            {
                                SetVehicleExclusiveDriver(CurrentPersonalVehicle.Handle, 0);
                                SetVehicleExclusiveDriver_2(CurrentPersonalVehicle.Handle, 0, 1);
                            }
                        }
                        else
                        {
                            item.Checked = !_checked;
                            Notify.Error("You currently can't control this vehicle. Is someone else currently driving your car? Please try again after making sure other players are not controlling your vehicle.");
                        }
                    }
                }
            };

            // Handle button presses.
            menu.OnItemSelect += (sender, item, index) =>
            {
                if (item == setVehice)
                {
                    if (Game.PlayerPed.IsInVehicle())
                    {
                        var veh = GetVehicle();
                        if (veh != null && veh.Exists())
                        {
                            if (Game.PlayerPed == veh.Driver)
                            {
                                CurrentPersonalVehicle      = veh;
                                veh.PreviouslyOwnedByPlayer = true;
                                veh.IsPersistent            = true;
                                if (EnableVehicleBlip && IsAllowed(Permission.PVAddBlip))
                                {
                                    if (veh.AttachedBlip == null || !veh.AttachedBlip.Exists())
                                    {
                                        veh.AttachBlip();
                                    }
                                    veh.AttachedBlip.Sprite = BlipSprite.PersonalVehicleCar;
                                    veh.AttachedBlip.Name   = "Personal Vehicle";
                                }
                                var name = GetLabelText(veh.DisplayName);
                                if (string.IsNullOrEmpty(name) || name.ToLower() == "null")
                                {
                                    name = veh.DisplayName;
                                }
                                item.Label = $"Current Vehicle: {name}";
                            }
                            else
                            {
                                Notify.Error(CommonErrors.NeedToBeTheDriver);
                            }
                        }
                        else
                        {
                            Notify.Error(CommonErrors.NoVehicle);
                        }
                    }
                    else
                    {
                        Notify.Error(CommonErrors.NoVehicle);
                    }
                }
                else if (CurrentPersonalVehicle != null && CurrentPersonalVehicle.Exists())
                {
                    if (item == kickAllPassengers)
                    {
                        if (CurrentPersonalVehicle.Occupants.Count() > 0 && CurrentPersonalVehicle.Occupants.Any(p => p != Game.PlayerPed))
                        {
                            var netId = VehToNet(CurrentPersonalVehicle.Handle);
                            TriggerServerEvent("vMenu:GetOutOfCar", netId, Game.Player.ServerId);
                        }
                        else
                        {
                            Notify.Info("There are no other players in your vehicle that need to be kicked out.");
                        }
                    }
                    else
                    {
                        if (!NetworkHasControlOfEntity(CurrentPersonalVehicle.Handle))
                        {
                            if (!NetworkRequestControlOfEntity(CurrentPersonalVehicle.Handle))
                            {
                                Notify.Error("You currently can't control this vehicle. Is someone else currently driving your car? Please try again after making sure other players are not controlling your vehicle.");
                                return;
                            }
                        }

                        if (item == toggleEngine)
                        {
                            SetVehicleEngineOn(CurrentPersonalVehicle.Handle, !CurrentPersonalVehicle.IsEngineRunning, true, true);
                        }

                        else if (item == lockDoors || item == unlockDoors)
                        {
                            bool _lock = item == lockDoors;
                            LockOrUnlockDoors(CurrentPersonalVehicle, _lock);
                        }

                        else if (item == soundHorn)
                        {
                            SoundHorn(CurrentPersonalVehicle);
                        }

                        else if (item == toggleAlarm)
                        {
                            ToggleVehicleAlarm(CurrentPersonalVehicle);
                        }
                    }
                }
                else
                {
                    Notify.Error("You have not yet selected a personal vehicle, or your vehicle has been deleted. Set a personal vehicle before you can use these options.");
                }
            };
        }
示例#25
0
        /// <summary>
        /// Creates the menu.
        /// </summary>
        private void CreateMenu()
        {
            #region create main weapon options menu and add items
            // Create the menu.
            menu = new UIMenu(GetPlayerName(PlayerId()), "Weapon Options", true)
            {
                ScaleWithSafezone       = false,
                MouseControlsEnabled    = false,
                MouseEdgeEnabled        = false,
                ControlDisablingEnabled = false
            };

            UIMenuItem         getAllWeapons    = new UIMenuItem("Get All Weapons", "Get all weapons.");
            UIMenuItem         removeAllWeapons = new UIMenuItem("Remove All Weapons", "Removes all weapons in your inventory.");
            UIMenuCheckboxItem unlimitedAmmo    = new UIMenuCheckboxItem("Unlimited Ammo", UnlimitedAmmo, "Unlimited ammonition supply.");
            UIMenuCheckboxItem noReload         = new UIMenuCheckboxItem("No Reload", NoReload, "Never reload.");
            UIMenuItem         setAmmo          = new UIMenuItem("Set All Ammo Count", "Set the amount of ammo in all your weapons.");
            UIMenuItem         refillMaxAmmo    = new UIMenuItem("Refill All Ammo", "Give all your weapons max ammo.");
            ValidWeapons       vw          = new ValidWeapons();
            UIMenuItem         spawnByName = new UIMenuItem("Spawn Weapon By Name", "Enter a weapon mode name to spawn.");

            // Add items based on permissions
            if (cf.IsAllowed(Permission.WPGetAll))
            {
                menu.AddItem(getAllWeapons);
            }
            if (cf.IsAllowed(Permission.WPRemoveAll))
            {
                menu.AddItem(removeAllWeapons);
            }
            if (cf.IsAllowed(Permission.WPUnlimitedAmmo))
            {
                menu.AddItem(unlimitedAmmo);
            }
            if (cf.IsAllowed(Permission.WPNoReload))
            {
                menu.AddItem(noReload);
            }
            if (cf.IsAllowed(Permission.WPSetAllAmmo))
            {
                menu.AddItem(setAmmo);
                menu.AddItem(refillMaxAmmo);
            }
            if (cf.IsAllowed(Permission.WPSpawn))
            {
                menu.AddItem(spawnByName);
            }
            #endregion

            #region addonweapons submenu
            UIMenuItem addonWeaponsBtn  = new UIMenuItem("Addon Weapons", "Equip / remove addon weapons available on this server.");
            UIMenu     addonWeaponsMenu = new UIMenu("Addon Weapons", "Equip/Remove Addon Weapons", true)
            {
                MouseControlsEnabled    = false,
                MouseEdgeEnabled        = false,
                ControlDisablingEnabled = false,
                ScaleWithSafezone       = false
            };
            menu.AddItem(addonWeaponsBtn);

            #region manage creating and accessing addon weapons menu
            if (cf.IsAllowed(Permission.WPSpawn) && AddonWeapons != null && AddonWeapons.Count > 0)
            {
                menu.BindMenuToItem(addonWeaponsMenu, addonWeaponsBtn);
                foreach (KeyValuePair <string, uint> weapon in AddonWeapons)
                {
                    string name  = weapon.Key.ToString();
                    uint   model = weapon.Value;
                    var    item  = new UIMenuItem(name, $"Click to add/remove this weapon ({name}) to/from your inventory.");
                    addonWeaponsMenu.AddItem(item);
                    if (!IsWeaponValid(model))
                    {
                        item.Enabled = false;
                        item.SetLeftBadge(UIMenuItem.BadgeStyle.Lock);
                        item.Description = "This model is not available. Please ask the server owner to verify it's being streamed correctly.";
                    }
                }
                addonWeaponsMenu.OnItemSelect += (sender, item, index) =>
                {
                    var weapon = AddonWeapons.ElementAt(index);
                    if (HasPedGotWeapon(PlayerPedId(), weapon.Value, false))
                    {
                        RemoveWeaponFromPed(PlayerPedId(), weapon.Value);
                    }
                    else
                    {
                        var maxAmmo = 200;
                        GetMaxAmmo(PlayerPedId(), weapon.Value, ref maxAmmo);
                        GiveWeaponToPed(PlayerPedId(), weapon.Value, maxAmmo, false, true);
                    }
                };
                addonWeaponsBtn.SetRightLabel("→→→");
            }
            else
            {
                addonWeaponsBtn.SetLeftBadge(UIMenuItem.BadgeStyle.Lock);
                addonWeaponsBtn.Enabled     = false;
                addonWeaponsBtn.Description = "This option is not available on this server because you don't have permission to use it, or it is not setup correctly.";
            }
            #endregion

            addonWeaponsMenu.RefreshIndex();
            addonWeaponsMenu.UpdateScaleform();
            #endregion

            #region parachute options menu
            #region parachute buttons and submenus
            UIMenuItem parachuteBtn  = new UIMenuItem("Parachute Options", "All parachute related options can be changed here.");
            UIMenu     parachuteMenu = new UIMenu("Parachute Options", "Parachute Options", true)
            {
                MouseEdgeEnabled        = false,
                MouseControlsEnabled    = false,
                ControlDisablingEnabled = false,
                ScaleWithSafezone       = false
            };

            UIMenu primaryChute = new UIMenu("Parachute Options", "Select A Primary Parachute", true)
            {
                MouseControlsEnabled    = false,
                MouseEdgeEnabled        = false,
                ControlDisablingEnabled = false,
                ScaleWithSafezone       = false
            };

            UIMenu secondaryChute = new UIMenu("Parachute Options", "Select A Reserve Parachute", true)
            {
                MouseControlsEnabled    = false,
                MouseEdgeEnabled        = false,
                ControlDisablingEnabled = false,
                ScaleWithSafezone       = false
            };

            UIMenuItem chute    = new UIMenuItem("No Style", "Default parachute.");
            UIMenuItem chute0   = new UIMenuItem(GetLabelText("PM_TINT0"), GetLabelText("PD_TINT0"));            // Rainbow Chute
            UIMenuItem chute1   = new UIMenuItem(GetLabelText("PM_TINT1"), GetLabelText("PD_TINT1"));            // Red Chute
            UIMenuItem chute2   = new UIMenuItem(GetLabelText("PM_TINT2"), GetLabelText("PD_TINT2"));            // Seaside Stripes Chute
            UIMenuItem chute3   = new UIMenuItem(GetLabelText("PM_TINT3"), GetLabelText("PD_TINT3"));            // Window Maker Chute
            UIMenuItem chute4   = new UIMenuItem(GetLabelText("PM_TINT4"), GetLabelText("PD_TINT4"));            // Patriot Chute
            UIMenuItem chute5   = new UIMenuItem(GetLabelText("PM_TINT5"), GetLabelText("PD_TINT5"));            // Blue Chute
            UIMenuItem chute6   = new UIMenuItem(GetLabelText("PM_TINT6"), GetLabelText("PD_TINT6"));            // Black Chute
            UIMenuItem chute7   = new UIMenuItem(GetLabelText("PM_TINT7"), GetLabelText("PD_TINT7"));            // Hornet Chute
            UIMenuItem chute8   = new UIMenuItem(GetLabelText("PS_CAN_0"), "Air Force parachute.");              // Air Force Chute
            UIMenuItem chute9   = new UIMenuItem(GetLabelText("PM_TINT0"), "Desert parachute.");                 // Desert Chute
            UIMenuItem chute10  = new UIMenuItem("Shadow Chute", "Shadow parachute.");                           // Shadow Chute
            UIMenuItem chute11  = new UIMenuItem(GetLabelText("UNLOCK_NAME_PSRWD"), "High altitude parachute."); // High Altitude Chute
            UIMenuItem chute12  = new UIMenuItem("Airborne Chute", "Airborne parachute.");                       // Airborne Chute
            UIMenuItem chute13  = new UIMenuItem("Sunrise Chute", "Sunrise parachute.");                         // Sunrise Chute
            UIMenuItem rchute   = new UIMenuItem("No Style", "Default parachute.");
            UIMenuItem rchute0  = new UIMenuItem(GetLabelText("PM_TINT0"), GetLabelText("PD_TINT0"));            // Rainbow Chute
            UIMenuItem rchute1  = new UIMenuItem(GetLabelText("PM_TINT1"), GetLabelText("PD_TINT1"));            // Red Chute
            UIMenuItem rchute2  = new UIMenuItem(GetLabelText("PM_TINT2"), GetLabelText("PD_TINT2"));            // Seaside Stripes Chute
            UIMenuItem rchute3  = new UIMenuItem(GetLabelText("PM_TINT3"), GetLabelText("PD_TINT3"));            // Window Maker Chute
            UIMenuItem rchute4  = new UIMenuItem(GetLabelText("PM_TINT4"), GetLabelText("PD_TINT4"));            // Patriot Chute
            UIMenuItem rchute5  = new UIMenuItem(GetLabelText("PM_TINT5"), GetLabelText("PD_TINT5"));            // Blue Chute
            UIMenuItem rchute6  = new UIMenuItem(GetLabelText("PM_TINT6"), GetLabelText("PD_TINT6"));            // Black Chute
            UIMenuItem rchute7  = new UIMenuItem(GetLabelText("PM_TINT7"), GetLabelText("PD_TINT7"));            // Hornet Chute
            UIMenuItem rchute8  = new UIMenuItem(GetLabelText("PS_CAN_0"), "Air Force parachute.");              // Air Force Chute
            UIMenuItem rchute9  = new UIMenuItem(GetLabelText("PM_TINT0"), "Desert parachute.");                 // Desert Chute
            UIMenuItem rchute10 = new UIMenuItem("Shadow Chute", "Shadow parachute.");                           // Shadow Chute
            UIMenuItem rchute11 = new UIMenuItem(GetLabelText("UNLOCK_NAME_PSRWD"), "High altitude parachute."); // High Altitude Chute
            UIMenuItem rchute12 = new UIMenuItem("Airborne Chute", "Airborne parachute.");                       // Airborne Chute
            UIMenuItem rchute13 = new UIMenuItem("Sunrise Chute", "Sunrise parachute.");                         // Sunrise Chute

            primaryChute.AddItem(chute);
            primaryChute.AddItem(chute0);
            primaryChute.AddItem(chute1);
            primaryChute.AddItem(chute2);
            primaryChute.AddItem(chute3);
            primaryChute.AddItem(chute4);
            primaryChute.AddItem(chute5);
            primaryChute.AddItem(chute6);
            primaryChute.AddItem(chute7);
            primaryChute.AddItem(chute8);
            primaryChute.AddItem(chute9);
            primaryChute.AddItem(chute10);
            primaryChute.AddItem(chute11);
            primaryChute.AddItem(chute12);
            primaryChute.AddItem(chute13);

            secondaryChute.AddItem(rchute);
            secondaryChute.AddItem(rchute0);
            secondaryChute.AddItem(rchute1);
            secondaryChute.AddItem(rchute2);
            secondaryChute.AddItem(rchute3);
            secondaryChute.AddItem(rchute4);
            secondaryChute.AddItem(rchute5);
            secondaryChute.AddItem(rchute6);
            secondaryChute.AddItem(rchute7);
            secondaryChute.AddItem(rchute8);
            secondaryChute.AddItem(rchute9);
            secondaryChute.AddItem(rchute10);
            secondaryChute.AddItem(rchute11);
            secondaryChute.AddItem(rchute12);
            secondaryChute.AddItem(rchute13);
            #endregion

            #region handle events
            primaryChute.OnItemSelect += (sender, item, index) =>
            {
                SetPedParachuteTintIndex(PlayerPedId(), index - 1);
                Subtitle.Custom($"Primary parachute style selected: ~r~{item.Text}~s~.");
            };

            secondaryChute.OnItemSelect += (sender, item, index) =>
            {
                SetPlayerReserveParachuteTintIndex(PlayerId(), index - 1);
                Subtitle.Custom($"Reserve parachute style selected: ~r~{item.Text}~s~.");
            };
            #endregion

            #region create more buttons
            UIMenuItem primaryChuteBtn   = new UIMenuItem("Primary Parachute Style", "Select a primary parachute.");
            UIMenuItem secondaryChuteBtn = new UIMenuItem("Reserve Parachute Style", "Select a reserve parachute.");

            parachuteMenu.AddItem(primaryChuteBtn);
            primaryChuteBtn.SetRightLabel("→→→");
            parachuteMenu.AddItem(secondaryChuteBtn);
            secondaryChuteBtn.SetRightLabel("→→→");

            parachuteMenu.BindMenuToItem(primaryChute, primaryChuteBtn);
            parachuteMenu.BindMenuToItem(secondaryChute, secondaryChuteBtn);

            UIMenuCheckboxItem autoEquipParachute = new UIMenuCheckboxItem("Auto Equip Parachute", AutoEquipChute, "Automatically equip a parachute whenever you enter a plane/helicopter.");
            parachuteMenu.AddItem(autoEquipParachute);

            UIMenuItem togglePrimary   = new UIMenuItem("Get / Remove Primary Parachute", "Equip a primary parachute.");
            UIMenuItem toggleSecondary = new UIMenuItem("Get Reserve Parachute", "Equip a reserve parachute, you need to get a primary parachute first before equipping a reserve parachute.");

            parachuteMenu.AddItem(togglePrimary);
            parachuteMenu.AddItem(toggleSecondary);
            #endregion

            #region handle parachute menu events
            parachuteMenu.OnItemSelect += (sender, item, index) =>
            {
                if (item == togglePrimary)
                {
                    if (HasPedGotWeapon(PlayerPedId(), (uint)WeaponHash.Parachute, false))
                    {
                        RemoveWeaponFromPed(PlayerPedId(), (uint)WeaponHash.Parachute);
                        Notify.Success("Primary parachute ~r~removed~s~.", true);
                    }
                    else
                    {
                        GiveWeaponToPed(PlayerPedId(), (uint)WeaponHash.Parachute, 1, false, false);
                        Notify.Success("Primary parachute ~g~equippped~s~.", true);
                    }
                }
                else if (item == toggleSecondary)
                {
                    SetPlayerHasReserveParachute(PlayerId());
                    Notify.Success("Reserve parachute ~g~equippped~s~.", true);
                }
            };

            parachuteMenu.OnCheckboxChange += (sender, item, _checked) =>
            {
                if (item == autoEquipParachute)
                {
                    AutoEquipChute = _checked;
                }
            };
            #endregion

            #region parachute smoke trail colors
            List <dynamic> smokeColor = new List <dynamic>()
            {
                "White",
                "Yellow",
                "Red",
                "Green",
                "Blue",
                "Dark Gray",
            };

            UIMenuListItem smokeColors = new UIMenuListItem("Smoke Trail Color", smokeColor, 0, "Select a parachute smoke trail color.");
            parachuteMenu.AddItem(smokeColors);
            parachuteMenu.OnListChange += (sender, item, index) =>
            {
                if (item == smokeColors)
                {
                    SetPlayerCanLeaveParachuteSmokeTrail(PlayerId(), false);
                    if (index == 0)
                    {
                        SetPlayerParachuteSmokeTrailColor(PlayerId(), 255, 255, 255);
                    }
                    else if (index == 1)
                    {
                        SetPlayerParachuteSmokeTrailColor(PlayerId(), 255, 255, 0);
                    }
                    else if (index == 2)
                    {
                        SetPlayerParachuteSmokeTrailColor(PlayerId(), 255, 0, 0);
                    }
                    else if (index == 3)
                    {
                        SetPlayerParachuteSmokeTrailColor(PlayerId(), 0, 255, 0);
                    }
                    else if (index == 4)
                    {
                        SetPlayerParachuteSmokeTrailColor(PlayerId(), 0, 0, 255);
                    }
                    else if (index == 5)
                    {
                        SetPlayerParachuteSmokeTrailColor(PlayerId(), 1, 1, 1);
                    }

                    SetPlayerCanLeaveParachuteSmokeTrail(PlayerId(), true);
                }
            };
            #endregion

            #region misc parachute menu setup
            menu.AddItem(parachuteBtn);
            parachuteBtn.SetRightLabel("→→→");
            menu.BindMenuToItem(parachuteMenu, parachuteBtn);

            parachuteMenu.RefreshIndex();
            parachuteMenu.UpdateScaleform();

            primaryChute.RefreshIndex();
            primaryChute.UpdateScaleform();

            secondaryChute.RefreshIndex();
            secondaryChute.UpdateScaleform();

            MainMenu.Mp.Add(addonWeaponsMenu);
            MainMenu.Mp.Add(parachuteMenu);
            MainMenu.Mp.Add(primaryChute);
            MainMenu.Mp.Add(secondaryChute);
            #endregion
            #endregion

            #region Create Weapon Category Submenus
            UIMenuItem spacer = cf.GetSpacerMenuItem("↓ Weapon Categories ↓");
            menu.AddItem(spacer);

            UIMenu handGuns = new UIMenu("Weapons", "Handguns", true)
            {
                ScaleWithSafezone       = false,
                ControlDisablingEnabled = false,
                MouseControlsEnabled    = false,
                MouseEdgeEnabled        = false,
            };
            handGuns.SetMenuWidthOffset(50);
            UIMenuItem handGunsBtn = new UIMenuItem("Handguns");

            UIMenu rifles = new UIMenu("Weapons", "Assault Rifles", true)
            {
                ScaleWithSafezone       = false,
                ControlDisablingEnabled = false,
                MouseControlsEnabled    = false,
                MouseEdgeEnabled        = false,
            };
            rifles.SetMenuWidthOffset(50);
            UIMenuItem riflesBtn = new UIMenuItem("Assault Rifles");

            UIMenu shotguns = new UIMenu("Weapons", "Shotguns", true)
            {
                ScaleWithSafezone       = false,
                ControlDisablingEnabled = false,
                MouseControlsEnabled    = false,
                MouseEdgeEnabled        = false,
            };
            shotguns.SetMenuWidthOffset(50);
            UIMenuItem shotgunsBtn = new UIMenuItem("Shotguns");

            UIMenu smgs = new UIMenu("Weapons", "Sub-/Light Machine Guns", true)
            {
                ScaleWithSafezone       = false,
                ControlDisablingEnabled = false,
                MouseControlsEnabled    = false,
                MouseEdgeEnabled        = false,
            };
            smgs.SetMenuWidthOffset(50);
            UIMenuItem smgsBtn = new UIMenuItem("Sub-/Light Machine Guns");

            UIMenu throwables = new UIMenu("Weapons", "Throwables", true)
            {
                ScaleWithSafezone       = false,
                ControlDisablingEnabled = false,
                MouseControlsEnabled    = false,
                MouseEdgeEnabled        = false,
            };
            throwables.SetMenuWidthOffset(50);
            UIMenuItem throwablesBtn = new UIMenuItem("Throwables");

            UIMenu melee = new UIMenu("Weapons", "Melee", true)
            {
                ScaleWithSafezone       = false,
                ControlDisablingEnabled = false,
                MouseControlsEnabled    = false,
                MouseEdgeEnabled        = false,
            };
            melee.SetMenuWidthOffset(50);
            UIMenuItem meleeBtn = new UIMenuItem("Melee");

            UIMenu heavy = new UIMenu("Weapons", "Heavy Weapons", true)
            {
                ScaleWithSafezone       = false,
                ControlDisablingEnabled = false,
                MouseControlsEnabled    = false,
                MouseEdgeEnabled        = false,
            };
            heavy.SetMenuWidthOffset(50);
            UIMenuItem heavyBtn = new UIMenuItem("Heavy Weapons");

            UIMenu snipers = new UIMenu("Weapons", "Sniper Rifles", true)
            {
                ScaleWithSafezone       = false,
                ControlDisablingEnabled = false,
                MouseControlsEnabled    = false,
                MouseEdgeEnabled        = false,
            };
            snipers.SetMenuWidthOffset(50);
            UIMenuItem snipersBtn = new UIMenuItem("Sniper Rifles");

            MainMenu.Mp.Add(handGuns);
            MainMenu.Mp.Add(rifles);
            MainMenu.Mp.Add(shotguns);
            MainMenu.Mp.Add(smgs);
            MainMenu.Mp.Add(throwables);
            MainMenu.Mp.Add(melee);
            MainMenu.Mp.Add(heavy);
            MainMenu.Mp.Add(snipers);
            #endregion

            #region Setup weapon category buttons and submenus.
            handGunsBtn.SetRightLabel("→→→");
            menu.AddItem(handGunsBtn);
            menu.BindMenuToItem(handGuns, handGunsBtn);

            riflesBtn.SetRightLabel("→→→");
            menu.AddItem(riflesBtn);
            menu.BindMenuToItem(rifles, riflesBtn);

            shotgunsBtn.SetRightLabel("→→→");
            menu.AddItem(shotgunsBtn);
            menu.BindMenuToItem(shotguns, shotgunsBtn);

            smgsBtn.SetRightLabel("→→→");
            menu.AddItem(smgsBtn);
            menu.BindMenuToItem(smgs, smgsBtn);

            throwablesBtn.SetRightLabel("→→→");
            menu.AddItem(throwablesBtn);
            menu.BindMenuToItem(throwables, throwablesBtn);

            meleeBtn.SetRightLabel("→→→");
            menu.AddItem(meleeBtn);
            menu.BindMenuToItem(melee, meleeBtn);

            heavyBtn.SetRightLabel("→→→");
            menu.AddItem(heavyBtn);
            menu.BindMenuToItem(heavy, heavyBtn);

            snipersBtn.SetRightLabel("→→→");
            menu.AddItem(snipersBtn);
            menu.BindMenuToItem(snipers, snipersBtn);
            #endregion

            #region Loop through all weapons, create menus for them and add all menu items and handle events.
            foreach (ValidWeapon weapon in vw.WeaponList)
            {
                uint cat = (uint)GetWeapontypeGroup(weapon.Hash);
                if (weapon.Name != null && (cf.IsAllowed(weapon.Perm) || cf.IsAllowed(Permission.WPGetAll)))
                {
                    #region Create menu for this weapon and add buttons
                    UIMenu weaponMenu = new UIMenu("Weapon Options", weapon.Name, true)
                    {
                        ScaleWithSafezone       = false,
                        MouseControlsEnabled    = false,
                        MouseEdgeEnabled        = false,
                        ControlDisablingEnabled = false
                    };
                    UIMenuItem weaponItem = new UIMenuItem(weapon.Name, $"Open the options for ~y~{weapon.Name.ToString()}~s~.");
                    weaponItem.SetRightLabel("→→→");
                    weaponItem.SetLeftBadge(UIMenuItem.BadgeStyle.Gun);

                    MainMenu.Mp.Add(weaponMenu);

                    weaponInfo.Add(weaponMenu, weapon);

                    UIMenuItem getOrRemoveWeapon = new UIMenuItem("Equip/Remove Weapon", "Add or remove this weapon to/form your inventory.");
                    getOrRemoveWeapon.SetLeftBadge(UIMenuItem.BadgeStyle.Gun);
                    weaponMenu.AddItem(getOrRemoveWeapon);
                    if (!cf.IsAllowed(Permission.WPSpawn))
                    {
                        getOrRemoveWeapon.Enabled     = false;
                        getOrRemoveWeapon.Description = "This option has been disabled by the server owner.";
                        getOrRemoveWeapon.SetLeftBadge(UIMenuItem.BadgeStyle.Lock);
                    }

                    UIMenuItem fillAmmo = new UIMenuItem("Re-fill Ammo", "Get max ammo for this weapon.");
                    fillAmmo.SetLeftBadge(UIMenuItem.BadgeStyle.Ammo);
                    weaponMenu.AddItem(fillAmmo);

                    List <dynamic> tints = new List <dynamic>();
                    if (weapon.Name.Contains(" Mk II"))
                    {
                        foreach (var tint in ValidWeapons.WeaponTintsMkII)
                        {
                            tints.Add(tint.Key);
                        }
                    }
                    else
                    {
                        foreach (var tint in ValidWeapons.WeaponTints)
                        {
                            tints.Add(tint.Key);
                        }
                    }

                    UIMenuListItem weaponTints = new UIMenuListItem("Tints", tints, 0, "Select a tint for your weapon.");
                    weaponMenu.AddItem(weaponTints);
                    #endregion

                    #region Handle weapon specific list changes
                    weaponMenu.OnListChange += (sender, item, index) =>
                    {
                        if (item == weaponTints)
                        {
                            if (HasPedGotWeapon(PlayerPedId(), weaponInfo[sender].Hash, false))
                            {
                                SetPedWeaponTintIndex(PlayerPedId(), weaponInfo[sender].Hash, index);
                            }
                            else
                            {
                                Notify.Error("You need to get the weapon first!");
                            }
                        }
                    };
                    #endregion

                    #region Handle weapon specific button presses
                    weaponMenu.OnItemSelect += (sender, item, index) =>
                    {
                        if (item == getOrRemoveWeapon)
                        {
                            var  info = weaponInfo[sender];
                            uint hash = info.Hash;
                            if (HasPedGotWeapon(PlayerPedId(), hash, false))
                            {
                                RemoveWeaponFromPed(PlayerPedId(), hash);
                                Subtitle.Custom("Weapon removed.");
                            }
                            else
                            {
                                var ammo = 255;
                                GetMaxAmmo(PlayerPedId(), hash, ref ammo);
                                GiveWeaponToPed(PlayerPedId(), hash, ammo, false, true);
                                Subtitle.Custom("Weapon added.");
                            }
                        }
                        else if (item == fillAmmo)
                        {
                            if (HasPedGotWeapon(PlayerPedId(), weaponInfo[sender].Hash, false))
                            {
                                var ammo = 900;
                                GetMaxAmmo(PlayerPedId(), weaponInfo[sender].Hash, ref ammo);
                                SetAmmoInClip(PlayerPedId(), weaponInfo[sender].Hash, ammo);
                            }
                            else
                            {
                                Notify.Error("You need to get the weapon first before re-filling ammo!");
                            }
                        }
                    };
                    #endregion

                    #region load components
                    if (weapon.Components != null)
                    {
                        if (weapon.Components.Count > 0)
                        {
                            foreach (var comp in weapon.Components)
                            {
                                UIMenuItem compItem = new UIMenuItem(comp.Key, "Click to equip or remove this component.");
                                weaponComponents.Add(compItem, comp.Key);
                                weaponMenu.AddItem(compItem);

                                #region Handle component button presses
                                weaponMenu.OnItemSelect += (sender, item, index) =>
                                {
                                    if (item == compItem)
                                    {
                                        var Weapon        = weaponInfo[sender];
                                        var componentHash = Weapon.Components[weaponComponents[item]];
                                        if (HasPedGotWeapon(PlayerPedId(), Weapon.Hash, false))
                                        {
                                            if (HasPedGotWeaponComponent(PlayerPedId(), Weapon.Hash, componentHash))
                                            {
                                                RemoveWeaponComponentFromPed(PlayerPedId(), Weapon.Hash, componentHash);
                                                Subtitle.Custom("Component removed.");
                                            }
                                            else
                                            {
                                                GiveWeaponComponentToPed(PlayerPedId(), Weapon.Hash, componentHash);
                                                Subtitle.Custom("Component equiped.");
                                            }
                                        }
                                        else
                                        {
                                            Notify.Error("You need to get the weapon first before you can modify it.");
                                        }
                                    }
                                };
                                #endregion
                            }
                        }
                    }
                    #endregion

                    // refresh and add to menu.
                    weaponMenu.RefreshIndex();
                    weaponMenu.UpdateScaleform();

                    if (cat == 970310034) // 970310034 rifles
                    {
                        rifles.AddItem(weaponItem);
                        rifles.BindMenuToItem(weaponMenu, weaponItem);
                    }
                    else if (cat == 416676503 || cat == 690389602) // 416676503 hand guns // 690389602 stun gun
                    {
                        handGuns.AddItem(weaponItem);
                        handGuns.BindMenuToItem(weaponMenu, weaponItem);
                    }
                    else if (cat == 860033945) // 860033945 shotguns
                    {
                        shotguns.AddItem(weaponItem);
                        shotguns.BindMenuToItem(weaponMenu, weaponItem);
                    }
                    else if (cat == 3337201093 || cat == 1159398588) // 3337201093 sub machine guns // 1159398588 light machine guns
                    {
                        smgs.AddItem(weaponItem);
                        smgs.BindMenuToItem(weaponMenu, weaponItem);
                    }
                    else if (cat == 1548507267 || cat == 4257178988 || cat == 1595662460) // 1548507267 throwables // 4257178988 fire extinghuiser // jerry can
                    {
                        throwables.AddItem(weaponItem);
                        throwables.BindMenuToItem(weaponMenu, weaponItem);
                    }
                    else if (cat == 3566412244 || cat == 2685387236) // 3566412244 melee weapons // 2685387236 knuckle duster
                    {
                        melee.AddItem(weaponItem);
                        melee.BindMenuToItem(weaponMenu, weaponItem);
                    }
                    else if (cat == 2725924767) // 2725924767 heavy weapons
                    {
                        heavy.AddItem(weaponItem);
                        heavy.BindMenuToItem(weaponMenu, weaponItem);
                    }
                    else if (cat == 3082541095) // 3082541095 sniper rifles
                    {
                        snipers.AddItem(weaponItem);
                        snipers.BindMenuToItem(weaponMenu, weaponItem);
                    }
                }
            }
            #endregion

            #region Disable submenus if no weapons in that category are allowed.
            if (handGuns.MenuItems.Count == 0)
            {
                menu.ReleaseMenuFromItem(handGunsBtn);
                handGunsBtn.SetLeftBadge(UIMenuItem.BadgeStyle.Lock);
                handGunsBtn.Description = "The server owner removed the permissions for all weapons in this category.";
                handGunsBtn.Enabled     = false;
            }
            if (rifles.MenuItems.Count == 0)
            {
                menu.ReleaseMenuFromItem(riflesBtn);
                riflesBtn.SetLeftBadge(UIMenuItem.BadgeStyle.Lock);
                riflesBtn.Description = "The server owner removed the permissions for all weapons in this category.";
                riflesBtn.Enabled     = false;
            }
            if (shotguns.MenuItems.Count == 0)
            {
                menu.ReleaseMenuFromItem(shotgunsBtn);
                shotgunsBtn.SetLeftBadge(UIMenuItem.BadgeStyle.Lock);
                shotgunsBtn.Description = "The server owner removed the permissions for all weapons in this category.";
                shotgunsBtn.Enabled     = false;
            }
            if (smgs.MenuItems.Count == 0)
            {
                menu.ReleaseMenuFromItem(smgsBtn);
                smgsBtn.SetLeftBadge(UIMenuItem.BadgeStyle.Lock);
                smgsBtn.Description = "The server owner removed the permissions for all weapons in this category.";
                smgsBtn.Enabled     = false;
            }
            if (throwables.MenuItems.Count == 0)
            {
                menu.ReleaseMenuFromItem(throwablesBtn);
                throwablesBtn.SetLeftBadge(UIMenuItem.BadgeStyle.Lock);
                throwablesBtn.Description = "The server owner removed the permissions for all weapons in this category.";
                throwablesBtn.Enabled     = false;
            }
            if (melee.MenuItems.Count == 0)
            {
                menu.ReleaseMenuFromItem(meleeBtn);
                meleeBtn.SetLeftBadge(UIMenuItem.BadgeStyle.Lock);
                meleeBtn.Description = "The server owner removed the permissions for all weapons in this category.";
                meleeBtn.Enabled     = false;
            }
            if (heavy.MenuItems.Count == 0)
            {
                menu.ReleaseMenuFromItem(heavyBtn);
                heavyBtn.SetLeftBadge(UIMenuItem.BadgeStyle.Lock);
                heavyBtn.Description = "The server owner removed the permissions for all weapons in this category.";
                heavyBtn.Enabled     = false;
            }
            if (snipers.MenuItems.Count == 0)
            {
                menu.ReleaseMenuFromItem(snipersBtn);
                snipersBtn.SetLeftBadge(UIMenuItem.BadgeStyle.Lock);
                snipersBtn.Description = "The server owner removed the permissions for all weapons in this category.";
                snipersBtn.Enabled     = false;
            }
            #endregion

            #region Handle button presses
            menu.OnItemSelect += (sender, item, index) =>
            {
                Ped ped = new Ped(PlayerPedId());
                if (item == getAllWeapons)
                {
                    foreach (var weapon in ValidWeapons.Weapons)
                    {
                        var ammo = 255;
                        GetMaxAmmo(PlayerPedId(), weapon.Value, ref ammo);
                        ped.Weapons.Give((WeaponHash)weapon.Value, ammo, weapon.Key == "Unarmed", true);
                    }
                    ped.Weapons.Give(WeaponHash.Unarmed, 0, true, true);
                }
                else if (item == removeAllWeapons)
                {
                    ped.Weapons.RemoveAll();
                }
                else if (item == setAmmo)
                {
                    cf.SetAllWeaponsAmmo();
                }
                else if (item == refillMaxAmmo)
                {
                    foreach (var wp in ValidWeapons.Weapons)
                    {
                        if (ped.Weapons.HasWeapon((WeaponHash)wp.Value))
                        {
                            int maxammo = 200;
                            GetMaxAmmo(ped.Handle, wp.Value, ref maxammo);
                            SetPedAmmo(ped.Handle, wp.Value, maxammo);
                        }
                    }
                }
                else if (item == spawnByName)
                {
                    cf.SpawnCustomWeapon();
                }
            };
            #endregion

            #region Handle checkbox changes
            menu.OnCheckboxChange += (sender, item, _checked) =>
            {
                if (item == noReload)
                {
                    NoReload = _checked;
                    Subtitle.Custom($"No reload is now {(_checked ? "enabled" : "disabled")}.");
                }
                else if (item == unlimitedAmmo)
                {
                    UnlimitedAmmo = _checked;
                    Subtitle.Custom($"Unlimited ammo is now {(_checked ? "enabled" : "disabled")}.");
                }
            };
            #endregion
        }
示例#26
0
        /// <summary>
        /// Creates the menu.
        /// </summary>
        private void CreateMenu()
        {
            #region create menu and menu items
            // Create the menu.
            menu = new Menu("YDDY:RP", "Меню настроек персонажа");

            // Create all checkboxes.
            MenuCheckboxItem playerGodModeCheckbox    = new MenuCheckboxItem("Godmode", "Makes you invincible.", PlayerGodMode);
            MenuCheckboxItem invisibleCheckbox        = new MenuCheckboxItem("Невидимый", "Делает персонажа невидимым. Как шляпа-невидимка.", PlayerInvisible);
            MenuCheckboxItem unlimitedStaminaCheckbox = new MenuCheckboxItem("Unlimited Stamina", "Allows you to run forever without slowing down or taking damage.", PlayerStamina);
            MenuCheckboxItem fastRunCheckbox          = new MenuCheckboxItem("Fast Run", "Get ~g~Snail~s~ powers and run very fast!", PlayerFastRun);
            SetRunSprintMultiplierForPlayer(Game.Player.Handle, (PlayerFastRun && IsAllowed(Permission.POFastRun) ? 1.49f : 1f));
            MenuCheckboxItem fastSwimCheckbox = new MenuCheckboxItem("Fast Swim", "Get ~g~Snail 2.0~s~ powers and swim super fast!", PlayerFastSwim);
            SetSwimMultiplierForPlayer(Game.Player.Handle, (PlayerFastSwim && IsAllowed(Permission.POFastSwim) ? 1.49f : 1f));
            MenuCheckboxItem superJumpCheckbox             = new MenuCheckboxItem("Super Jump", "Get ~g~Snail 3.0~s~ powers and jump like a champ!", PlayerSuperJump);
            MenuCheckboxItem noRagdollCheckbox             = new MenuCheckboxItem("No Ragdoll", "Disables player ragdoll, makes you not fall off your bike anymore.", PlayerNoRagdoll);
            MenuCheckboxItem neverWantedCheckbox           = new MenuCheckboxItem("Never Wanted", "Disables all wanted levels.", PlayerNeverWanted);
            MenuCheckboxItem everyoneIgnoresPlayerCheckbox = new MenuCheckboxItem("Игнорировать персонажа", "Все оставят вас в покое.", PlayerIsIgnored);
            MenuCheckboxItem playerStayInVehicleCheckbox   = new MenuCheckboxItem("Stay In Vehicle", "When this is enabled, NPCs will not be able to drag you out of your vehicle if they get angry at you.", PlayerStayInVehicle);
            MenuCheckboxItem playerFrozenCheckbox          = new MenuCheckboxItem("Заморозить персонажа", "Как в криокамере!", PlayerFrozen);

            // Wanted level options
            List <string> wantedLevelList = new List <string> {
                "No Wanted Level", "1", "2", "3", "4", "5"
            };
            MenuListItem setWantedLevel = new MenuListItem("Set Wanted Level", wantedLevelList, GetPlayerWantedLevel(Game.Player.Handle), "Set your wanted level by selecting a value, and pressing enter.");
            MenuListItem setArmorItem   = new MenuListItem("Set Armor Type", new List <string> {
                "No Armor", GetLabelText("WT_BA_0"), GetLabelText("WT_BA_1"), GetLabelText("WT_BA_2"), GetLabelText("WT_BA_3"), GetLabelText("WT_BA_4"),
            }, 0, "Set the armor level/type for your player.");

            MenuItem healPlayerBtn    = new MenuItem("Heal Player", "Give the player max health.");
            MenuItem cleanPlayerBtn   = new MenuItem("Очистить одежду", "Убрать засохшую кровь одной кнопкой.");
            MenuItem dryPlayerBtn     = new MenuItem("Высушить одежду", "На 20% безопаснее, чем промышленным феном.");
            MenuItem wetPlayerBtn     = new MenuItem("Намочить одежду", "Ну вот опять.");
            MenuItem suicidePlayerBtn = new MenuItem("~r~Самоубийство", "Съесть 6 аскорбинок или воспользоваться пистолетом?");

            Menu vehicleAutoPilot = new Menu("Auto Pilot", "Vehicle auto pilot options.");

            MenuController.AddSubmenu(menu, vehicleAutoPilot);

            MenuItem vehicleAutoPilotBtn = new MenuItem("Vehicle Auto Pilot Menu", "Manage vehicle auto pilot options.")
            {
                Label = "→→→"
            };

            List <string> drivingStyles = new List <string>()
            {
                "Normal", "Rushed", "Avoid highways", "Drive in reverse", "Custom"
            };
            MenuListItem drivingStyle = new MenuListItem("Driving Style", drivingStyles, 0, "Set the driving style that is used for the Drive to Waypoint and Drive Around Randomly functions.");

            // Scenarios (list can be found in the PedScenarios class)
            MenuListItem playerScenarios = new MenuListItem("Анимации", PedScenarios.Scenarios, 0, "Enter - выбрать/отменить анимацию.");
            MenuItem     stopScenario    = new MenuItem("Отменить анимацию", "Отменяет выполнение анимации за 0.22 мс.");
            #endregion

            #region add items to menu based on permissions
            // Add all checkboxes to the menu. (keeping permissions in mind)
            if (IsAllowed(Permission.POGod))
            {
                menu.AddMenuItem(playerGodModeCheckbox);
            }
            if (IsAllowed(Permission.POInvisible))
            {
                menu.AddMenuItem(invisibleCheckbox);
            }
            if (IsAllowed(Permission.POUnlimitedStamina))
            {
                menu.AddMenuItem(unlimitedStaminaCheckbox);
            }
            if (IsAllowed(Permission.POFastRun))
            {
                menu.AddMenuItem(fastRunCheckbox);
            }
            if (IsAllowed(Permission.POFastSwim))
            {
                menu.AddMenuItem(fastSwimCheckbox);
            }
            if (IsAllowed(Permission.POSuperjump))
            {
                menu.AddMenuItem(superJumpCheckbox);
            }
            if (IsAllowed(Permission.PONoRagdoll))
            {
                menu.AddMenuItem(noRagdollCheckbox);
            }
            if (IsAllowed(Permission.PONeverWanted))
            {
                menu.AddMenuItem(neverWantedCheckbox);
            }
            if (IsAllowed(Permission.POSetWanted))
            {
                menu.AddMenuItem(setWantedLevel);
            }
            if (IsAllowed(Permission.POIgnored))
            {
                menu.AddMenuItem(everyoneIgnoresPlayerCheckbox);
            }
            if (IsAllowed(Permission.POStayInVehicle))
            {
                menu.AddMenuItem(playerStayInVehicleCheckbox);
            }
            if (IsAllowed(Permission.POMaxHealth))
            {
                menu.AddMenuItem(healPlayerBtn);
            }
            if (IsAllowed(Permission.POMaxArmor))
            {
                menu.AddMenuItem(setArmorItem);
            }
            if (IsAllowed(Permission.POCleanPlayer))
            {
                menu.AddMenuItem(cleanPlayerBtn);
            }
            if (IsAllowed(Permission.PODryPlayer))
            {
                menu.AddMenuItem(dryPlayerBtn);
            }
            if (IsAllowed(Permission.POWetPlayer))
            {
                menu.AddMenuItem(wetPlayerBtn);
            }

            menu.AddMenuItem(suicidePlayerBtn);

            if (IsAllowed(Permission.POVehicleAutoPilotMenu))
            {
                menu.AddMenuItem(vehicleAutoPilotBtn);
                MenuController.BindMenuItem(menu, vehicleAutoPilot, vehicleAutoPilotBtn);

                vehicleAutoPilot.AddMenuItem(drivingStyle);

                MenuItem startDrivingWaypoint = new MenuItem("Drive To Waypoint", "Make your player ped drive your vehicle to your waypoint.");
                MenuItem startDrivingRandomly = new MenuItem("Drive Around Randomly", "Make your player ped drive your vehicle randomly around the map.");
                MenuItem stopDriving          = new MenuItem("Stop Driving", "The player ped will find a suitable place to stop the vehicle. The task will be stopped once the vehicle has reached the suitable stop location.");
                MenuItem forceStopDriving     = new MenuItem("Force Stop Driving", "This will stop the driving task immediately without finding a suitable place to stop.");
                MenuItem customDrivingStyle   = new MenuItem("Custom Driving Style", "Select a custom driving style. Make sure to also enable it by selecting the 'Custom' driving style in the driving styles list.")
                {
                    Label = "→→→"
                };
                MenuController.AddSubmenu(vehicleAutoPilot, CustomDrivingStyleMenu);
                vehicleAutoPilot.AddMenuItem(customDrivingStyle);
                MenuController.BindMenuItem(vehicleAutoPilot, CustomDrivingStyleMenu, customDrivingStyle);
                Dictionary <int, string> knownNames = new Dictionary <int, string>()
                {
                    { 0, "Stop before vehicles" },
                    { 1, "Stop before peds" },
                    { 2, "Avoid vehicles" },
                    { 3, "Avoid empty vehicles" },
                    { 4, "Avoid peds" },
                    { 5, "Avoid objects" },

                    { 7, "Stop at traffic lights" },
                    { 8, "Use blinkers" },
                    { 9, "Allow going wrong way" },
                    { 10, "Go in reverse gear" },

                    { 18, "Use shortest path" },

                    { 22, "Ignore roads" },

                    { 24, "Ignore all pathing" },

                    { 29, "Avoid highways (if possible)" },
                };
                for (var i = 0; i < 31; i++)
                {
                    string name = "~r~Unknown Flag";
                    if (knownNames.ContainsKey(i))
                    {
                        name = knownNames[i];
                    }
                    MenuCheckboxItem checkbox = new MenuCheckboxItem(name, "Toggle this driving style flag.", false);
                    CustomDrivingStyleMenu.AddMenuItem(checkbox);
                }
                CustomDrivingStyleMenu.OnCheckboxChange += (sender, item, index, _checked) =>
                {
                    int style = GetStyleFromIndex(drivingStyle.ListIndex);
                    CustomDrivingStyleMenu.MenuSubtitle = $"custom style: {style}";
                    if (drivingStyle.ListIndex == 4)
                    {
                        Notify.Custom("Driving style updated.");
                        SetDriveTaskDrivingStyle(Game.PlayerPed.Handle, style);
                    }
                    else
                    {
                        Notify.Custom("Driving style NOT updated because you haven't enabled the Custom driving style in the previous menu.");
                    }
                };

                vehicleAutoPilot.AddMenuItem(startDrivingWaypoint);
                vehicleAutoPilot.AddMenuItem(startDrivingRandomly);
                vehicleAutoPilot.AddMenuItem(stopDriving);
                vehicleAutoPilot.AddMenuItem(forceStopDriving);

                vehicleAutoPilot.RefreshIndex();

                vehicleAutoPilot.OnItemSelect += async(sender, item, index) =>
                {
                    if (Game.PlayerPed.IsInVehicle() && item != stopDriving && item != forceStopDriving)
                    {
                        if (Game.PlayerPed.CurrentVehicle != null && Game.PlayerPed.CurrentVehicle.Exists() && !Game.PlayerPed.CurrentVehicle.IsDead && Game.PlayerPed.CurrentVehicle.IsDriveable)
                        {
                            if (Game.PlayerPed.CurrentVehicle.Driver == Game.PlayerPed)
                            {
                                if (item == startDrivingWaypoint)
                                {
                                    if (IsWaypointActive())
                                    {
                                        int style = GetStyleFromIndex(drivingStyle.ListIndex);
                                        DriveToWp(style);
                                        Notify.Info("Your player ped is now driving the vehicle for you. You can cancel any time by pressing the Stop Driving button. The vehicle will stop when it has reached the destination.");
                                    }
                                    else
                                    {
                                        Notify.Error("You need a waypoint before you can drive to it!");
                                    }
                                }
                                else if (item == startDrivingRandomly)
                                {
                                    int style = GetStyleFromIndex(drivingStyle.ListIndex);
                                    DriveWander(style);
                                    Notify.Info("Your player ped is now driving the vehicle for you. You can cancel any time by pressing the Stop Driving button.");
                                }
                            }
                            else
                            {
                                Notify.Error("You must be the driver of this vehicle!");
                            }
                        }
                        else
                        {
                            Notify.Error("Your vehicle is broken or it does not exist!");
                        }
                    }
                    else if (item != stopDriving && item != forceStopDriving)
                    {
                        Notify.Error("You need to be in a vehicle first!");
                    }
                    if (item == stopDriving)
                    {
                        if (Game.PlayerPed.IsInVehicle())
                        {
                            Vehicle veh = GetVehicle();
                            if (veh != null && veh.Exists() && !veh.IsDead)
                            {
                                Vector3 outPos = new Vector3();
                                if (GetNthClosestVehicleNode(Game.PlayerPed.Position.X, Game.PlayerPed.Position.Y, Game.PlayerPed.Position.Z, 3, ref outPos, 0, 0, 0))
                                {
                                    Notify.Info("The player ped will find a suitable place to park the car and will then stop driving. Please wait.");
                                    ClearPedTasks(Game.PlayerPed.Handle);
                                    TaskVehiclePark(Game.PlayerPed.Handle, veh.Handle, outPos.X, outPos.Y, outPos.Z, Game.PlayerPed.Heading, 3, 60f, true);
                                    while (Game.PlayerPed.Position.DistanceToSquared2D(outPos) > 3f)
                                    {
                                        await BaseScript.Delay(0);
                                    }
                                    SetVehicleHalt(veh.Handle, 3f, 0, false);
                                    ClearPedTasks(Game.PlayerPed.Handle);
                                    Notify.Info("The player ped has stopped driving.");
                                }
                            }
                        }
                        else
                        {
                            ClearPedTasks(Game.PlayerPed.Handle);
                            Notify.Alert("Your ped is not in any vehicle.");
                        }
                    }
                    else if (item == forceStopDriving)
                    {
                        ClearPedTasks(Game.PlayerPed.Handle);
                        Notify.Info("Driving task cancelled.");
                    }
                };

                vehicleAutoPilot.OnListItemSelect += (sender, item, listIndex, itemIndex) =>
                {
                    if (item == drivingStyle)
                    {
                        int style = GetStyleFromIndex(listIndex);
                        SetDriveTaskDrivingStyle(Game.PlayerPed.Handle, style);
                        Notify.Info($"Driving task style is now set to: ~r~{drivingStyles[listIndex]}~s~.");
                    }
                };
            }

            if (IsAllowed(Permission.POFreeze))
            {
                menu.AddMenuItem(playerFrozenCheckbox);
            }
            if (IsAllowed(Permission.POScenarios))
            {
                menu.AddMenuItem(playerScenarios);
                menu.AddMenuItem(stopScenario);
            }
            #endregion

            #region handle all events
            // Checkbox changes.
            menu.OnCheckboxChange += (sender, item, itemIndex, _checked) =>
            {
                // God Mode toggled.
                if (item == playerGodModeCheckbox)
                {
                    PlayerGodMode = _checked;
                }
                // Invisibility toggled.
                else if (item == invisibleCheckbox)
                {
                    PlayerInvisible = _checked;
                    SetEntityVisible(Game.PlayerPed.Handle, !PlayerInvisible, false);
                }
                // Unlimited Stamina toggled.
                else if (item == unlimitedStaminaCheckbox)
                {
                    PlayerStamina = _checked;
                    StatSetInt((uint)GetHashKey("MP0_STAMINA"), _checked ? 100 : 0, true);
                }
                // Fast run toggled.
                else if (item == fastRunCheckbox)
                {
                    PlayerFastRun = _checked;
                    SetRunSprintMultiplierForPlayer(Game.Player.Handle, (_checked ? 1.49f : 1f));
                }
                // Fast swim toggled.
                else if (item == fastSwimCheckbox)
                {
                    PlayerFastSwim = _checked;
                    SetSwimMultiplierForPlayer(Game.Player.Handle, (_checked ? 1.49f : 1f));
                }
                // Super jump toggled.
                else if (item == superJumpCheckbox)
                {
                    PlayerSuperJump = _checked;
                }
                // No ragdoll toggled.
                else if (item == noRagdollCheckbox)
                {
                    PlayerNoRagdoll = _checked;
                }
                // Never wanted toggled.
                else if (item == neverWantedCheckbox)
                {
                    PlayerNeverWanted = _checked;
                    if (!_checked)
                    {
                        SetMaxWantedLevel(5);
                    }
                    else
                    {
                        SetMaxWantedLevel(0);
                    }
                }
                // Everyone ignores player toggled.
                else if (item == everyoneIgnoresPlayerCheckbox)
                {
                    PlayerIsIgnored = _checked;

                    // Manage player is ignored by everyone.
                    SetEveryoneIgnorePlayer(Game.Player.Handle, PlayerIsIgnored);
                    SetPoliceIgnorePlayer(Game.Player.Handle, PlayerIsIgnored);
                    SetPlayerCanBeHassledByGangs(Game.Player.Handle, !PlayerIsIgnored);
                }
                else if (item == playerStayInVehicleCheckbox)
                {
                    PlayerStayInVehicle = _checked;
                }
                // Freeze player toggled.
                else if (item == playerFrozenCheckbox)
                {
                    PlayerFrozen = _checked;

                    if (MainMenu.NoClipMenu != null && !MainMenu.NoClipEnabled)
                    {
                        FreezeEntityPosition(Game.PlayerPed.Handle, PlayerFrozen);
                    }
                    else if (!MainMenu.NoClipEnabled)
                    {
                        FreezeEntityPosition(Game.PlayerPed.Handle, PlayerFrozen);
                    }
                }
            };

            // List selections
            menu.OnListItemSelect += (sender, listItem, listIndex, itemIndex) =>
            {
                // Set wanted Level
                if (listItem == setWantedLevel)
                {
                    SetPlayerWantedLevel(Game.Player.Handle, listIndex, false);
                    SetPlayerWantedLevelNow(Game.Player.Handle, false);
                }
                // Player Scenarios
                else if (listItem == playerScenarios)
                {
                    PlayScenario(PedScenarios.ScenarioNames[PedScenarios.Scenarios[listIndex]]);
                }
                else if (listItem == setArmorItem)
                {
                    Game.PlayerPed.Armor = (listItem.ListIndex) * 20;
                }
            };

            // button presses
            menu.OnItemSelect += (sender, item, index) =>
            {
                // Force Stop Scenario button
                if (item == stopScenario)
                {
                    // Play a new scenario named "forcestop" (this scenario doesn't exist, but the "Play" function checks
                    // for the string "forcestop", if that's provided as th scenario name then it will forcefully clear the player task.
                    PlayScenario("forcestop");
                }
                else if (item == healPlayerBtn)
                {
                    Game.PlayerPed.Health = Game.PlayerPed.MaxHealth;
                    Notify.Success("Player healed.");
                }
                else if (item == cleanPlayerBtn)
                {
                    Game.PlayerPed.ClearBloodDamage();
                    Notify.Success("Player clothes have been cleaned.");
                }
                else if (item == dryPlayerBtn)
                {
                    Game.PlayerPed.WetnessHeight = 0f;
                    Notify.Success("Player is now dry.");
                }
                else if (item == wetPlayerBtn)
                {
                    Game.PlayerPed.WetnessHeight = 2f;
                    Notify.Success("Player is now wet.");
                }
                else if (item == suicidePlayerBtn)
                {
                    CommitSuicide();
                }
            };
            #endregion
        }
示例#27
0
        /// <summary>
        /// Creates the menu if it doesn't exist yet and sets the event handlers.
        /// </summary>
        public void CreateMenu()
        {
            menu = new Menu(Game.Player.Name, "weapon loadouts management");

            MenuController.AddSubmenu(menu, SavedLoadoutsMenu);
            MenuController.AddSubmenu(SavedLoadoutsMenu, ManageLoadoutMenu);

            MenuItem saveLoadout          = new MenuItem("Save Loadout", "Save your current weapons into a new loadout slot.");
            MenuItem savedLoadoutsMenuBtn = new MenuItem("Manage Loadouts", "Manage saved weapon loadouts.")
            {
                Label = "→→→"
            };
            MenuCheckboxItem enableDefaultLoadouts = new MenuCheckboxItem("Restore Default Loadout On Respawn", "If you've set a loadout as default loadout, then your loadout will be equipped automatically whenever you (re)spawn.", WeaponLoadoutsSetLoadoutOnRespawn);

            menu.AddMenuItem(saveLoadout);
            menu.AddMenuItem(savedLoadoutsMenuBtn);
            MenuController.BindMenuItem(menu, SavedLoadoutsMenu, savedLoadoutsMenuBtn);
            if (IsAllowed(Permission.WLEquipOnRespawn))
            {
                menu.AddMenuItem(enableDefaultLoadouts);

                menu.OnCheckboxChange += (sender, checkbox, index, _checked) =>
                {
                    WeaponLoadoutsSetLoadoutOnRespawn = _checked;
                };
            }


            void RefreshSavedWeaponsMenu()
            {
                int oldCount = SavedLoadoutsMenu.Size;

                SavedLoadoutsMenu.ClearMenuItems(true);

                RefreshSavedWeaponsList();

                foreach (var sw in SavedWeapons)
                {
                    MenuItem btn = new MenuItem(sw.Key.Replace("vmenu_string_saved_weapon_loadout_", ""), "Click to manage this loadout.")
                    {
                        Label = "→→→"
                    };
                    SavedLoadoutsMenu.AddMenuItem(btn);
                    MenuController.BindMenuItem(SavedLoadoutsMenu, ManageLoadoutMenu, btn);
                }

                if (oldCount > SavedWeapons.Count)
                {
                    SavedLoadoutsMenu.RefreshIndex();
                }
            }

            MenuItem spawnLoadout      = new MenuItem("Equip Loadout", "Spawn this saved weapons loadout. This will remove all your current weapons and replace them with this saved slot.");
            MenuItem renameLoadout     = new MenuItem("Rename Loadout", "Rename this saved loadout.");
            MenuItem cloneLoadout      = new MenuItem("Clone Loadout", "Clones this saved loadout to a new slot.");
            MenuItem setDefaultLoadout = new MenuItem("Set As Default Loadout", "Set this loadout to be your default loadout for whenever you (re)spawn. This will override the 'Restore Weapons' option inside the Misc Settings menu. You can toggle this option in the main Weapon Loadouts menu.");
            MenuItem replaceLoadout    = new MenuItem("~r~Replace Loadout", "~r~This replaces this saved slot with the weapons that you currently have in your inventory. This action can not be undone!");
            MenuItem deleteLoadout     = new MenuItem("~r~Delete Loadout", "~r~This will delete this saved loadout. This action can not be undone!");

            if (IsAllowed(Permission.WLEquip))
            {
                ManageLoadoutMenu.AddMenuItem(spawnLoadout);
            }
            ManageLoadoutMenu.AddMenuItem(renameLoadout);
            ManageLoadoutMenu.AddMenuItem(cloneLoadout);
            ManageLoadoutMenu.AddMenuItem(setDefaultLoadout);
            ManageLoadoutMenu.AddMenuItem(replaceLoadout);
            ManageLoadoutMenu.AddMenuItem(deleteLoadout);

            // Save the weapons loadout.
            menu.OnItemSelect += async(sender, item, index) =>
            {
                if (item == saveLoadout)
                {
                    string name = await GetUserInput("Enter a save name", 30);

                    if (string.IsNullOrEmpty(name))
                    {
                        Notify.Error(CommonErrors.InvalidInput);
                    }
                    else
                    {
                        if (SavedWeapons.ContainsKey("vmenu_string_saved_weapon_loadout_" + name))
                        {
                            Notify.Error(CommonErrors.SaveNameAlreadyExists);
                        }
                        else
                        {
                            if (SaveWeaponLoadout("vmenu_string_saved_weapon_loadout_" + name))
                            {
                                Log("saveweapons called from menu select (save loadout button)");
                                Notify.Success($"Your weapons have been saved as ~g~<C>{name}</C>~s~.");
                            }
                            else
                            {
                                Notify.Error(CommonErrors.UnknownError);
                            }
                        }
                    }
                }
            };

            // manage spawning, renaming, deleting etc.
            ManageLoadoutMenu.OnItemSelect += async(sender, item, index) =>
            {
                if (SavedWeapons.ContainsKey(SelectedSavedLoadoutName))
                {
                    List <ValidWeapon> weapons = SavedWeapons[SelectedSavedLoadoutName];

                    if (item == spawnLoadout) // spawn
                    {
                        await SpawnWeaponLoadoutAsync(SelectedSavedLoadoutName, false, true, false);
                    }
                    else if (item == renameLoadout || item == cloneLoadout) // rename or clone
                    {
                        string newName = await GetUserInput("Enter a save name", SelectedSavedLoadoutName.Replace("vmenu_string_saved_weapon_loadout_", ""), 30);

                        if (string.IsNullOrEmpty(newName))
                        {
                            Notify.Error(CommonErrors.InvalidInput);
                        }
                        else
                        {
                            if (SavedWeapons.ContainsKey("vmenu_string_saved_weapon_loadout_" + newName))
                            {
                                Notify.Error(CommonErrors.SaveNameAlreadyExists);
                            }
                            else
                            {
                                SetResourceKvp("vmenu_string_saved_weapon_loadout_" + newName, JsonConvert.SerializeObject(weapons));
                                Notify.Success($"Your weapons loadout has been {(item == renameLoadout ? "renamed" : "cloned")} to ~g~<C>{newName}</C>~s~.");

                                if (item == renameLoadout)
                                {
                                    DeleteResourceKvp(SelectedSavedLoadoutName);
                                }

                                ManageLoadoutMenu.GoBack();
                            }
                        }
                    }
                    else if (item == setDefaultLoadout) // set as default
                    {
                        SetResourceKvp("vmenu_string_default_loadout", SelectedSavedLoadoutName);
                        Notify.Success("This is now your default loadout.");
                        item.LeftIcon = MenuItem.Icon.TICK;
                    }
                    else if (item == replaceLoadout) // replace
                    {
                        if (replaceLoadout.Label == "Are you sure?")
                        {
                            replaceLoadout.Label = "";
                            SaveWeaponLoadout(SelectedSavedLoadoutName);
                            Log("save weapons called from replace loadout");
                            Notify.Success("Your saved loadout has been replaced with your current weapons.");
                        }
                        else
                        {
                            replaceLoadout.Label = "Are you sure?";
                        }
                    }
                    else if (item == deleteLoadout) // delete
                    {
                        if (deleteLoadout.Label == "Are you sure?")
                        {
                            deleteLoadout.Label = "";
                            DeleteResourceKvp(SelectedSavedLoadoutName);
                            ManageLoadoutMenu.GoBack();
                            Notify.Success("Your saved loadout has been deleted.");
                        }
                        else
                        {
                            deleteLoadout.Label = "Are you sure?";
                        }
                    }
                }
            };

            // Reset the 'are you sure' states.
            ManageLoadoutMenu.OnMenuClose += (sender) =>
            {
                deleteLoadout.Label = "";
                renameLoadout.Label = "";
            };
            // Reset the 'are you sure' states.
            ManageLoadoutMenu.OnIndexChange += (sender, oldItem, newItem, oldIndex, newIndex) =>
            {
                deleteLoadout.Label = "";
                renameLoadout.Label = "";
            };

            // Refresh the spawned weapons menu whenever this menu is opened.
            SavedLoadoutsMenu.OnMenuOpen += (sender) =>
            {
                RefreshSavedWeaponsMenu();
            };

            // Set the current saved loadout whenever a loadout is selected.
            SavedLoadoutsMenu.OnItemSelect += (sender, item, index) =>
            {
                if (SavedWeapons.ContainsKey("vmenu_string_saved_weapon_loadout_" + item.Text))
                {
                    SelectedSavedLoadoutName = "vmenu_string_saved_weapon_loadout_" + item.Text;
                }
                else // shouldn't ever happen, but just in case
                {
                    ManageLoadoutMenu.GoBack();
                }
            };

            // Reset the index whenever the ManageLoadout menu is opened. Just to prevent auto selecting the delete option for example.
            ManageLoadoutMenu.OnMenuOpen += (sender) =>
            {
                ManageLoadoutMenu.RefreshIndex();
                string kvp = GetResourceKvpString("vmenu_string_default_loadout");
                if (string.IsNullOrEmpty(kvp) || kvp != SelectedSavedLoadoutName)
                {
                    setDefaultLoadout.LeftIcon = MenuItem.Icon.NONE;
                }
                else
                {
                    setDefaultLoadout.LeftIcon = MenuItem.Icon.TICK;
                }
            };

            // Refresh the saved weapons menu.
            RefreshSavedWeaponsMenu();
        }
示例#28
0
        /// <summary>
        /// Updates the player items.
        /// </summary>
        public void UpdatePlayerlist()
        {
            // Remove leftover menu items if they exist.
            if (menu.MenuItems.Count > 0)
            {
                menu.MenuItems.Clear();
            }

            // Create a new player list.
            PlayerList pl = new PlayerList();

            // Loop through the playerlist.
            foreach (Player p in pl)
            {
                // Create a button for this player and add it to the menu.
                UIMenuItem playerItem = new UIMenuItem(p.Name, "[" + (p.Handle < 10 ? "0" : "") + p.Handle + "] " + p.Name + " (Server ID: " + p.ServerId + ")");
                playerItem.SetRightLabel("→→→");
                menu.AddItem(playerItem);

                // Handle button presses.
                menu.OnItemSelect += (sender, item, index) =>
                {
                    // If the player item is pressed.
                    if (item == playerItem)
                    {
                        // Create the player object.
                        Player player = new Player(int.Parse(item.Description.Substring(1, 2).ToString()));

                        // Create the menu for the player & set the width offset.
                        UIMenu PlayerMenu = new UIMenu(player.Name, "[" + (player.Handle < 10 ? "0" : "") + player.Handle + "] " + player.Name +
                                                       " (Server ID: " + player.ServerId + ")", true)
                        {
                            ScaleWithSafezone       = false,
                            MouseControlsEnabled    = false,
                            MouseEdgeEnabled        = false,
                            ControlDisablingEnabled = false
                        };
                        PlayerMenu.SetMenuWidthOffset(50);
                        PlayerMenu.RefreshIndex();
                        PlayerMenu.UpdateScaleform();


                        // Create all player options buttons.
                        UIMenuItem teleportBtn      = new UIMenuItem("Teleport To Player", "Teleport to this player.");
                        UIMenuItem teleportInVehBtn = new UIMenuItem("Teleport Into Vehicle", "Teleport into the player's vehicle.");
                        UIMenuItem setWaypointBtn   = new UIMenuItem("Set Waypoint", "Set a waypoint to this player.");
                        UIMenuItem spectateBtn      = new UIMenuItem("Spectate Player", "Spectate this player.");
                        UIMenuItem summonBtn        = new UIMenuItem("Summon Player", "Bring this player to your location.");
                        summonBtn.SetRightBadge(UIMenuItem.BadgeStyle.Alert);
                        UIMenuItem killBtn = new UIMenuItem("Kill Player", "Kill the selected player! Why are you so cruel :(");
                        killBtn.SetRightBadge(UIMenuItem.BadgeStyle.Alert);
                        UIMenuItem kickPlayerBtn = new UIMenuItem("~r~Kick Player", "~r~Kick~s~ this player from the server, you need to specify a reason " +
                                                                  "otherwise the kick will be cancelled.");
                        kickPlayerBtn.SetRightBadge(UIMenuItem.BadgeStyle.Alert);
                        UIMenuItem permBanBtn = new UIMenuItem("~r~Ban Player", "Ban the player from the server forever.");
                        permBanBtn.SetRightBadge(UIMenuItem.BadgeStyle.Alert);
                        UIMenuItem tempBanBtn = new UIMenuItem("~r~Tempban Player", "Ban the player from the server for the specified amount of hours. " +
                                                               "The player will be able to rejoin after the ban expires.");
                        tempBanBtn.SetRightBadge(UIMenuItem.BadgeStyle.Alert);

                        // Add all buttons to the player options submenu. Keeping permissions in mind.
                        if (cf.IsAllowed(Permission.OPTeleport))
                        {
                            PlayerMenu.AddItem(teleportBtn);
                            PlayerMenu.AddItem(teleportInVehBtn);
                        }
                        if (cf.IsAllowed(Permission.OPWaypoint))
                        {
                            PlayerMenu.AddItem(setWaypointBtn);
                        }
                        if (cf.IsAllowed(Permission.OPSpectate))
                        {
                            PlayerMenu.AddItem(spectateBtn);
                        }
                        if (cf.IsAllowed(Permission.OPSummon))
                        {
                            PlayerMenu.AddItem(summonBtn);
                        }
                        if (cf.IsAllowed(Permission.OPKill))
                        {
                            PlayerMenu.AddItem(killBtn);
                        }
                        if (cf.IsAllowed(Permission.OPKick))
                        {
                            PlayerMenu.AddItem(kickPlayerBtn);
                        }
                        if (cf.IsAllowed(Permission.OPTempBan))
                        {
                            PlayerMenu.AddItem(tempBanBtn);
                        }
                        if (cf.IsAllowed(Permission.OPPermBan))
                        {
                            PlayerMenu.AddItem(permBanBtn);
                        }


                        // Add the player menu to the menu pool.
                        MainMenu.Mp.Add(PlayerMenu);

                        // Set the menu invisible.
                        menu.Visible = false;
                        // Set the player menu visible.
                        PlayerMenu.Visible = true;


                        // If a button is pressed in the player's options menu.
                        PlayerMenu.OnItemSelect += (sender2, item2, index2) =>
                        {
                            // Teleport button is pressed.
                            if (item2 == teleportBtn)
                            {
                                cf.TeleportToPlayerAsync(player.Handle, false);
                            }
                            // Teleport in vehicle button is pressed.
                            else if (item2 == teleportInVehBtn)
                            {
                                cf.TeleportToPlayerAsync(player.Handle, true);
                            }
                            // Set waypoint button is pressed.
                            else if (item2 == setWaypointBtn)
                            {
                                World.WaypointPosition = GetEntityCoords(GetPlayerPed(player.Handle), true);
                                //Subtitle.Info($"A new waypoint has been set to ~y~{player.Name}~z~.", prefix: "Info:");
                            }
                            // Spectate player button is pressed.
                            else if (item2 == spectateBtn)
                            {
                                if (player.Handle == PlayerId())
                                {
                                    //Subtitle.Error("You can ~h~not~h~ spectate yourself!", prefix: "Error:");
                                    Notify.Error("Sorry, you can ~r~~h~not~h~ ~s~spectate yourself!");
                                }
                                else
                                {
                                    cf.SpectateAsync(player.Handle);
                                }
                            }
                            // Summon player button is pressed.
                            else if (item2 == summonBtn)
                            {
                                if (player.Handle == PlayerId())
                                {
                                    Notify.Error("Sorry, you can ~r~~h~not~h~ ~s~summon yourself!");
                                }
                                else
                                {
                                    cf.SummonPlayer(player);
                                }
                            }
                            // Kill player button is pressed.
                            else if (item2 == killBtn)
                            {
                                //Subtitle.Info($"~y~{player.Name} ~z~has been killed.", prefix: "Info:");
                                Notify.Success($"Player ~y~<C>{player.Name}</C> ~s~has been killed.");
                                cf.KillPlayer(player);
                            }
                            // Kick player button is pressed.
                            else if (item2 == kickPlayerBtn)
                            {
                                // Close the menu.
                                PlayerMenu.GoBack();

                                // Kick the player.
                                cf.KickPlayer(player, true);

                                // Update the player list.
                                UpdatePlayerlist();

                                // Refresh the index & update scaleform.
                                menu.RefreshIndex();
                                menu.UpdateScaleform();
                            }
                            else if (item2 == tempBanBtn)
                            {
                                cf.BanPlayer(player: player, forever: false);
                            }
                            else if (item2 == permBanBtn)
                            {
                                cf.BanPlayer(player: player, forever: true);
                            }
                        };

                        // Reopen the playerlist menu when a player specific menu is closed.
                        PlayerMenu.OnMenuClose += (sender2) =>
                        {
                            menu.Visible = true;
                        };
                    }
                };
            }
            ;
        }
示例#29
0
        /// <summary>
        /// Main OnTick task runs every game tick and handles all the menu stuff.
        /// </summary>
        /// <returns></returns>
        private async Task OnTick()
        {
            #region FirstTick
            // Only run this the first tick.
            if (firstTick)
            {
                firstTick = false;
                // Clear all previous pause menu info/brief messages on resource start.
                ClearBrief();

                // Request the permissions data from the server.
                TriggerServerEvent("vMenu:RequestPermissions");

                // Wait until the data is received and the player's name is loaded correctly.
                while (!ConfigOptionsSetupComplete || !PermissionsSetupComplete || Game.Player.Name == "**Invalid**" || Game.Player.Name == "** Invalid **")
                {
                    await Delay(0);
                }
                if ((IsAllowed(Permission.Staff) && GetSettingsBool(Setting.vmenu_menu_staff_only)) || GetSettingsBool(Setting.vmenu_menu_staff_only) == false)
                {
                    if (GetSettingsInt(Setting.vmenu_menu_toggle_key) != -1)
                    {
                        MenuToggleKey = (Control)GetSettingsInt(Setting.vmenu_menu_toggle_key);
                        //MenuToggleKey = GetSettingsInt(Setting.vmenu_menu_toggle_key);
                    }
                    if (GetSettingsInt(Setting.vmenu_noclip_toggle_key) != -1)
                    {
                        NoClipKey = GetSettingsInt(Setting.vmenu_noclip_toggle_key);
                    }
                    // Create the main menu.
                    Menu = new Menu(Game.Player.Name, "Main Menu");

                    // Add the main menu to the menu pool.
                    MenuController.AddMenu(Menu);
                    MenuController.MainMenu = Menu;

                    // Create all (sub)menus.
                    CreateSubmenus();
                }
                else
                {
                    MenuController.MainMenu           = null;
                    MenuController.DisableMenuButtons = true;
                    MenuController.DontOpenAnyMenu    = true;
                    MenuController.MenuToggleKey      = (Control)(-1); // disables the menu toggle key
                }

                // Manage Stamina
                if (PlayerOptionsMenu != null && PlayerOptionsMenu.PlayerStamina && IsAllowed(Permission.POUnlimitedStamina))
                {
                    StatSetInt((uint)GetHashKey("MP0_STAMINA"), 100, true);
                    StatSetInt((uint)GetHashKey("MP1_STAMINA"), 100, true);
                }
                else
                {
                    StatSetInt((uint)GetHashKey("MP0_STAMINA"), 0, true);
                    StatSetInt((uint)GetHashKey("MP1_STAMINA"), 0, true);
                }
                // Manage other stats.
                StatSetInt((uint)GetHashKey("MP0_STRENGTH"), 100, true);
                StatSetInt((uint)GetHashKey("MP0_LUNG_CAPACITY"), 80, true); // reduced because it was over powered
                StatSetInt((uint)GetHashKey("MP0_WHEELIE_ABILITY"), 100, true);
                StatSetInt((uint)GetHashKey("MP0_FLYING_ABILITY"), 100, true);
                StatSetInt((uint)GetHashKey("MP0_SHOOTING_ABILITY"), 50, true); // reduced because it was over powered
                StatSetInt((uint)GetHashKey("MP0_STEALTH_ABILITY"), 100, true);
                StatSetInt((uint)GetHashKey("MP1_STRENGTH"), 100, true);
                StatSetInt((uint)GetHashKey("MP1_LUNG_CAPACITY"), 80, true); // reduced because it was over powered
                StatSetInt((uint)GetHashKey("MP1_WHEELIE_ABILITY"), 100, true);
                StatSetInt((uint)GetHashKey("MP1_FLYING_ABILITY"), 100, true);
                StatSetInt((uint)GetHashKey("MP1_SHOOTING_ABILITY"), 50, true); // reduced because it was over powered
                StatSetInt((uint)GetHashKey("MP1_STEALTH_ABILITY"), 100, true);
            }
            #endregion


            // If the setup (permissions) is done, and it's not the first tick, then do this:
            if (ConfigOptionsSetupComplete && !firstTick)
            {
                #region Handle Opening/Closing of the menu.


                var tmpMenu = GetOpenMenu();
                if (MpPedCustomizationMenu != null)
                {
                    bool IsOpen()
                    {
                        return
                            (MpPedCustomizationMenu.appearanceMenu.Visible ||
                             MpPedCustomizationMenu.faceShapeMenu.Visible ||
                             MpPedCustomizationMenu.createCharacterMenu.Visible ||
                             MpPedCustomizationMenu.inheritanceMenu.Visible ||
                             MpPedCustomizationMenu.propsMenu.Visible ||
                             MpPedCustomizationMenu.clothesMenu.Visible ||
                             MpPedCustomizationMenu.tattoosMenu.Visible);
                    }

                    if (IsOpen())
                    {
                        if (tmpMenu == MpPedCustomizationMenu.createCharacterMenu)
                        {
                            MpPedCustomization.DisableBackButton = true;
                        }
                        else
                        {
                            MpPedCustomization.DisableBackButton = false;
                        }
                        MpPedCustomization.DontCloseMenus = true;
                    }
                    else
                    {
                        MpPedCustomization.DisableBackButton = false;
                        MpPedCustomization.DontCloseMenus    = false;
                    }
                }

                if (Game.IsDisabledControlJustReleased(0, Control.PhoneCancel) && MpPedCustomization.DisableBackButton)
                {
                    await Delay(0);

                    Notify.Alert("You must save your ped first before exiting, or click the ~r~Exit Without Saving~s~ button.");
                }

                if (Game.CurrentInputMode == InputMode.MouseAndKeyboard)
                {
                    if (!MenuController.IsAnyMenuOpen() || NoClipEnabled)
                    {
                        if (Game.IsControlJustPressed(0, (Control)NoClipKey) && IsAllowed(Permission.NoClip))
                        {
                            if (MenuController.IsAnyMenuOpen())
                            {
                                if (MenuController.GetCurrentMenu() != null && MenuController.GetCurrentMenu() != NoClipMenu)
                                {
                                    MenuController.CloseAllMenus();
                                }
                            }
                            if (Game.PlayerPed.IsInVehicle())
                            {
                                Vehicle veh = GetVehicle();
                                if (veh != null && veh.Exists() && veh.Driver == Game.PlayerPed)
                                {
                                    NoClipEnabled = !NoClipEnabled;
                                    MenuController.DontOpenAnyMenu = NoClipEnabled;
                                }
                                else
                                {
                                    NoClipEnabled = false;
                                    MenuController.DontOpenAnyMenu = NoClipEnabled;
                                    Notify.Error("This vehicle does not exist (somehow) or you need to be the driver of this vehicle to enable noclip!");
                                }
                            }
                            else
                            {
                                NoClipEnabled = !NoClipEnabled;
                                MenuController.DontOpenAnyMenu = NoClipEnabled;
                            }
                        }
                    }
                }

                if (NoClipEnabled)
                {
                    MenuController.DontOpenAnyMenu = true;
                }

                #endregion

                // Menu toggle button.
                Game.DisableControlThisFrame(0, MenuToggleKey);
            }
        }
示例#30
0
        /// <summary>
        /// Creates the menu.
        /// </summary>
        private void CreateMenu()
        {
            menu = new Menu(Game.Player.Name, LM.Get("Banned Players Management"));

            menu.InstructionalButtons.Add(Control.Jump, LM.Get("Filter Options"));
            menu.ButtonPressHandlers.Add(new Menu.ButtonPressHandler(Control.Jump, Menu.ControlPressCheckType.JUST_RELEASED, new Action <Menu, Control>(async(a, b) =>
            {
                if (banlist.Count > 1)
                {
                    string filterText = await GetUserInput(LM.Get("Filter List By Username (leave this empty to reset the filter!)"));
                    if (string.IsNullOrEmpty(filterText))
                    {
                        Subtitle.Custom(LM.Get("Filters have been cleared."));
                        menu.ResetFilter();
                        UpdateBans();
                    }
                    else
                    {
                        menu.FilterMenuItems(item => item.ItemData is BanRecord br && br.playerName.ToLower().Contains(filterText.ToLower()));
                        Subtitle.Custom(LM.Get("Username filter has been applied."));
                    }
                }
                else
                {
                    Notify.Error(LM.Get("At least 2 players need to be banned in order to use the filter function."));
                }

                Log($"Button pressed: {a} {b}");
            }), true));

            bannedPlayer.AddMenuItem(new MenuItem(LM.Get("Player Name")));
            bannedPlayer.AddMenuItem(new MenuItem(LM.Get("Banned By")));
            bannedPlayer.AddMenuItem(new MenuItem(LM.Get("Banned Until")));
            bannedPlayer.AddMenuItem(new MenuItem(LM.Get("Player Identifiers")));
            bannedPlayer.AddMenuItem(new MenuItem(LM.Get("Banned For")));
            bannedPlayer.AddMenuItem(new MenuItem(LM.Get("~r~Unban"), LM.Get("~r~Warning, unbanning the player can NOT be undone. You will NOT be able to ban them again until they re-join the server. Are you absolutely sure you want to unban this player? ~s~Tip: Tempbanned players will automatically get unbanned if they log on to the server after their ban date has expired.")));

            // should be enough for now to cover all possible identifiers.
            List <string> colors = new List <string>()
            {
                "~r~", "~g~", "~b~", "~o~", "~y~", "~p~", "~s~", "~t~",
            };

            bannedPlayer.OnMenuClose += (sender) =>
            {
                BaseScript.TriggerServerEvent("vMenu:RequestBanList", Game.Player.Handle);
                bannedPlayer.GetMenuItems()[5].Label = "";
                UpdateBans();
            };

            bannedPlayer.OnIndexChange += (sender, oldItem, newItem, oldIndex, newIndex) =>
            {
                bannedPlayer.GetMenuItems()[5].Label = "";
            };

            bannedPlayer.OnItemSelect += (sender, item, index) =>
            {
                if (index == 5 && IsAllowed(Permission.OPUnban))
                {
                    if (item.Label == LM.Get("Are you sure?"))
                    {
                        if (banlist.Contains(currentRecord))
                        {
                            UnbanPlayer(banlist.IndexOf(currentRecord));
                            bannedPlayer.GetMenuItems()[5].Label = "";
                            bannedPlayer.GoBack();
                        }
                        else
                        {
                            Notify.Error(LM.Get("Somehow you managed to click the unban button but this ban record you're apparently viewing does not even exist. Weird..."));
                        }
                    }
                    else
                    {
                        item.Label = LM.Get("Are you sure?");
                    }
                }
                else
                {
                    bannedPlayer.GetMenuItems()[5].Label = "";
                }
            };

            menu.OnItemSelect += (sender, item, index) =>
            {
                //if (index < banlist.Count)
                //{
                currentRecord = item.ItemData;

                bannedPlayer.MenuSubtitle = LM.Get("Ban Record: ~y~") + currentRecord.playerName;
                var nameItem              = bannedPlayer.GetMenuItems()[0];
                var bannedByItem          = bannedPlayer.GetMenuItems()[1];
                var bannedUntilItem       = bannedPlayer.GetMenuItems()[2];
                var playerIdentifiersItem = bannedPlayer.GetMenuItems()[3];
                var banReasonItem         = bannedPlayer.GetMenuItems()[4];
                nameItem.Label           = currentRecord.playerName;
                nameItem.Description     = LM.Get("Player name: ~y~") + currentRecord.playerName;
                bannedByItem.Label       = currentRecord.bannedBy;
                bannedByItem.Description = LM.Get("Player banned by: ~y~") + currentRecord.bannedBy;
                if (currentRecord.bannedUntil.Date.Year == 3000)
                {
                    bannedUntilItem.Label = LM.Get("Forever");
                }
                else
                {
                    bannedUntilItem.Label = currentRecord.bannedUntil.Date.ToString();
                }
                bannedUntilItem.Description       = LM.Get("This player is banned until: ") + currentRecord.bannedUntil.Date.ToString();
                playerIdentifiersItem.Description = "";

                int i = 0;
                foreach (string id in currentRecord.identifiers)
                {
                    // only (admins) people that can unban players are allowed to view IP's.
                    // this is just a slight 'safety' feature in case someone who doesn't know what they're doing
                    // gave builtin.everyone access to view the banlist.
                    if (id.StartsWith("ip:") && !IsAllowed(Permission.OPUnban))
                    {
                        playerIdentifiersItem.Description += $"{colors[i]}ip: (hidden) ";
                    }
                    else
                    {
                        playerIdentifiersItem.Description += $"{colors[i]}{id.Replace(":", ": ")} ";
                    }
                    i++;
                }
                banReasonItem.Description = LM.Get("Banned for: ") + currentRecord.banReason;

                var unbanPlayerBtn = bannedPlayer.GetMenuItems()[5];
                unbanPlayerBtn.Label = "";
                if (!IsAllowed(Permission.OPUnban))
                {
                    unbanPlayerBtn.Enabled     = false;
                    unbanPlayerBtn.Description = LM.Get("You are not allowed to unban players. You are only allowed to view their ban record.");
                    unbanPlayerBtn.LeftIcon    = MenuItem.Icon.LOCK;
                }

                bannedPlayer.RefreshIndex();
                //}
            };
            MenuController.AddMenu(bannedPlayer);
        }