Пример #1
0
        private static void SetupMenu()
        {
            if (setupDone)
            {
                return;
            }
            setupDone = true;

            MenuCheckboxItem minimapKeybind = new MenuCheckboxItem("Minimap Controls", "Holding down the Select Radar Option button will allow you to toggle the minimap on/off when this option is enabled.", UserDefaults.MiscMinimapControls);
            MenuCheckboxItem showCores      = new MenuCheckboxItem("Always Show Cores", "The cores above your radar will always be displayed when this option is enabled. The game will automatically show or hide the cores if this is disabled.", UserDefaults.MiscAlwaysShowCores);

            menu.AddMenuItem(minimapKeybind);
            menu.AddMenuItem(showCores);

            menu.OnCheckboxChange += (m, item, index, _checked) =>
            {
                if (item == minimapKeybind)
                {
                    UserDefaults.MiscMinimapControls = _checked;
                }
                else if (item == showCores)
                {
                    UserDefaults.MiscAlwaysShowCores = _checked;
                    Function.Call((Hash)0xD4EE21B7CC7FD350, UserDefaults.MiscAlwaysShowCores); // _ALWAYS_SHOW_HORSE_CORES
                    Function.Call((Hash)0x50C803A4CD5932C5, UserDefaults.MiscAlwaysShowCores); // _ALWAYS_SHOW_PLAYER_CORES
                }
            };
        }
Пример #2
0
 private void checkboxChanged(Menu menu1, MenuCheckboxItem menuItem, int itemIndex, bool newCheckedState)
 {
     if (menuItem == beschikbaar)
     {
         beschikbaarBool = !beschikbaarBool;
         TriggerServerEvent("SV:UpdateBeschikbaar");
     }
 }
Пример #3
0
        public async void OnCheckboxChange(Menu menu, MenuCheckboxItem item, int index, bool state)
        {
            switch (item.Text)
            {
            case "Cambia Sesso":
                await ChangeGender(state);

                break;
            }
        }
Пример #4
0
        public void CreateMenuItems()
        {
            GenderCheckbox = new MenuCheckboxItem("Cambia Sesso", "È un maschio o una femmina?")
            {
                Style = MenuCheckboxItem.CheckboxStyle.Cross, Checked = true
            };
            ExitButton = new MenuItem("Completa La Creazione", "Descrizione");
            NameButton = new MenuItem("Nome Completo", "Descrizione");

            Menu.AddMenuItem(GenderCheckbox);
            Menu.AddMenuItem(ExitButton);
            Menu.AddMenuItem(NameButton);
        }
Пример #5
0
        public void Display(MissionData data)
        {
            Clear();
            foreach (var pair in StaticData.IPLData.Database)
            {
                var item = new MenuCheckboxItem(pair.Key, data.Interiors.Contains(pair.Key), pair.Value.Item1 ? "This interior requires the online map to load." : "");
                AddItem(item);

                item.CheckboxEvent += (sender, @checked) =>
                {
                    if (@checked)
                    {
                        if (!data.Interiors.Contains(pair.Key))
                        {
                            data.Interiors.Add(pair.Key);
                        }

                        if (pair.Value.Item1)
                        {
                            Util.LoadOnlineMap();
                        }

                        foreach (string s in pair.Value.Item2)
                        {
                            Util.LoadInterior(s);
                        }

                        foreach (var s in pair.Value.Item3)
                        {
                            Util.RemoveInterior(s);
                        }
                    }
                    else
                    {
                        data.Interiors.Remove(pair.Key);

                        foreach (string s in pair.Value.Item3)
                        {
                            Util.LoadInterior(s);
                        }

                        foreach (var s in pair.Value.Item2)
                        {
                            Util.RemoveInterior(s);
                        }
                    }
                };
            }
            RefreshIndex();
        }
        public void BuildFor(SerializableData.SerializablePickup actor)
        {
            Clear();

            #region SpawnAfter
            {
                var item = new MenuListItem("Spawn Before Objective", StaticData.StaticLists.NumberMenu, actor.SpawnAfter);

                item.OnListChanged += (sender, index) =>
                {
                    actor.SpawnAfter = index;
                };

                AddItem(item);
            }
            #endregion

            #region Weapons
            {
                var listIndex = actor.Ammo == 0
                    ? StaticData.StaticLists.AmmoChoses.FindIndex(n => n == (dynamic)9999)
                    : StaticData.StaticLists.AmmoChoses.FindIndex(n => n == (dynamic)actor.Ammo);
                var item = new MenuListItem("Ammo Count", StaticData.StaticLists.AmmoChoses, listIndex);

                item.OnListChanged += (sender, index) =>
                {
                    int newAmmo = int.Parse(((MenuListItem)sender).IndexToItem(index).ToString(), CultureInfo.InvariantCulture);
                    actor.Ammo = newAmmo;
                };

                AddItem(item);
            }
            #endregion

            #region Respawn
            {
                var item = new MenuCheckboxItem("Respawn", actor.Respawn);
                item.CheckboxEvent += (sender, @checked) =>
                {
                    actor.Respawn = @checked;
                };
                AddItem(item);
            }
            #endregion

            RefreshIndex();
        }
Пример #7
0
        /// <summary>
        /// Creates the menu.
        /// </summary>
        private void CreateMenu()
        {
            menu = new Menu("Time & Weather Options", "Time & Weather Options");

            clientSidedEnabled = new MenuCheckboxItem("Client-Sided Time & Weather", "Enable or disable client-sided time and weather changes.", false);
            menu.AddMenuItem(clientSidedEnabled);

            timeFrozen = new MenuCheckboxItem("Freeze Time", "Enable or disable time freezing.", false);
            menu.AddMenuItem(timeFrozen);

            List <string> timeData = new List <string>();

            for (var i = 0; i < 24; i++)
            {
                timeData.Add(i.ToString() + ".00");
            }
            timeDataList = new MenuListItem("Change Time", timeData, 12, "Select time of day.");
            menu.AddMenuItem(timeDataList);

            weatherList = new MenuListItem("Change Weather", weatherListData, 0, "Select weather.");
            menu.AddMenuItem(weatherList);
        }
Пример #8
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();
                }
            };
        }
Пример #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
        private void CreateMenu()
        {
            // Create the menu.
            menu = new Menu(Game.Player.Name, "天氣選項");

            dynamicWeatherEnabled = new MenuCheckboxItem("開關動態天氣", "啟用或禁用動態天氣變化.", EventManager.dynamicWeather);
            blackout = new MenuCheckboxItem("開關燈光", "這會禁用或啟用地圖上的所有燈光.", EventManager.blackoutMode);
            MenuItem extrasunny      = new MenuItem("大太陽", "將天氣設置為 ~y~更加陽光明媚~s~!");
            MenuItem clear           = new MenuItem("明確", "將天氣設置為 ~y~明確~s~!");
            MenuItem neutral         = new MenuItem("普通天氣", "將天氣設置為 ~y~普通天氣~s~!");
            MenuItem smog            = new MenuItem("煙霧", "將天氣設置為 ~y~煙霧~s~!");
            MenuItem foggy           = new MenuItem("霧霾", "將天氣設置為 ~y~霧霾~s~!");
            MenuItem clouds          = new MenuItem("多雲的", "將天氣設置為  ~y~多雲的~s~!");
            MenuItem overcast        = new MenuItem("灰濛蒙", "將天氣設置為  ~y~灰濛蒙~s~!");
            MenuItem clearing        = new MenuItem("樹林中中氣息", "將天氣設置為 ~y~樹林中中氣息~s~!");
            MenuItem rain            = new MenuItem("多雨", "將天氣設置為~y~多雨~s~!");
            MenuItem thunder         = new MenuItem("雷電雨", "將天氣設置為 ~y~雷電雨~s~!");
            MenuItem blizzard        = new MenuItem("暴風雪", "將天氣設置為 ~y~暴風雪~s~!");
            MenuItem snow            = new MenuItem("雪", "將天氣設置為 ~y~雪~s~!");
            MenuItem snowlight       = new MenuItem("小雪", "將天氣設置為 ~y~小雪~s~!");
            MenuItem xmas            = new MenuItem("聖誕節的雪", "將天氣設置為 ~y~聖誕節的雪~s~!");
            MenuItem halloween       = new MenuItem("萬聖節", "將天氣設置為 ~y~萬聖節~s~!");
            MenuItem removeclouds    = new MenuItem("移除所有的雲", "移除天空中的所有的雲!");
            MenuItem randomizeclouds = new MenuItem("隨機產生雲", "向天空隨機新增雲!");

            var indexOffset = 2;

            if (IsAllowed(Permission.WODynamic))
            {
                menu.AddMenuItem(dynamicWeatherEnabled);
                indexOffset--;
            }
            if (IsAllowed(Permission.WOBlackout))
            {
                menu.AddMenuItem(blackout);
                indexOffset--;
            }
            if (IsAllowed(Permission.WOSetWeather))
            {
                weatherHashMenuIndex.Add((uint)GetHashKey("EXTRASUNNY"), extrasunny);
                weatherHashMenuIndex.Add((uint)GetHashKey("CLEAR"), clear);
                weatherHashMenuIndex.Add((uint)GetHashKey("NEUTRAL"), neutral);
                weatherHashMenuIndex.Add((uint)GetHashKey("SMOG"), smog);
                weatherHashMenuIndex.Add((uint)GetHashKey("FOGGY"), foggy);
                weatherHashMenuIndex.Add((uint)GetHashKey("CLOUDS"), clouds);
                weatherHashMenuIndex.Add((uint)GetHashKey("OVERCAST"), overcast);
                weatherHashMenuIndex.Add((uint)GetHashKey("CLEARING"), clearing);
                weatherHashMenuIndex.Add((uint)GetHashKey("RAIN"), rain);
                weatherHashMenuIndex.Add((uint)GetHashKey("THUNDER"), thunder);
                weatherHashMenuIndex.Add((uint)GetHashKey("BLIZZARD"), blizzard);
                weatherHashMenuIndex.Add((uint)GetHashKey("SNOW"), snow);
                weatherHashMenuIndex.Add((uint)GetHashKey("SNOWLIGHT"), snowlight);
                weatherHashMenuIndex.Add((uint)GetHashKey("XMAS"), xmas);
                weatherHashMenuIndex.Add((uint)GetHashKey("HALLOWEEN"), halloween);

                menu.AddMenuItem(extrasunny);
                menu.AddMenuItem(clear);
                menu.AddMenuItem(neutral);
                menu.AddMenuItem(smog);
                menu.AddMenuItem(foggy);
                menu.AddMenuItem(clouds);
                menu.AddMenuItem(overcast);
                menu.AddMenuItem(clearing);
                menu.AddMenuItem(rain);
                menu.AddMenuItem(thunder);
                menu.AddMenuItem(blizzard);
                menu.AddMenuItem(snow);
                menu.AddMenuItem(snowlight);
                menu.AddMenuItem(xmas);
                menu.AddMenuItem(halloween);
            }
            if (IsAllowed(Permission.WORandomizeClouds))
            {
                menu.AddMenuItem(removeclouds);
            }

            if (IsAllowed(Permission.WORemoveClouds))
            {
                menu.AddMenuItem(randomizeclouds);
            }

            List <string> weatherTypes = new List <string>()
            {
                "EXTRASUNNY",
                "CLEAR",
                "NEUTRAL",
                "SMOG",
                "FOGGY",
                "CLOUDS",
                "OVERCAST",
                "CLEARING",
                "RAIN",
                "THUNDER",
                "BLIZZARD",
                "SNOW",
                "SNOWLIGHT",
                "XMAS",
                "HALLOWEEN"
            };

            menu.OnItemSelect += (sender, item, index2) =>
            {
                var index = index2 + indexOffset;
                // A weather type is selected.
                if (index >= 2 && index <= 16)
                {
                    Notify.Custom($"天氣將再30秒後更改為 ~y~{weatherTypes[index - 2]}~s~");
                    UpdateServerWeather(weatherTypes[index - 2], EventManager.blackoutMode, EventManager.dynamicWeather);
                }
                if (item == removeclouds)
                {
                    ModifyClouds(true);
                }
                else if (item == randomizeclouds)
                {
                    ModifyClouds(false);
                }
            };

            menu.OnCheckboxChange += (sender, item, index, _checked) =>
            {
                if (item == dynamicWeatherEnabled)
                {
                    EventManager.dynamicWeather = _checked;
                    Notify.Custom($"現在天氣動態變化 {(_checked ? "~g~開啟" : "~r~關閉")}~s~.");
                    UpdateServerWeather(EventManager.currentWeatherType, EventManager.blackoutMode, _checked);
                }
                else if (item == blackout)
                {
                    EventManager.blackoutMode = _checked;
                    Notify.Custom($"現在是停電模式 {(_checked ? "~g~開啟" : "~r~關閉")}~s~.");
                    UpdateServerWeather(EventManager.currentWeatherType, _checked, EventManager.dynamicWeather);
                }
            };
        }
Пример #11
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
        }
Пример #12
0
        private void CreateMenu()
        {
            currentChannel = channels[0];
            if (IsAllowed(Permission.VCStaffChannel))
            {
                channels.Add("Staff Channel");
            }

            // Create the menu.
            menu = new Menu(Game.Player.Name, "Voice Chat Settings");

            MenuCheckboxItem voiceChatEnabled   = new MenuCheckboxItem("Enable Voice Chat", "Enable or disable voice chat.", EnableVoicechat);
            MenuCheckboxItem showCurrentSpeaker = new MenuCheckboxItem("Show Current Speaker", "Shows who is currently talking.", ShowCurrentSpeaker);
            MenuCheckboxItem showVoiceStatus    = new MenuCheckboxItem("Show Microphone Status", "Shows whether your microphone is open or muted.", ShowVoiceStatus);

            List <string> proximity = new List <string>()
            {
                "5 m",
                "10 m",
                "15 m",
                "20 m",
                "100 m",
                "300 m",
                "1 km",
                "2 km",
                "Global",
            };
            MenuListItem voiceChatProximity = new MenuListItem("Voice Chat Proximity", proximity, proximityRange.IndexOf(currentProximity), "Set the voice chat receiving proximity in meters.");
            MenuListItem voiceChatChannel   = new MenuListItem("Voice Chat Channel", channels, channels.IndexOf(currentChannel), "Set the voice chat channel.");

            if (IsAllowed(Permission.VCEnable))
            {
                menu.AddMenuItem(voiceChatEnabled);

                // Nested permissions because without voice chat enabled, you wouldn't be able to use these settings anyway.
                if (IsAllowed(Permission.VCShowSpeaker))
                {
                    menu.AddMenuItem(showCurrentSpeaker);
                }

                menu.AddMenuItem(voiceChatProximity);
                menu.AddMenuItem(voiceChatChannel);
                menu.AddMenuItem(showVoiceStatus);
            }

            menu.OnCheckboxChange += (sender, item, index, _checked) =>
            {
                if (item == voiceChatEnabled)
                {
                    EnableVoicechat = _checked;
                }
                else if (item == showCurrentSpeaker)
                {
                    ShowCurrentSpeaker = _checked;
                }
                else if (item == showVoiceStatus)
                {
                    ShowVoiceStatus = _checked;
                }
            };

            menu.OnListIndexChange += (sender, item, oldIndex, newIndex, itemIndex) =>
            {
                if (item == voiceChatProximity)
                {
                    currentProximity = proximityRange[newIndex];
                    Subtitle.Custom($"New voice chat proximity set to: ~b~{proximity[newIndex]}~s~.");
                }
                else if (item == voiceChatChannel)
                {
                    currentChannel = channels[newIndex];
                    Subtitle.Custom($"New voice chat channel set to: ~b~{channels[newIndex]}~s~.");
                }
            };
        }
Пример #13
0
        private void CreateMenu()
        {
            menu = new Menu(_t("DRONE_TITLE"), _t("DRONE_DESC"));

            #region main parameters

            // Drone modes
            List <string> modeListData = new List <string>()
            {
                _t("DRONE_RACE"), _t("DRONE_ZERO_G"), _t("DRONE_SPECTATOR"), _t("DRONE_HOMING")
            };
            modeList = new MenuListItem(_t("DRONE_MODE"), modeListData, 0, _t("DRONE_MODE_DESC"));

            // Invert input
            invertPitch = new MenuCheckboxItem(_t("DRONE_INVERT_PITCH"), _t("DRONE_INVERT_PITCH_DESC"), false);
            invertRoll  = new MenuCheckboxItem(_t("DRONE_INVERT_ROLL"), _t("DRONE_INVERT_ROLL_DESC"), false);

            // Gravity multiplier
            List <string> gravityMultValues = new List <string>();
            for (float i = 0.5f; i <= 4.0f; i += 0.05f)
            {
                gravityMultValues.Add(i.ToString("0.00"));
            }
            gravityMultList = new MenuListItem(_t("DRONE_GRAVITY"), gravityMultValues, 10, _t("DRONE_GRAVITY_DESC"))
            {
                ShowColorPanel = false
            };

            // Timestep multiplier
            List <string> timestepValues = new List <string>();
            for (float i = 0.5f; i <= 4.0f; i += 0.05f)
            {
                timestepValues.Add(i.ToString("0.00"));
            }
            timestepMultList = new MenuListItem(_t("DRONE_TIMESTEP"), timestepValues, 10, _t("DRONE_TIMESTEP_DESC"))
            {
                ShowColorPanel = false
            };

            // Drag multiplier
            List <string> dragMultValues = new List <string>();
            for (float i = 0.0f; i <= 4.0f; i += 0.05f)
            {
                dragMultValues.Add(i.ToString("0.00"));
            }
            dragMultList = new MenuListItem(_t("DRONE_DRAG"), dragMultValues, 20, _t("DRONE_DRAG_DESC"))
            {
                ShowColorPanel = false
            };

            // Acceleration multiplier
            List <string> accelerationMultValues = new List <string>();
            for (float i = 0.5f; i <= 4.0f; i += 0.05f)
            {
                accelerationMultValues.Add(i.ToString("0.00"));
            }
            accelerationMultList = new MenuListItem(_t("DRONE_ACCELE"), accelerationMultValues, 10, _t("DRONE_ACCELE_DESC"))
            {
                ShowColorPanel = false
            };

            // Rotation multipliers
            List <string> rotationMultXValues = new List <string>();
            for (float i = 0.5f; i <= 4.0f; i += 0.05f)
            {
                rotationMultXValues.Add(i.ToString("0.00"));
            }
            rotationMultXList = new MenuListItem(_t("DRONE_PITCH"), rotationMultXValues, 10, _t("DRONE_PITCH_DESC"))
            {
                ShowColorPanel = false
            };
            List <string> rotationMultYValues = new List <string>();
            for (float i = 0.5f; i <= 4.0f; i += 0.05f)
            {
                rotationMultYValues.Add(i.ToString("0.00"));
            }
            rotationMultYList = new MenuListItem(_t("DRONE_ROLL"), rotationMultYValues, 10, _t("DRONE_ROLL_DESC"))
            {
                ShowColorPanel = false
            };
            List <string> rotationMultZValues = new List <string>();
            for (float i = 0.5f; i <= 4.0f; i += 0.05f)
            {
                rotationMultZValues.Add(i.ToString("0.00"));
            }
            rotationMultZList = new MenuListItem(_t("DRONE_YAW"), rotationMultZValues, 10, _t("DRONE_YAW_DESC"))
            {
                ShowColorPanel = false
            };
            // Tilt angle
            List <string> tiltAngleValues = new List <string>();
            for (float i = 0.0f; i <= 80.0f; i += 5f)
            {
                tiltAngleValues.Add(i.ToString("0.0"));
            }
            tiltAngleList = new MenuListItem(_t("DRONE_TILT"), tiltAngleValues, 9, _t("DRONE_TILT_DESC"))
            {
                ShowColorPanel = false
            };
            // FOV
            List <string> fovValues = new List <string>();
            for (float i = 30.0f; i <= 120.0f; i += 5f)
            {
                fovValues.Add(i.ToString("0.0"));
            }
            fovList = new MenuListItem(_t("DRONE_FOV"), fovValues, 10, _t("DRONE_FOV_DESC"))
            {
                ShowColorPanel = false
            };
            // Max velocity
            List <string> maxVelValues = new List <string>();
            for (float i = 10.0f; i <= 50.0f; i += 1f)
            {
                maxVelValues.Add(i.ToString("0.0"));
            }
            maxVelList = new MenuListItem(_t("DRONE_MAX_VELOCITY"), maxVelValues, 20, _t("DRONE_MAX_VELOCITY_DESC"))
            {
                ShowColorPanel = false
            };

            #endregion

            #region adding menu items

            menu.AddMenuItem(modeList);
            menu.AddMenuItem(invertPitch);
            menu.AddMenuItem(invertRoll);
            menu.AddMenuItem(gravityMultList);
            menu.AddMenuItem(timestepMultList);
            menu.AddMenuItem(dragMultList);
            menu.AddMenuItem(accelerationMultList);
            menu.AddMenuItem(maxVelList);
            menu.AddMenuItem(rotationMultXList);
            menu.AddMenuItem(rotationMultYList);
            menu.AddMenuItem(rotationMultZList);
            menu.AddMenuItem(tiltAngleList);
            menu.AddMenuItem(fovList);

            #endregion

            #region managing save/load camera stuff

            // Saving/Loading cameras
            MenuItem savedDronesButton = new MenuItem(_t("DRONE_SAVED"), _t("DRONE_SAVED_DESC"));
            savedDronesMenu = new Menu(_t("DRONE_SAVED_TITLE"));
            MenuController.AddSubmenu(menu, savedDronesMenu);
            menu.AddMenuItem(savedDronesButton);
            savedDronesButton.Label = "→→→";
            MenuController.BindMenuItem(menu, savedDronesMenu, savedDronesButton);

            MenuItem saveDrone = new MenuItem(_t("DRONE_SAVE_CURRENT"), _t("DRONE_SAVE_CURRENT_DESC"));
            savedDronesMenu.AddMenuItem(saveDrone);
            savedDronesMenu.OnMenuOpen += (sender) => {
                savedDronesMenu.ClearMenuItems();
                savedDronesMenu.AddMenuItem(saveDrone);
                LoadDroneCameras();
            };

            savedDronesMenu.OnItemSelect += (sender, item, index) => {
                if (item == saveDrone)
                {
                    SaveCamera();
                    savedDronesMenu.GoBack();
                }
                else
                {
                    UpdateSelectedCameraMenu(item, sender);
                }
            };

            MenuController.AddMenu(selectedDroneMenu);
            MenuItem spawnCamera  = new MenuItem(_t("DRONE_SPAWN"), _t("DRONE_SPAWN_DESC"));
            MenuItem renameCamera = new MenuItem(_t("DRONE_RENAME"), _t("DRONE_RENAME_DESC"));
            MenuItem deleteCamera = new MenuItem(_t("DRONE_DELETE"), _t("DRONE_DELETE_DESC"));
            selectedDroneMenu.AddMenuItem(spawnCamera);
            selectedDroneMenu.AddMenuItem(renameCamera);
            selectedDroneMenu.AddMenuItem(deleteCamera);

            selectedDroneMenu.OnMenuClose += (sender) => {
                selectedDroneMenu.RefreshIndex();
            };

            selectedDroneMenu.OnItemSelect += async(sender, item, index) => {
                if (item == spawnCamera)
                {
                    MainMenu.ResetCameras();
                    SpawnSavedCamera();
                    UpdateParams();
                    selectedDroneMenu.GoBack();
                    savedDronesMenu.RefreshIndex();
                }
                else if (item == deleteCamera)
                {
                    item.Label = "";
                    DeleteResourceKvp(currentlySelectedDrone.Key);
                    selectedDroneMenu.GoBack();
                    savedDronesMenu.RefreshIndex();
                    MainMenu.Notify("~g~~h~Info~h~~s~: Your saved drone has been deleted.");
                }
                else if (item == renameCamera)
                {
                    string newName = await MainMenu.GetUserInput(windowTitle : "Enter a new name for this drone.", defaultText : null, maxInputLength : 30);

                    if (string.IsNullOrEmpty(newName))
                    {
                        MainMenu.Notify("~r~~h~Error~h~~s~: Invalid input");
                    }
                    else
                    {
                        if (SaveCameraInfo("xdm_" + newName, currentlySelectedDrone.Value, false))
                        {
                            DeleteResourceKvp(currentlySelectedDrone.Key);
                            while (!selectedDroneMenu.Visible)
                            {
                                await BaseScript.Delay(0);
                            }
                            MainMenu.Notify("~g~~h~Info~h~~s~: Your drone has successfully been renamed.");
                            selectedDroneMenu.GoBack();
                            currentlySelectedDrone = new KeyValuePair <string, DroneSaveInfo>();
                        }
                        else
                        {
                            MainMenu.Notify("~r~~h~Error~h~~s~: This name is already in use or something unknown failed. Contact the server owner if you believe something is wrong.");
                        }
                    }
                }
            };

            #endregion

            #region handling menu changes

            // Handle checkbox changes
            menu.OnCheckboxChange += (_menu, _item, _index, _checked) => {
                if (_item == invertPitch)
                {
                    invertedPitch = _checked;
                }
                else if (_item == invertRoll)
                {
                    invertedRoll = _checked;
                }
            };

            // Handle sliders
            menu.OnListIndexChange += (_menu, _listItem, _oldIndex, _newIndex, _itemIndex) => {
                if (_listItem == modeList)
                {
                    droneMode = _newIndex;
                    if (droneMode == 3)
                    {
                        homingTarget = GetClosestVehicleToDrone(2000);
                    }
                }

                if (_listItem == gravityMultList)
                {
                    gravityMult = _newIndex * 0.05f + 0.5f;
                }
                if (_listItem == timestepMultList)
                {
                    timestepMult = _newIndex * 0.05f + 0.5f;
                }
                if (_listItem == dragMultList)
                {
                    dragMult = _newIndex * 0.05f;
                }
                if (_listItem == accelerationMultList)
                {
                    accelerationMult = _newIndex * 0.05f + 0.5f;
                }

                if (_listItem == rotationMultXList)
                {
                    rotationMult.X = _newIndex * 0.05f + 0.5f;
                }
                if (_listItem == rotationMultYList)
                {
                    rotationMult.Y = _newIndex * 0.05f + 0.5f;
                }
                if (_listItem == rotationMultZList)
                {
                    rotationMult.Z = _newIndex * 0.05f + 0.5f;
                }

                if (_listItem == maxVelList)
                {
                    maxVel = _newIndex * 1f + 10f;
                }

                if (_listItem == tiltAngleList)
                {
                    tiltAngle = _newIndex * 5.0f;
                }
                if (_listItem == fovList)
                {
                    droneFov = _newIndex * 5.0f + 30f;
                    if (MainMenu.droneCamera != null)
                    {
                        SetCamFov(MainMenu.droneCamera.Handle, droneFov);
                    }
                }
            };

            #endregion
        }
Пример #14
0
        private void CreateMenu()
        {
            #region initial setup.
            // Create the menu.
            menu = new Menu(Game.Player.Name, "Vehicle Spawner");

            // Create the buttons and checkboxes.
            MenuItem         spawnByName = new MenuItem("Spawn Vehicle By Model Name", "Enter the name of a vehicle to spawn.");
            MenuCheckboxItem spawnInVeh  = new MenuCheckboxItem("Spawn Inside Vehicle", "This will teleport you into the vehicle when you spawn it.", SpawnInVehicle);
            MenuCheckboxItem replacePrev = new MenuCheckboxItem("Replace Previous Vehicle", "This will automatically delete your previously spawned vehicle when you spawn a new vehicle.", ReplaceVehicle);

            // Add the items to the menu.
            if (IsAllowed(Permission.VSSpawnByName))
            {
                menu.AddMenuItem(spawnByName);
            }
            menu.AddMenuItem(spawnInVeh);
            menu.AddMenuItem(replacePrev);
            #endregion

            #region addon cars menu
            // Vehicle Addons List
            Menu     addonCarsMenu = new Menu("Addon Vehicles", "Spawn An Addon Vehicle");
            MenuItem addonCarsBtn  = new MenuItem("Addon Vehicles", "A list of addon vehicles available on this server.")
            {
                Label = "→→→"
            };

            menu.AddMenuItem(addonCarsBtn);

            if (IsAllowed(Permission.VSAddon))
            {
                if (AddonVehicles != null)
                {
                    if (AddonVehicles.Count > 0)
                    {
                        MenuController.BindMenuItem(menu, addonCarsMenu, addonCarsBtn);
                        MenuController.AddSubmenu(menu, addonCarsMenu);
                        Menu     unavailableCars    = new Menu("Addon Spawner", "Unavailable Vehicles");
                        MenuItem unavailableCarsBtn = new MenuItem("Unavailable Vehicles", "These addon vehicles are not currently being streamed (correctly) and are not able to be spawned.")
                        {
                            Label = "→→→"
                        };
                        MenuController.AddSubmenu(addonCarsMenu, unavailableCars);

                        for (var cat = 0; cat < 23; cat++)
                        {
                            Menu     categoryMenu = new Menu("Addon Spawner", GetLabelText($"VEH_CLASS_{cat}"));
                            MenuItem categoryBtn  = new MenuItem(GetLabelText($"VEH_CLASS_{cat}"), $"Spawn an addon vehicle from the {GetLabelText($"VEH_CLASS_{cat}")} class.")
                            {
                                Label = "→→→"
                            };

                            addonCarsMenu.AddMenuItem(categoryBtn);

                            if (!allowedCategories[cat])
                            {
                                categoryBtn.Description = "This vehicle class is disabled by the server.";
                                categoryBtn.Enabled     = false;
                                categoryBtn.LeftIcon    = MenuItem.Icon.LOCK;
                                categoryBtn.Label       = "";
                                continue;
                            }

                            // Loop through all addon vehicles in this class.
                            foreach (KeyValuePair <string, uint> veh in AddonVehicles.Where(v => GetVehicleClassFromName(v.Value) == cat))
                            {
                                string localizedName = GetLabelText(GetDisplayNameFromVehicleModel(veh.Value));

                                string name = localizedName != "NULL" ? localizedName : GetDisplayNameFromVehicleModel(veh.Value);
                                name = name != "CARNOTFOUND" ? name : veh.Key;

                                MenuItem carBtn = new MenuItem(name, $"Click to spawn {name}.")
                                {
                                    Label    = $"({veh.Key})",
                                    ItemData = veh.Key // store the model name in the button data.
                                };

                                // This should be impossible to be false, but we check it anyway.
                                if (IsModelInCdimage(veh.Value))
                                {
                                    categoryMenu.AddMenuItem(carBtn);
                                }
                                else
                                {
                                    carBtn.Enabled     = false;
                                    carBtn.Description = "This vehicle is not available. Please ask the server owner to check if the vehicle is being streamed correctly.";
                                    carBtn.LeftIcon    = MenuItem.Icon.LOCK;
                                    unavailableCars.AddMenuItem(carBtn);
                                }
                            }

                            //if (AddonVehicles.Count(av => GetVehicleClassFromName(av.Value) == cat && IsModelInCdimage(av.Value)) > 0)
                            if (categoryMenu.Size > 0)
                            {
                                MenuController.AddSubmenu(addonCarsMenu, categoryMenu);
                                MenuController.BindMenuItem(addonCarsMenu, categoryMenu, categoryBtn);

                                categoryMenu.OnItemSelect += (sender, item, index) =>
                                {
                                    SpawnVehicle(item.ItemData.ToString(), SpawnInVehicle, ReplaceVehicle);
                                };
                            }
                            else
                            {
                                categoryBtn.Description = "There are no addon cars available in this category.";
                                categoryBtn.Enabled     = false;
                                categoryBtn.LeftIcon    = MenuItem.Icon.LOCK;
                                categoryBtn.Label       = "";
                            }
                        }

                        if (unavailableCars.Size > 0)
                        {
                            addonCarsMenu.AddMenuItem(unavailableCarsBtn);
                            MenuController.BindMenuItem(addonCarsMenu, unavailableCars, unavailableCarsBtn);
                        }
                    }
                    else
                    {
                        addonCarsBtn.Enabled     = false;
                        addonCarsBtn.LeftIcon    = MenuItem.Icon.LOCK;
                        addonCarsBtn.Description = "There are no addon vehicles available on this server.";
                    }
                }
                else
                {
                    addonCarsBtn.Enabled     = false;
                    addonCarsBtn.LeftIcon    = MenuItem.Icon.LOCK;
                    addonCarsBtn.Description = "The list containing all addon cars could not be loaded, is it configured properly?";
                }
            }
            else
            {
                addonCarsBtn.Enabled     = false;
                addonCarsBtn.LeftIcon    = MenuItem.Icon.LOCK;
                addonCarsBtn.Description = "Access to this list has been restricted by the server owner.";
            }
            #endregion

            // These are the max speed, acceleration, braking and traction values per vehicle class.
            float[] speedValues = new float[23]
            {
                44.9374657f,
                50.0000038f,
                48.862133f,
                48.1321335f,
                50.7077942f,
                51.3333359f,
                52.3922348f,
                53.86687f,
                52.03867f,
                49.2241631f,
                39.6176529f,
                37.5559425f,
                42.72843f,
                21.0f,
                45.0f,
                65.1952744f,
                109.764259f,
                42.72843f,
                56.5962219f,
                57.5398865f,
                43.3140678f,
                26.66667f,
                53.0537224f
            };
            float[] accelerationValues = new float[23]
            {
                0.34f,
                0.29f,
                0.335f,
                0.28f,
                0.395f,
                0.39f,
                0.66f,
                0.42f,
                0.425f,
                0.475f,
                0.21f,
                0.3f,
                0.32f,
                0.17f,
                18.0f,
                5.88f,
                21.0700016f,
                0.33f,
                14.0f,
                6.86f,
                0.32f,
                0.2f,
                0.76f
            };
            float[] brakingValues = new float[23]
            {
                0.72f,
                0.95f,
                0.85f,
                0.9f,
                1.0f,
                1.0f,
                1.3f,
                1.25f,
                1.52f,
                1.1f,
                0.6f,
                0.7f,
                0.8f,
                3.0f,
                0.4f,
                3.5920403f,
                20.58f,
                0.9f,
                2.93960738f,
                3.9472363f,
                0.85f,
                5.0f,
                1.3f
            };
            float[] tractionValues = new float[23]
            {
                2.3f,
                2.55f,
                2.3f,
                2.6f,
                2.625f,
                2.65f,
                2.8f,
                2.782f,
                2.9f,
                2.95f,
                2.0f,
                3.3f,
                2.175f,
                2.05f,
                0.0f,
                1.6f,
                2.15f,
                2.55f,
                2.57f,
                3.7f,
                2.05f,
                2.5f,
                3.2925f
            };

            #region vehicle classes submenus
            // Loop through all the vehicle classes.
            for (var vehClass = 0; vehClass < 23; vehClass++)
            {
                // Get the class name.
                string className = GetLabelText($"VEH_CLASS_{vehClass}");

                // Create a button & a menu for it, add the menu to the menu pool and add & bind the button to the menu.
                MenuItem btn = new MenuItem(className, $"Spawn a vehicle from the ~o~{className} ~s~class.")
                {
                    Label = "→→→"
                };

                Menu vehicleClassMenu = new Menu("Vehicle Spawner", className);

                MenuController.AddSubmenu(menu, vehicleClassMenu);
                menu.AddMenuItem(btn);

                if (allowedCategories[vehClass])
                {
                    MenuController.BindMenuItem(menu, vehicleClassMenu, btn);
                }
                else
                {
                    btn.LeftIcon    = MenuItem.Icon.LOCK;
                    btn.Description = "This category has been disabled by the server owner.";
                    btn.Enabled     = false;
                }

                // Create a dictionary for the duplicate vehicle names (in this vehicle class).
                var duplicateVehNames = new Dictionary <string, int>();

                #region Add vehicles per class
                // Loop through all the vehicles in the vehicle class.
                foreach (var veh in VehicleData.Vehicles.VehicleClasses[className])
                {
                    // Convert the model name to start with a Capital letter, converting the other characters to lowercase.
                    string properCasedModelName = veh[0].ToString().ToUpper() + veh.ToLower().Substring(1);

                    // Get the localized vehicle name, if it's "NULL" (no label found) then use the "properCasedModelName" created above.
                    string vehName      = GetVehDisplayNameFromModel(veh) != "NULL" ? GetVehDisplayNameFromModel(veh) : properCasedModelName;
                    string vehModelName = veh;
                    uint   model        = (uint)GetHashKey(vehModelName);

                    float topSpeed     = Map(GetVehicleModelEstimatedMaxSpeed(model), 0f, speedValues[vehClass], 0f, 1f);
                    float acceleration = Map(GetVehicleModelAcceleration(model), 0f, accelerationValues[vehClass], 0f, 1f);
                    float maxBraking   = Map(GetVehicleModelMaxBraking(model), 0f, brakingValues[vehClass], 0f, 1f);
                    float maxTraction  = Map(GetVehicleModelMaxTraction(model), 0f, tractionValues[vehClass], 0f, 1f);

                    // Loop through all the menu items and check each item's title/text and see if it matches the current vehicle (display) name.
                    var duplicate = false;
                    for (var itemIndex = 0; itemIndex < vehicleClassMenu.Size; itemIndex++)
                    {
                        // If it matches...
                        if (vehicleClassMenu.GetMenuItems()[itemIndex].Text.ToString() == vehName)
                        {
                            // Check if the model was marked as duplicate before.
                            if (duplicateVehNames.Keys.Contains(vehName))
                            {
                                // If so, add 1 to the duplicate counter for this model name.
                                duplicateVehNames[vehName]++;
                            }

                            // If this is the first duplicate, then set it to 2.
                            else
                            {
                                duplicateVehNames[vehName] = 2;
                            }

                            // The model name is a duplicate, so get the modelname and add the duplicate amount for this model name to the end of the vehicle name.
                            vehName += $" ({duplicateVehNames[vehName]})";

                            // Then create and add a new button for this vehicle.

                            if (DoesModelExist(veh))
                            {
                                var vehBtn = new MenuItem(vehName)
                                {
                                    Enabled  = true,
                                    Label    = $"({vehModelName.ToLower()})",
                                    ItemData = new float[4] {
                                        topSpeed, acceleration, maxBraking, maxTraction
                                    }
                                };
                                vehicleClassMenu.AddMenuItem(vehBtn);
                            }
                            else
                            {
                                var vehBtn = new MenuItem(vehName, "This vehicle is not available because the model could not be found in your game files. If this is a DLC vehicle, make sure the server is streaming it.")
                                {
                                    Enabled  = false,
                                    Label    = $"({vehModelName.ToLower()})",
                                    ItemData = new float[4] {
                                        0f, 0f, 0f, 0f
                                    }
                                };
                                vehicleClassMenu.AddMenuItem(vehBtn);
                                vehBtn.RightIcon = MenuItem.Icon.LOCK;
                            }

                            // Mark duplicate as true and break from the loop because we already found the duplicate.
                            duplicate = true;
                            break;
                        }
                    }

                    // If it's not a duplicate, add the model name.
                    if (!duplicate)
                    {
                        if (DoesModelExist(veh))
                        {
                            var vehBtn = new MenuItem(vehName)
                            {
                                Enabled  = true,
                                Label    = $"({vehModelName.ToLower()})",
                                ItemData = new float[4] {
                                    topSpeed, acceleration, maxBraking, maxTraction
                                }
                            };
                            vehicleClassMenu.AddMenuItem(vehBtn);
                        }
                        else
                        {
                            var vehBtn = new MenuItem(vehName, "This vehicle is not available because the model could not be found in your game files. If this is a DLC vehicle, make sure the server is streaming it.")
                            {
                                Enabled  = false,
                                Label    = $"({vehModelName.ToLower()})",
                                ItemData = new float[4] {
                                    0f, 0f, 0f, 0f
                                }
                            };
                            vehicleClassMenu.AddMenuItem(vehBtn);
                            vehBtn.RightIcon = MenuItem.Icon.LOCK;
                        }
                    }
                }
                #endregion

                vehicleClassMenu.ShowVehicleStatsPanel = true;

                // Handle button presses
                vehicleClassMenu.OnItemSelect += (sender2, item2, index2) =>
                {
                    SpawnVehicle(VehicleData.Vehicles.VehicleClasses[className][index2], SpawnInVehicle, ReplaceVehicle);
                };

                void HandleStatsPanel(Menu openedMenu, MenuItem currentItem)
                {
                    if (currentItem != null)
                    {
                        if (currentItem.ItemData is float[] data)
                        {
                            openedMenu.ShowVehicleStatsPanel = true;
                            openedMenu.SetVehicleStats(data[0], data[1], data[2], data[3]);
                            openedMenu.SetVehicleUpgradeStats(0f, 0f, 0f, 0f);
                        }
                        else
                        {
                            openedMenu.ShowVehicleStatsPanel = false;
                        }
                    }
                }

                vehicleClassMenu.OnMenuOpen += (m) =>
                {
                    HandleStatsPanel(m, m.GetCurrentMenuItem());
                };

                vehicleClassMenu.OnIndexChange += (m, oldItem, newItem, oldIndex, newIndex) =>
                {
                    HandleStatsPanel(m, newItem);
                };
            }
            #endregion

            #region handle events
            // Handle button presses.
            menu.OnItemSelect += (sender, item, index) =>
            {
                if (item == spawnByName)
                {
                    // Passing "custom" as the vehicle name, will ask the user for input.
                    SpawnVehicle("custom", SpawnInVehicle, ReplaceVehicle);
                }
            };

            // Handle checkbox changes.
            menu.OnCheckboxChange += (sender, item, index, _checked) =>
            {
                if (item == spawnInVeh)
                {
                    SpawnInVehicle = _checked;
                }
                else if (item == replacePrev)
                {
                    ReplaceVehicle = _checked;
                }
            };
            #endregion
        }
Пример #15
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
        }
Пример #16
0
        public MenuHandler()
        {
            // Menus
            menu             = new Menu("Roleplay Menu");
            destinationsMenu = new Menu("Destinations");
            miscSettingsMenu = new Menu("Misc Settings");

            // Create menu controller
            if (menuController == null)
            {
                menuController = new MenuController();
                MenuController.AddMenu(menu);
                MenuController.AddMenu(destinationsMenu);
                MenuController.AddMenu(miscSettingsMenu);
                MenuController.MenuAlignment = MenuController.MenuAlignmentOption.Right;
                MenuController.MenuToggleKey = Control.MultiplayerInfo;
                MenuController.EnableMenuToggleKeyOnController = false;
                MenuController.MainMenu = menu;
                MenuController.AddSubmenu(menu, miscSettingsMenu);
            }

            // Main menu items
            MenuItem taxiItem = new MenuItem("Call Taxi", "Dispatches a taxi to your current location")
            {
                Enabled  = true,
                LeftIcon = MenuItem.Icon.CAR
            };

            menu.AddMenuItem(taxiItem);

            MenuItem miscSettingsItem = new MenuItem("Miscellaneous Settings", "Configure various miscellaneous settings.")
            {
                Enabled = true,
            };

            menu.AddMenuItem(miscSettingsItem);

            // Misc Settings items
            MenuCheckboxItem seatShuffleItem = new MenuCheckboxItem("Disable passenger seat shuffling",
                                                                    "Disables the automatic seat shuffling the passenger performs if the driver seat is empty", true)
            {
                Enabled = true,
                Checked = false
            };

            miscSettingsMenu.AddMenuItem(seatShuffleItem);

            // Main menu events
            menu.OnItemSelect += (_menu, _item, _index) =>
            {
                if (_item == taxiItem)
                {
                    UIHandler.ShowNotificationWithIcon("CHAR_TAXI", "CHAR_TAXI", "A taxi will be dispatched to your location shortly.", "Downtown Cab & Co.");
                    menu.CloseMenu();
                    TriggerEvent("RoleplayMenu:SendTaxiToPlayer");
                }
                else if (_item == miscSettingsItem)
                {
                    menu.CloseMenu();
                    miscSettingsMenu.OpenMenu();
                }
            };

            // Misc settings menu events

            miscSettingsMenu.OnCheckboxChange += (_sender, _item, _index, _checked) =>
            {
                Debug.WriteLine("Shitty");
                if (_item == seatShuffleItem)
                {
                    Debug.WriteLine("Selected item");
                    VehicleSettings.DisableSeatShuffle = seatShuffleItem.Checked;
                }
            };

            miscSettingsMenu.OnMenuClose += (_sender) =>
            {
                miscSettingsMenu.ParentMenu.OpenMenu();
            };

            // Destination menu events
            destinationsMenu.OnItemSelect += (_menu, _item, _index) =>
            {
                if (_index == 0)
                {
                    if (IsWaypointActive())
                    {
                        TaxiHandler.GetCurrentTaxi().DriveToDestination(World.GetNextPositionOnStreet(World.WaypointPosition));
                    }
                }
                else
                {
                    foreach (int p in GetActivePlayers())
                    {
                        if (_item.Text == GetPlayerName(p))
                        {
                            TaxiHandler.GetCurrentTaxi().DriveToDestination(World.GetNextPositionOnStreet(GetEntityCoords(GetPlayerPed(p), true)));
                        }
                    }
                }
            };
        }
Пример #17
0
        private void CreateMenu()
        {
            Misc = new Menu("Miscellaneous", "Miscellaneous stuff");

            MenuCheckboxItem Align = new MenuCheckboxItem("Right Align Menu", "This will change the menu to appear on the left", !Misc.LeftAligned)
            {
                Style = MenuCheckboxItem.CheckboxStyle.Tick
            };

            Misc.AddMenuItem(Align);

            /*
             * MenuCheckboxItem DebugMode = new MenuCheckboxItem("Debug Mode", "This will enable debug mode", MainMenu.DebugMode)
             * {
             *  Style = MenuCheckboxItem.CheckboxStyle.Tick
             * };
             * Misc.AddMenuItem(DebugMode);
             */
            // Credits
            Misc.AddMenuItem(new MenuItem("Made using MenuAPI by Vespura", "Full credit to him otherwise this wouldn't be possible! <3"));

            /*
             ########################################################
             #                  Event handlers
             ########################################################
             */
            Misc.OnCheckboxChange += (_menu, _item, _index, _checked) =>
            {
                // Code in here gets executed whenever a checkbox is toggled.
                if (MainMenu.DebugMode == true)
                {
                    Debug.WriteLine($"OnCheckboxChange: [{_menu}, {_item}, {_index}, {_checked}]");
                }

                // If the align-menu checkbox is toggled, toggle the menu alignment.
                if (_item == Align)
                {
                    if (_checked)
                    {
                        MenuController.MenuAlignment = MenuController.MenuAlignmentOption.Right;
                    }
                    else
                    {
                        MenuController.MenuAlignment = MenuController.MenuAlignmentOption.Left;
                    }
                }

                /*
                 * if (_item == DebugMode)
                 * {
                 *  if (_checked)
                 *  {
                 *      MainMenu.DebugMode = true;
                 *  }
                 *  else
                 *  {
                 *      MainMenu.DebugMode = false;
                 *  }
                 * }*/
            };
        }
Пример #18
0
        private void CreateMenu()
        {
            #region initial setup.
            // Create the menu.
            menu = new Menu(Game.Player.Name, "Vehicle Spawner");

            // Create the buttons and checkboxes.
            MenuItem         spawnByName = new MenuItem("Spawn Vehicle By Model Name", "Enter the name of a vehicle to spawn.");
            MenuCheckboxItem spawnInVeh  = new MenuCheckboxItem("Spawn Inside Vehicle", "This will teleport you into the vehicle when you spawn it.", SpawnInVehicle);
            MenuCheckboxItem replacePrev = new MenuCheckboxItem("Replace Previous Vehicle", "This will automatically delete your previously spawned vehicle when you spawn a new vehicle.", ReplaceVehicle);

            // Add the items to the menu.
            if (IsAllowed(Permission.VSSpawnByName))
            {
                menu.AddMenuItem(spawnByName);
            }
            menu.AddMenuItem(spawnInVeh);
            menu.AddMenuItem(replacePrev);
            #endregion

            #region addon cars menu
            // Vehicle Addons List
            Menu     addonCarsMenu = new Menu("Addon Vehicles", "Spawn An Addon Vehicle");
            MenuItem addonCarsBtn  = new MenuItem("Addon Vehicles", "A list of addon vehicles available on this server.")
            {
                Label = "→→→"
            };

            menu.AddMenuItem(addonCarsBtn);

            if (IsAllowed(Permission.VSAddon))
            {
                if (AddonVehicles != null)
                {
                    if (AddonVehicles.Count > 0)
                    {
                        MenuController.BindMenuItem(menu, addonCarsMenu, addonCarsBtn);
                        MenuController.AddSubmenu(menu, addonCarsMenu);
                        Menu     unavailableCars    = new Menu("Addon Spawner", "Unavailable Vehicles");
                        MenuItem unavailableCarsBtn = new MenuItem("Unavailable Vehicles", "These addon vehicles are not currently being streamed (correctly) and are not able to be spawned.")
                        {
                            Label = "→→→"
                        };
                        MenuController.AddSubmenu(addonCarsMenu, unavailableCars);

                        for (var cat = 0; cat < 23; cat++)
                        {
                            Menu     categoryMenu = new Menu("Addon Spawner", GetLabelText($"VEH_CLASS_{cat}"));
                            MenuItem categoryBtn  = new MenuItem(GetLabelText($"VEH_CLASS_{cat}"), $"Spawn an addon vehicle from the {GetLabelText($"VEH_CLASS_{cat}")} class.")
                            {
                                Label = "→→→"
                            };

                            addonCarsMenu.AddMenuItem(categoryBtn);

                            if (!allowedCategories[cat])
                            {
                                categoryBtn.Description = "This vehicle class is disabled by the server.";
                                categoryBtn.Enabled     = false;
                                categoryBtn.LeftIcon    = MenuItem.Icon.LOCK;
                                categoryBtn.Label       = "";
                                continue;
                            }

                            // Loop through all addon vehicles in this class.
                            foreach (KeyValuePair <string, uint> veh in AddonVehicles.Where(v => GetVehicleClassFromName(v.Value) == cat))
                            {
                                string localizedName = GetLabelText(GetDisplayNameFromVehicleModel(veh.Value));

                                string name = localizedName != "NULL" ? localizedName : GetDisplayNameFromVehicleModel(veh.Value);
                                name = name != "CARNOTFOUND" ? name : veh.Key;

                                MenuItem carBtn = new MenuItem(name, $"Click to spawn {name}.")
                                {
                                    Label    = $"({veh.Key})",
                                    ItemData = veh.Key // store the model name in the button data.
                                };

                                // This should be impossible to be false, but we check it anyway.
                                if (IsModelInCdimage(veh.Value))
                                {
                                    categoryMenu.AddMenuItem(carBtn);
                                }
                                else
                                {
                                    carBtn.Enabled     = false;
                                    carBtn.Description = "This vehicle is not available. Please ask the server owner to check if the vehicle is being streamed correctly.";
                                    carBtn.LeftIcon    = MenuItem.Icon.LOCK;
                                    unavailableCars.AddMenuItem(carBtn);
                                }
                            }

                            //if (AddonVehicles.Count(av => GetVehicleClassFromName(av.Value) == cat && IsModelInCdimage(av.Value)) > 0)
                            if (categoryMenu.Size > 0)
                            {
                                MenuController.AddSubmenu(addonCarsMenu, categoryMenu);
                                MenuController.BindMenuItem(addonCarsMenu, categoryMenu, categoryBtn);

                                categoryMenu.OnItemSelect += (sender, item, index) =>
                                {
                                    SpawnVehicle(item.ItemData.ToString(), SpawnInVehicle, ReplaceVehicle);
                                };
                            }
                            else
                            {
                                categoryBtn.Description = "There are no addon cars available in this category.";
                                categoryBtn.Enabled     = false;
                                categoryBtn.LeftIcon    = MenuItem.Icon.LOCK;
                                categoryBtn.Label       = "";
                            }
                        }

                        if (unavailableCars.Size > 0)
                        {
                            addonCarsMenu.AddMenuItem(unavailableCarsBtn);
                            MenuController.BindMenuItem(addonCarsMenu, unavailableCars, unavailableCarsBtn);
                        }
                    }
                    else
                    {
                        addonCarsBtn.Enabled     = false;
                        addonCarsBtn.LeftIcon    = MenuItem.Icon.LOCK;
                        addonCarsBtn.Description = "There are no addon vehicles available on this server.";
                    }
                }
                else
                {
                    addonCarsBtn.Enabled     = false;
                    addonCarsBtn.LeftIcon    = MenuItem.Icon.LOCK;
                    addonCarsBtn.Description = "The list containing all addon cars could not be loaded, is it configured properly?";
                }
            }
            else
            {
                addonCarsBtn.Enabled     = false;
                addonCarsBtn.LeftIcon    = MenuItem.Icon.LOCK;
                addonCarsBtn.Description = "Access to this list has been restricted by the server owner.";
            }
            #endregion

            #region vehicle classes submenus
            // Loop through all the vehicle classes.
            for (var vehClass = 0; vehClass < 23; vehClass++)
            {
                // Get the class name.
                string className = GetLabelText($"VEH_CLASS_{vehClass}");

                // Create a button & a menu for it, add the menu to the menu pool and add & bind the button to the menu.
                MenuItem btn = new MenuItem(className, $"Spawn a vehicle from the ~o~{className} ~s~class.")
                {
                    Label = "→→→"
                };

                Menu vehicleClassMenu = new Menu("Vehicle Spawner", className);

                MenuController.AddSubmenu(menu, vehicleClassMenu);
                menu.AddMenuItem(btn);

                if (allowedCategories[vehClass])
                {
                    MenuController.BindMenuItem(menu, vehicleClassMenu, btn);
                }
                else
                {
                    btn.LeftIcon    = MenuItem.Icon.LOCK;
                    btn.Description = "This category has been disabled by the server owner.";
                    btn.Enabled     = false;
                }

                // Create a dictionary for the duplicate vehicle names (in this vehicle class).
                var duplicateVehNames = new Dictionary <string, int>();

                #region Add vehicles per class
                // Loop through all the vehicles in the vehicle class.
                foreach (var veh in VehicleData.Vehicles.VehicleClasses[className])
                {
                    // Convert the model name to start with a Capital letter, converting the other characters to lowercase.
                    string properCasedModelName = veh[0].ToString().ToUpper() + veh.ToLower().Substring(1);

                    // Get the localized vehicle name, if it's "NULL" (no label found) then use the "properCasedModelName" created above.
                    string vehName      = GetVehDisplayNameFromModel(veh) != "NULL" ? GetVehDisplayNameFromModel(veh) : properCasedModelName;
                    string vehModelName = veh;

                    // Loop through all the menu items and check each item's title/text and see if it matches the current vehicle (display) name.
                    var duplicate = false;
                    for (var itemIndex = 0; itemIndex < vehicleClassMenu.Size; itemIndex++)
                    {
                        // If it matches...
                        if (vehicleClassMenu.GetMenuItems()[itemIndex].Text.ToString() == vehName)
                        {
                            // Check if the model was marked as duplicate before.
                            if (duplicateVehNames.Keys.Contains(vehName))
                            {
                                // If so, add 1 to the duplicate counter for this model name.
                                duplicateVehNames[vehName]++;
                            }

                            // If this is the first duplicate, then set it to 2.
                            else
                            {
                                duplicateVehNames[vehName] = 2;
                            }

                            // The model name is a duplicate, so get the modelname and add the duplicate amount for this model name to the end of the vehicle name.
                            vehName += $" ({duplicateVehNames[vehName]})";

                            // Then create and add a new button for this vehicle.

                            if (DoesModelExist(veh))
                            {
                                var vehBtn = new MenuItem(vehName)
                                {
                                    Enabled = true, Label = $"({vehModelName.ToLower()})"
                                };
                                vehicleClassMenu.AddMenuItem(vehBtn);
                            }
                            else
                            {
                                var vehBtn = new MenuItem(vehName, "This vehicle is not available because the model could not be found in your game files. If this is a DLC vehicle, make sure the server is streaming it.")
                                {
                                    Enabled = false, Label = $"({vehModelName.ToLower()})"
                                };
                                vehicleClassMenu.AddMenuItem(vehBtn);
                                vehBtn.RightIcon = MenuItem.Icon.LOCK;
                            }

                            // Mark duplicate as true and break from the loop because we already found the duplicate.
                            duplicate = true;
                            break;
                        }
                    }

                    // If it's not a duplicate, add the model name.
                    if (!duplicate)
                    {
                        if (DoesModelExist(veh))
                        {
                            var vehBtn = new MenuItem(vehName)
                            {
                                Enabled = true, Label = $"({vehModelName.ToLower()})"
                            };
                            vehicleClassMenu.AddMenuItem(vehBtn);
                        }
                        else
                        {
                            var vehBtn = new MenuItem(vehName, "This vehicle is not available because the model could not be found in your game files. If this is a DLC vehicle, make sure the server is streaming it.")
                            {
                                Enabled = false, Label = $"({vehModelName.ToLower()})"
                            };
                            vehicleClassMenu.AddMenuItem(vehBtn);
                            vehBtn.RightIcon = MenuItem.Icon.LOCK;
                        }
                    }
                }
                #endregion

                // Handle button presses
                vehicleClassMenu.OnItemSelect += (sender2, item2, index2) =>
                {
                    SpawnVehicle(VehicleData.Vehicles.VehicleClasses[className][index2], SpawnInVehicle, ReplaceVehicle);
                };
            }
            #endregion

            #region handle events
            // Handle button presses.
            menu.OnItemSelect += (sender, item, index) =>
            {
                if (item == spawnByName)
                {
                    // Passing "custom" as the vehicle name, will ask the user for input.
                    SpawnVehicle("custom", SpawnInVehicle, ReplaceVehicle);
                }
            };

            // Handle checkbox changes.
            menu.OnCheckboxChange += (sender, item, index, _checked) =>
            {
                if (item == spawnInVeh)
                {
                    SpawnInVehicle = _checked;
                }
                else if (item == replacePrev)
                {
                    ReplaceVehicle = _checked;
                }
            };
            #endregion
        }
Пример #19
0
        private void CreateMenu()
        {
            // Create the menu.
            menu = new Menu(Game.Player.Name, "Weather Options");

            dynamicWeatherEnabled = new MenuCheckboxItem("Toggle Dynamic Weather", "Enable or disable dynamic weather changes.", EventManager.dynamicWeather);
            blackout = new MenuCheckboxItem("Toggle Blackout", "This disables or enables all lights across the map.", EventManager.blackoutMode);
            MenuItem extrasunny      = new MenuItem("Extra Sunny", "Set the weather to ~y~extra sunny~s~!");
            MenuItem clear           = new MenuItem("Clear", "Set the weather to ~y~clear~s~!");
            MenuItem neutral         = new MenuItem("Neutral", "Set the weather to ~y~neutral~s~!");
            MenuItem smog            = new MenuItem("Smog", "Set the weather to ~y~smog~s~!");
            MenuItem foggy           = new MenuItem("Foggy", "Set the weather to ~y~foggy~s~!");
            MenuItem clouds          = new MenuItem("Cloudy", "Set the weather to ~y~clouds~s~!");
            MenuItem overcast        = new MenuItem("Overcast", "Set the weather to ~y~overcast~s~!");
            MenuItem clearing        = new MenuItem("Clearing", "Set the weather to ~y~clearing~s~!");
            MenuItem rain            = new MenuItem("Rainy", "Set the weather to ~y~rain~s~!");
            MenuItem thunder         = new MenuItem("Thunder", "Set the weather to ~y~thunder~s~!");
            MenuItem blizzard        = new MenuItem("Blizzard", "Set the weather to ~y~blizzard~s~!");
            MenuItem snow            = new MenuItem("Snow", "Set the weather to ~y~snow~s~!");
            MenuItem snowlight       = new MenuItem("Light Snow", "Set the weather to ~y~light snow~s~!");
            MenuItem xmas            = new MenuItem("X-MAS Snow", "Set the weather to ~y~x-mas~s~!");
            MenuItem halloween       = new MenuItem("Halloween", "Set the weather to ~y~halloween~s~!");
            MenuItem removeclouds    = new MenuItem("Remove All Clouds", "Remove all clouds from the sky!");
            MenuItem randomizeclouds = new MenuItem("Randomize Clouds", "Add random clouds to the sky!");

            var indexOffset = 2;

            if (IsAllowed(Permission.WODynamic))
            {
                menu.AddMenuItem(dynamicWeatherEnabled);
                indexOffset--;
            }
            if (IsAllowed(Permission.WOBlackout))
            {
                menu.AddMenuItem(blackout);
                indexOffset--;
            }
            if (IsAllowed(Permission.WOSetWeather))
            {
                weatherHashMenuIndex.Add("-1750463879", extrasunny);
                weatherHashMenuIndex.Add("916995460", clear);
                weatherHashMenuIndex.Add("-1530260698", neutral);
                weatherHashMenuIndex.Add("282916021", smog);
                weatherHashMenuIndex.Add("-1368164796", foggy);
                weatherHashMenuIndex.Add("821931868", clouds);
                weatherHashMenuIndex.Add("-1148613331", overcast);
                weatherHashMenuIndex.Add("1840358669", clearing);
                weatherHashMenuIndex.Add("1420204096", rain);
                weatherHashMenuIndex.Add("-1233681761", thunder);
                weatherHashMenuIndex.Add("669657108", blizzard);
                weatherHashMenuIndex.Add("-273223690", snow);
                weatherHashMenuIndex.Add("603685163", snowlight);
                weatherHashMenuIndex.Add("-1429616491", xmas);
                weatherHashMenuIndex.Add("-921030142", halloween);

                menu.AddMenuItem(extrasunny);
                menu.AddMenuItem(clear);
                menu.AddMenuItem(neutral);
                menu.AddMenuItem(smog);
                menu.AddMenuItem(foggy);
                menu.AddMenuItem(clouds);
                menu.AddMenuItem(overcast);
                menu.AddMenuItem(clearing);
                menu.AddMenuItem(rain);
                menu.AddMenuItem(thunder);
                menu.AddMenuItem(blizzard);
                menu.AddMenuItem(snow);
                menu.AddMenuItem(snowlight);
                menu.AddMenuItem(xmas);
                menu.AddMenuItem(halloween);
            }
            if (IsAllowed(Permission.WORandomizeClouds))
            {
                menu.AddMenuItem(removeclouds);
            }

            if (IsAllowed(Permission.WORemoveClouds))
            {
                menu.AddMenuItem(randomizeclouds);
            }

            List <string> weatherTypes = new List <string>()
            {
                "EXTRASUNNY",
                "CLEAR",
                "NEUTRAL",
                "SMOG",
                "FOGGY",
                "CLOUDS",
                "OVERCAST",
                "CLEARING",
                "RAIN",
                "THUNDER",
                "BLIZZARD",
                "SNOW",
                "SNOWLIGHT",
                "XMAS",
                "HALLOWEEN"
            };

            menu.OnItemSelect += (sender, item, index2) =>
            {
                var index = index2 + indexOffset;
                // A weather type is selected.
                if (index >= 2 && index <= 16)
                {
                    Notify.Custom($"The weather will be changed to ~y~{weatherTypes[index - 2]}~s~ in the next 45 seconds.");
                    UpdateServerWeather(weatherTypes[index - 2], EventManager.blackoutMode, EventManager.dynamicWeather);
                }
                if (item == removeclouds)
                {
                    ModifyClouds(true);
                }
                else if (item == randomizeclouds)
                {
                    ModifyClouds(false);
                }
            };

            menu.OnCheckboxChange += (sender, item, index, _checked) =>
            {
                if (item == dynamicWeatherEnabled)
                {
                    EventManager.dynamicWeather = _checked;
                    Notify.Custom($"Dynamic weather changes are now {(_checked ? "~g~enabled" : "~r~disabled")}~s~.");
                    UpdateServerWeather(EventManager.currentWeatherType, EventManager.blackoutMode, _checked);
                }
                else if (item == blackout)
                {
                    EventManager.blackoutMode = _checked;
                    Notify.Custom($"Blackout mode is now {(_checked ? "~g~enabled" : "~r~disabled")}~s~.");
                    UpdateServerWeather(EventManager.currentWeatherType, _checked, EventManager.dynamicWeather);
                }
            };
        }
Пример #20
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
        }
Пример #21
0
        public ExampleMenu()
        {
            // Setting the menu alignment to be right aligned. This can be changed at any time and it'll update instantly.
            // To test this, checkout one of the checkbox items in this example menu. Clicking it will toggle the menu alignment.
            MenuController.MenuAlignment = MenuController.MenuAlignmentOption.Right;

            // Creating the first menu.
            Menu menu = new Menu("Main Menu", "Subtitle")
            {
                Visible = true
            };

            MenuController.AddMenu(menu);

            // Adding a new button by directly creating one inline. You could also just store it and then add it but we don't need to do that in this example.
            menu.AddMenuItem(new MenuItem("Normal Button", "This is a simple button with a simple description. Scroll down for more button types!"));


            // Creating 3 sliders, showing off the 3 possible variations and custom colors.
            MenuSliderItem slider  = new MenuSliderItem("Slider", 0, 10, 5, false);
            MenuSliderItem slider2 = new MenuSliderItem("Slider + Bar", 0, 10, 5, true)
            {
                BarColor        = Color.FromArgb(255, 73, 233, 111),
                BackgroundColor = Color.FromArgb(255, 25, 100, 43)
            };
            MenuSliderItem slider3 = new MenuSliderItem("Slider + Bar + Icons", "The icons are currently male/female because that's probably the most common use. But any icon can be used!", 0, 10, 5, true)
            {
                BarColor        = Color.FromArgb(255, 255, 0, 0),
                BackgroundColor = Color.FromArgb(255, 100, 0, 0),
                SliderLeftIcon  = MenuItem.Icon.MALE,
                SliderRightIcon = MenuItem.Icon.FEMALE
            };

            // adding the sliders to the menu.
            menu.AddMenuItem(slider);
            menu.AddMenuItem(slider2);
            menu.AddMenuItem(slider3);

            // Creating 3 checkboxs, 2 different styles and one has a locked icon and it's 'not enabled' (not enabled meaning you can't toggle it).
            MenuCheckboxItem box = new MenuCheckboxItem("Checkbox - Style 1 (click me!)", "This checkbox can toggle the menu position! Try it out.", !menu.LeftAligned)
            {
                Style = MenuCheckboxItem.CheckboxStyle.Tick
            };

            MenuCheckboxItem box2 = new MenuCheckboxItem("Checkbox - Style 2", "This checkbox does nothing right now.", true)
            {
                Style = MenuCheckboxItem.CheckboxStyle.Cross
            };

            MenuCheckboxItem box3 = new MenuCheckboxItem("Checkbox (unchecked + locked)", "Make this menu right aligned. If you set this to false, then the menu will move to the left.", false)
            {
                Style    = MenuCheckboxItem.CheckboxStyle.Cross,
                Enabled  = false,
                LeftIcon = MenuItem.Icon.LOCK
            };

            // Adding the checkboxes to the menu.
            menu.AddMenuItem(box);
            menu.AddMenuItem(box2);
            menu.AddMenuItem(box3);

            // List items (first the 3 special variants, then a normal one)
            List <string> colorList = new List <string>();

            for (var i = 0; i < 64; i++)
            {
                colorList.Add($"Color #{i}");
            }
            MenuListItem hairColors = new MenuListItem("Hair Color", colorList, 0, "Hair color pallete.")
            {
                ShowColorPanel = true
            };

            // Also special
            List <string> makeupColorList = new List <string>();

            for (var i = 0; i < 64; i++)
            {
                makeupColorList.Add($"Color #{i}");
            }
            MenuListItem makeupColors = new MenuListItem("Makeup Color", makeupColorList, 0, "Makeup color pallete.")
            {
                ShowColorPanel      = true,
                ColorPanelColorType = MenuListItem.ColorPanelType.Makeup
            };

            // Also special
            List <string> opacityList = new List <string>();

            for (var i = 0; i < 11; i++)
            {
                opacityList.Add($"Opacity {i * 10}%");
            }
            MenuListItem opacity = new MenuListItem("Opacity Panel", opacityList, 0, "Set an opacity for something.")
            {
                ShowOpacityPanel = true
            };

            // Normal
            List <string> normalList = new List <string>()
            {
                "Item #1", "Item #2", "Item #3"
            };
            MenuListItem normalListItem = new MenuListItem("Normal List Item", normalList, 0, "And another simple description for yet another simple (list) item. Nothing special about this one.");

            // Adding the lists to the menu.
            menu.AddMenuItem(hairColors);
            menu.AddMenuItem(makeupColors);
            menu.AddMenuItem(opacity);
            menu.AddMenuItem(normalListItem);

            // Creating a submenu, adding it to the menus list, and creating and binding a button for it.
            Menu submenu = new Menu("Submenu", "Secondary Menu");

            MenuController.AddSubmenu(menu, submenu);

            MenuItem menuButton = new MenuItem("Submenu", "This button is bound to a submenu. Clicking it will take you to the submenu.")
            {
                Label = "→→→"
            };

            menu.AddMenuItem(menuButton);
            MenuController.BindMenuItem(menu, submenu, menuButton);

            // Adding items with sprites left & right to the submenu.
            for (var i = 0; i < 30; i++)
            {
                var tmpItem = new MenuItem($"Icon Sprite #{i}", "This menu item has a left and right sprite, and some also have a right label! Very cool huh?!");
                if (i % 4 == 0)
                {
                    tmpItem.Label = "Wowzers";
                }
                if (i % 7 == 0)
                {
                    tmpItem.Label = "Snailsome!";
                }
                tmpItem.LeftIcon  = (MenuItem.Icon)i;
                tmpItem.RightIcon = (MenuItem.Icon)i;

                submenu.AddMenuItem(tmpItem);
            }

            // Instructional buttons setup for the second (submenu) menu.
            submenu.InstructionalButtons.Add(Control.CharacterWheel, "Right?!");
            submenu.InstructionalButtons.Add(Control.CreatorLS, "Buttons");
            submenu.InstructionalButtons.Add(Control.CursorScrollDown, "Cool");
            submenu.InstructionalButtons.Add(Control.CreatorDelete, "Out!");
            submenu.InstructionalButtons.Add(Control.Cover, "This");
            submenu.InstructionalButtons.Add(Control.Context, "Check");

            // Create a third menu without a banner.
            Menu menu3 = new Menu(null, "Only a subtitle, no banner.");

            // you can use AddSubmenu or AddMenu, both will work but if you want to link this menu from another menu,
            // you should use AddSubmenu.
            MenuController.AddSubmenu(menu, menu3);
            MenuItem thirdSubmenuBtn = new MenuItem("Another submenu", "This is just a submenu without a banner. No big deal.")
            {
                Label = "→→→"
            };

            menu.AddMenuItem(thirdSubmenuBtn);
            MenuController.BindMenuItem(menu, menu3, thirdSubmenuBtn);
            menu3.AddMenuItem(new MenuItem("Nothing here!"));
            menu3.AddMenuItem(new MenuItem("Nothing here!"));
            menu3.AddMenuItem(new MenuItem("Nothing here!"));
            menu3.AddMenuItem(new MenuItem("Nothing here!"));


            /*
             ########################################################
             #                   Event handlers
             ########################################################
             */


            menu.OnCheckboxChange += (_menu, _item, _index, _checked) =>
            {
                // Code in here gets executed whenever a checkbox is toggled.
                Debug.WriteLine($"OnCheckboxChange: [{_menu}, {_item}, {_index}, {_checked}]");

                // If the align-menu checkbox is toggled, toggle the menu alignment.
                if (_item == box)
                {
                    if (_checked)
                    {
                        MenuController.MenuAlignment = MenuController.MenuAlignmentOption.Right;
                    }
                    else
                    {
                        MenuController.MenuAlignment = MenuController.MenuAlignmentOption.Left;
                    }
                }
            };

            menu.OnItemSelect += (_menu, _item, _index) =>
            {
                // Code in here would get executed whenever an item is pressed.
                Debug.WriteLine($"OnItemSelect: [{_menu}, {_item}, {_index}]");
            };

            menu.OnIndexChange += (_menu, _oldItem, _newItem, _oldIndex, _newIndex) =>
            {
                // Code in here would get executed whenever the up or down key is pressed and the index of the menu is changed.
                Debug.WriteLine($"OnIndexChange: [{_menu}, {_oldItem}, {_newItem}, {_oldIndex}, {_newIndex}]");
            };

            menu.OnListIndexChange += (_menu, _listItem, _oldIndex, _newIndex, _itemIndex) =>
            {
                // Code in here would get executed whenever the selected value of a list item changes (when left/right key is pressed).
                Debug.WriteLine($"OnListIndexChange: [{_menu}, {_listItem}, {_oldIndex}, {_newIndex}, {_itemIndex}]");
            };

            menu.OnListItemSelect += (_menu, _listItem, _listIndex, _itemIndex) =>
            {
                // Code in here would get executed whenever a list item is pressed.
                Debug.WriteLine($"OnListItemSelect: [{_menu}, {_listItem}, {_listIndex}, {_itemIndex}]");
            };

            menu.OnSliderPositionChange += (_menu, _sliderItem, _oldPosition, _newPosition, _itemIndex) =>
            {
                // Code in here would get executed whenever the position of a slider is changed (when left/right key is pressed).
                Debug.WriteLine($"OnSliderPositionChange: [{_menu}, {_sliderItem}, {_oldPosition}, {_newPosition}, {_itemIndex}]");
            };

            menu.OnSliderItemSelect += (_menu, _sliderItem, _sliderPosition, _itemIndex) =>
            {
                // Code in here would get executed whenever a slider item is pressed.
                Debug.WriteLine($"OnSliderItemSelect: [{_menu}, {_sliderItem}, {_sliderPosition}, {_itemIndex}]");
            };

            menu.OnMenuClose += (_menu) =>
            {
                // Code in here gets triggered whenever the menu is closed.
                Debug.WriteLine($"OnMenuClose: [{_menu}]");
            };

            menu.OnMenuOpen += (_menu) =>
            {
                // Code in here gets triggered whenever the menu is opened.
                Debug.WriteLine($"OnMenuOpen: [{_menu}]");
            };
        }
        public void BuildFor(SerializableData.SerializablePed actor)
        {
            Clear();

            #region SpawnAfter
            {
                var item = new MenuListItem("Spawn After Objective", StaticData.StaticLists.NumberMenu, actor.SpawnAfter);

                item.OnListChanged += (sender, index) =>
                {
                    actor.SpawnAfter = index;
                };

                AddItem(item);
            }
            #endregion

            #region RemoveAfter
            {
                var item = new MenuListItem("Remove After Objective", StaticData.StaticLists.RemoveAfterList, actor.RemoveAfter);

                item.OnListChanged += (sender, index) =>
                {
                    actor.RemoveAfter = index;
                };

                AddItem(item);
            }
            #endregion
            // TODO: Change NumberMenu to max num of objectives in mission

            // Note: if adding items before weapons, change item order in VehiclePropertiesMenu

            #region Weapons
            {
                var item = new NativeMenuItem("Weapon");
                var dict = StaticData.WeaponsData.Database.ToDictionary(k => k.Key, k => k.Value.Select(x => x.Item1).ToArray());
                var menu = new CategorySelectionMenu(dict, "Weapon", true, "SELECT WEAPON");
                menu.Build("Melee");
                Children.Add(menu);
                AddItem(item);
                BindMenuToItem(menu, item);

                menu.SelectionChanged += (sender, eventargs) =>
                {
                    GameFiber.StartNew(delegate
                    {
                        var hash = StaticData.WeaponsData.Database[menu.CurrentSelectedCategory].First(
                            tuple => tuple.Item1 == menu.CurrentSelectedItem).Item2;
                        NativeFunction.CallByName <uint>("REMOVE_ALL_PED_WEAPONS", actor.GetEntity().Handle.Value, true);
                        ((Ped)actor.GetEntity()).GiveNewWeapon(hash, actor.WeaponAmmo == 0 ? 9999 : actor.WeaponAmmo, true);
                        actor.WeaponHash = hash;
                    });
                };
            }

            {
                var listIndex = actor.WeaponAmmo == 0
                    ? StaticData.StaticLists.AmmoChoses.FindIndex(n => n == (dynamic)9999)
                    : StaticData.StaticLists.AmmoChoses.FindIndex(n => n == (dynamic)actor.WeaponAmmo);
                var item = new MenuListItem("Ammo Count", StaticData.StaticLists.AmmoChoses, listIndex);

                item.OnListChanged += (sender, index) =>
                {
                    int newAmmo = int.Parse(((MenuListItem)sender).IndexToItem(index).ToString(), CultureInfo.InvariantCulture);
                    actor.WeaponAmmo = newAmmo;
                    if (actor.WeaponHash == 0)
                    {
                        return;
                    }
                    NativeFunction.CallByName <uint>("REMOVE_ALL_PED_WEAPONS", actor.GetEntity().Handle.Value, true);
                    ((Ped)actor.GetEntity()).GiveNewWeapon(actor.WeaponHash, newAmmo, true);
                };

                AddItem(item);
            }
            #endregion

            #region Health
            {
                var listIndex = actor.Health == 0
                    ? StaticData.StaticLists.HealthArmorChoses.FindIndex(n => n == (dynamic)200)
                    : StaticData.StaticLists.HealthArmorChoses.FindIndex(n => n == (dynamic)actor.Health);
                var item = new MenuListItem("Health", StaticData.StaticLists.HealthArmorChoses, listIndex);

                item.OnListChanged += (sender, index) =>
                {
                    int newAmmo = int.Parse(((MenuListItem)sender).IndexToItem(index).ToString(), CultureInfo.InvariantCulture);
                    actor.Health = newAmmo;
                };

                AddItem(item);
            }
            #endregion

            #region Armor
            {
                var listIndex = StaticData.StaticLists.HealthArmorChoses.FindIndex(n => n == (dynamic)actor.Armor);
                var item      = new MenuListItem("Armor", StaticData.StaticLists.HealthArmorChoses, listIndex);

                item.OnListChanged += (sender, index) =>
                {
                    int newAmmo = int.Parse(((MenuListItem)sender).IndexToItem(index).ToString(), CultureInfo.InvariantCulture);
                    actor.Armor = newAmmo;
                };

                AddItem(item);
            }
            #endregion

            #region Accuracy
            {
                var listIndex = StaticData.StaticLists.AccuracyList.FindIndex(n => n == (dynamic)actor.Accuracy);
                var item      = new MenuListItem("Accuracy", StaticData.StaticLists.AccuracyList, listIndex);

                item.OnListChanged += (sender, index) =>
                {
                    int newAmmo = int.Parse(((MenuListItem)sender).IndexToItem(index).ToString(), CultureInfo.InvariantCulture);
                    actor.Accuracy = newAmmo;
                };

                AddItem(item);
            }
            #endregion

            #region Relationship
            {
                var item = new MenuListItem("Relationship", StaticData.StaticLists.RelationshipGroups, actor.RelationshipGroup);

                item.OnListChanged += (sender, index) =>
                {
                    actor.RelationshipGroup = index;
                };

                AddItem(item);
            }
            #endregion

            #region Behaviour
            {
                var wpyItem = new NativeMenuItem("Waypoints");

                {
                    var waypMenu = new WaypointEditor(actor);
                    BindMenuToItem(waypMenu.CreateWaypointMenu, wpyItem);

                    Vector3 camPos = new Vector3();
                    Rotator camRot = new Rotator();

                    wpyItem.Activated += (sender, selectedItem) =>
                    {
                        camPos = Editor.MainCamera.Position;
                        camRot = Editor.MainCamera.Rotation;

                        waypMenu.Enter();
                        Editor.WaypointEditor = waypMenu;
                    };

                    waypMenu.OnEditorExit += (sender, args) =>
                    {
                        Editor.WaypointEditor         = null;
                        Editor.DisableControlEnabling = true;
                        if (camPos != new Vector3())
                        {
                            Editor.MainCamera.Position = camPos;
                            Editor.MainCamera.Rotation = camRot;
                        }
                    };
                }

                if (actor.Behaviour != 4) // Follow Waypoints
                {
                    wpyItem.Enabled = false;
                }

                var item = new MenuListItem("Behaviour", StaticData.StaticLists.Behaviour, actor.Behaviour);

                item.OnListChanged += (sender, index) =>
                {
                    actor.Behaviour = index;
                    wpyItem.Enabled = index == 4;
                };

                AddItem(item);
                AddItem(wpyItem);
            }
            #endregion

            #region FailOnDeath
            {
                var item = new MenuCheckboxItem("Mission Fail On Death", actor.FailMissionOnDeath);
                item.CheckboxEvent += (sender, @checked) =>
                {
                    actor.FailMissionOnDeath = @checked;
                };
                AddItem(item);
            }
            #endregion

            RefreshIndex();
        }
Пример #23
0
        /// <summary>
        /// Creates all the submenus of main menu
        /// </summary>
        /// <returns></returns>
        private void CreateSubmenus()
        {
            // Create the menu.
            Menu = new Menu(_t("MAIN_MENU_TITLE"), _t("MAIN_MENU_DESC"));
            MenuController.AddMenu(Menu);

            #region checkbox items

            // Enabling angular drift cam
            leadCam = new MenuCheckboxItem(_t("MAIN_MENU_ENABLE_LEAD"), _t("MAIN_MENU_ENABLE_LEAD_DESC"), false);
            // Enabling chase cam
            chaseCam = new MenuCheckboxItem(_t("MAIN_MENU_ENABLE_CHASE"), _t("MAIN_MENU_ENABLE_CHASE"), false);
            // Enabling chase cam
            droneCam = new MenuCheckboxItem(_t("MAIN_MENU_ENABLE_DRONE"), _t("MAIN_MENU_ENABLE_DRONE"), false);

            #endregion

            #region adding menu items
            // Checkboxes
            Menu.AddMenuItem(leadCam);
            if (chaseCameraConfigEnabled)
            {
                Menu.AddMenuItem(chaseCam);
            }
            if (droneCameraConfigEnabled)
            {
                Menu.AddMenuItem(droneCam);
            }

            // Custom cam parameters menu
            CustomCamMenu = new CustomCam();
            Menu     customCamMenu = CustomCamMenu.GetMenu();
            MenuItem buttonCustom  = new MenuItem(_t("MAIN_MENU_LEAD_CHASE_CONF"), _t("MAIN_MENU_LEAD_CHASE_CONF_DESC"))
            {
                Label = "→→→"
            };
            AddMenu(Menu, customCamMenu, buttonCustom);

            // Drone cam parameters menu
            DroneCamMenu = new DroneCam();
            Menu     droneCamMenu = DroneCamMenu.GetMenu();
            MenuItem buttonDrone  = new MenuItem(_t("MAIN_MENU_DRONE_CONF"), _t("MAIN_MENU_DRONE_CONF_DESC"))
            {
                Label = "→→→"
            };

            if (droneCameraConfigEnabled)
            {
                AddMenu(Menu, droneCamMenu, buttonDrone);
            }

            // Credits
            MenuItem credits = new MenuItem(_t("MAIN_MENU_CREDITS"), _t("MAIN_MENU_CREDITS_DESC"))
            {
            };
            Menu.AddMenuItem(credits);

            #endregion

            #region handling menu changes

            // Handle checkbox changes
            Menu.OnCheckboxChange += (_menu, _item, _index, _checked) => {
                if (_item == leadCam)
                {
                    CustomCam.LeadCam    = _checked;
                    chaseCam.Checked     = false;
                    droneCam.Checked     = false;
                    CustomCam.ChaseCam   = false;
                    DroneCam.DroneCamVar = false;

                    if (!_checked)
                    {
                        ResetCameras();
                    }
                }
                if (_item == chaseCam)
                {
                    CustomCam.ChaseCam   = _checked;
                    leadCam.Checked      = false;
                    droneCam.Checked     = false;
                    CustomCam.LeadCam    = false;
                    DroneCam.DroneCamVar = false;

                    if (!_checked)
                    {
                        ResetCameras();
                    }
                    else
                    {
                        CustomCam.target = CustomCam.GetClosestVehicle(2000, CustomCam.maxAngle);
                    }
                }
                if (_item == droneCam)
                {
                    DroneCam.DroneCamVar = _checked;
                    chaseCam.Checked     = false;
                    leadCam.Checked      = false;
                    CustomCam.ChaseCam   = false;
                    CustomCam.LeadCam    = false;

                    if (!_checked)
                    {
                        ResetCameras();
                    }
                }
            };
            #endregion
        }
Пример #24
0
        private void CreateMenu()
        {
            #region initial setup.
            // Create the menu.
            menu = new Menu("YDDY:RP", "Меню спавна автомобилей");

            // Create the buttons and checkboxes.
            MenuItem         spawnByName = new MenuItem("Заспавнить по имени", "");
            MenuCheckboxItem spawnInVeh  = new MenuCheckboxItem("Спавниться в автомобиле", "", SpawnInVehicle);
            MenuCheckboxItem replacePrev = new MenuCheckboxItem("Заменять предыдущий", "", ReplaceVehicle);

            // Add the items to the menu.
            if (IsAllowed(Permission.VSSpawnByName))
            {
                menu.AddMenuItem(spawnByName);
            }
            menu.AddMenuItem(spawnInVeh);
            menu.AddMenuItem(replacePrev);
            #endregion

            #region addon cars menu
            // Vehicle Addons List
            Menu     addonCarsMenu = new Menu("Аддоны", "Заспавнить");
            MenuItem addonCarsBtn  = new MenuItem("Аддоны", "")
            {
                Label = "→→→"
            };

            menu.AddMenuItem(addonCarsBtn);

            if (IsAllowed(Permission.VSAddon))
            {
                if (AddonVehicles != null)
                {
                    if (AddonVehicles.Count > 0)
                    {
                        MenuController.BindMenuItem(menu, addonCarsMenu, addonCarsBtn);
                        MenuController.AddSubmenu(menu, addonCarsMenu);
                        Menu     unavailableCars    = new Menu("Меню спавна аддонов", "Недоступные автомобили");
                        MenuItem unavailableCarsBtn = new MenuItem("Недоступные автомобили", "На данный момент эти автомобили недоступны на YDDY.")
                        {
                            Label = "→→→"
                        };
                        MenuController.AddSubmenu(addonCarsMenu, unavailableCars);

                        for (var cat = 0; cat < 22; cat++)
                        {
                            Menu     categoryMenu = new Menu(GetLocalizedName($"VEH_CLASS_{cat}"), "Заспавнить");
                            MenuItem categoryBtn  = new MenuItem(GetLocalizedName($"VEH_CLASS_{cat}"), $"Заспавнить автомобиль из класса {GetLocalizedName($"VEH_CLASS_{cat}")}.")
                            {
                                Label = "→→→"
                            };

                            addonCarsMenu.AddMenuItem(categoryBtn);

                            if (!allowedCategories[cat])
                            {
                                categoryBtn.Description = "Этот класс отключен на сервере.";
                                categoryBtn.Enabled     = false;
                                categoryBtn.LeftIcon    = MenuItem.Icon.LOCK;
                                categoryBtn.Label       = "";
                                continue;
                            }

                            // Loop through all addon vehicles in this class.
                            foreach (KeyValuePair <string, uint> veh in AddonVehicles.Where(v => GetVehicleClassFromName(v.Value) == cat))
                            {
                                string localizedName = GetLabelText(GetDisplayNameFromVehicleModel(veh.Value));

                                string name = localizedName != "NULL" ? localizedName : GetDisplayNameFromVehicleModel(veh.Value);
                                name = name != "CARNOTFOUND" ? name : veh.Key;

                                MenuItem carBtn = new MenuItem(name, $"Нажмите, чтобы заспавнить {name}.")
                                {
                                    Label    = $"({veh.Key.ToString()})",
                                    ItemData = veh.Key // store the model name in the button data.
                                };

                                // This should be impossible to be false, but we check it anyway.
                                if (IsModelInCdimage(veh.Value))
                                {
                                    categoryMenu.AddMenuItem(carBtn);
                                }
                                else
                                {
                                    carBtn.Enabled     = false;
                                    carBtn.Description = "Этот автомобиль недоступен.";
                                    carBtn.LeftIcon    = MenuItem.Icon.LOCK;
                                    unavailableCars.AddMenuItem(carBtn);
                                }
                            }

                            //if (AddonVehicles.Count(av => GetVehicleClassFromName(av.Value) == cat && IsModelInCdimage(av.Value)) > 0)
                            if (categoryMenu.Size > 0)
                            {
                                MenuController.AddSubmenu(addonCarsMenu, categoryMenu);
                                MenuController.BindMenuItem(addonCarsMenu, categoryMenu, categoryBtn);

                                categoryMenu.OnItemSelect += (sender, item, index) =>
                                {
                                    SpawnVehicle(item.ItemData.ToString(), SpawnInVehicle, ReplaceVehicle);
                                };
                            }
                            else
                            {
                                categoryBtn.Description = "В этой категории нет автомобилей.";
                                categoryBtn.Enabled     = false;
                                categoryBtn.LeftIcon    = MenuItem.Icon.LOCK;
                                categoryBtn.Label       = "";
                            }
                        }

                        if (unavailableCars.Size > 0)
                        {
                            addonCarsMenu.AddMenuItem(unavailableCarsBtn);
                            MenuController.BindMenuItem(addonCarsMenu, unavailableCars, unavailableCarsBtn);
                        }

                        //addonCarsMenu.OnItemSelect += (sender, item, index) =>
                        //{

                        //    //SpawnVehicle(AddonVehicles.ElementAt(index).Key, SpawnInVehicle, ReplaceVehicle);
                        //};
                    }
                    else
                    {
                        addonCarsBtn.Enabled     = false;
                        addonCarsBtn.LeftIcon    = MenuItem.Icon.LOCK;
                        addonCarsBtn.Description = "На сервере нет аддонов.";
                    }
                }
                else
                {
                    addonCarsBtn.Enabled     = false;
                    addonCarsBtn.LeftIcon    = MenuItem.Icon.LOCK;
                    addonCarsBtn.Description = "The list containing all addon cars could not be loaded, is it configured properly?";
                }
            }
            else
            {
                addonCarsBtn.Enabled     = false;
                addonCarsBtn.LeftIcon    = MenuItem.Icon.LOCK;
                addonCarsBtn.Description = "Access to this list has been restricted by the server owner.";
            }
            #endregion

            #region vehicle classes submenus
            // Loop through all the vehicle classes.
            for (var vehClass = 0; vehClass < 22; vehClass++)
            {
                // Get the class name.
                string className = GetLocalizedName($"VEH_CLASS_{vehClass.ToString()}");

                // Create a button & a menu for it, add the menu to the menu pool and add & bind the button to the menu.
                MenuItem btn = new MenuItem(className, $"Заспавнить автомобиль из класса ~o~{className} ~s~.")
                {
                    Label = "→→→"
                };

                Menu vehicleClassMenu = new Menu(className, "Заспавнить");

                MenuController.AddSubmenu(menu, vehicleClassMenu);
                menu.AddMenuItem(btn);

                if (allowedCategories[vehClass])
                {
                    MenuController.BindMenuItem(menu, vehicleClassMenu, btn);
                }
                else
                {
                    btn.LeftIcon    = MenuItem.Icon.LOCK;
                    btn.Description = "This category has been disabled by the server owner.";
                    btn.Enabled     = false;
                }

                // Create a dictionary for the duplicate vehicle names (in this vehicle class).
                var duplicateVehNames = new Dictionary <string, int>();

                #region Add vehicles per class
                // Loop through all the vehicles in the vehicle class.
                foreach (var veh in VehicleData.Vehicles.VehicleClasses[className])
                {
                    // Convert the model name to start with a Capital letter, converting the other characters to lowercase.
                    var properCasedModelName = veh[0].ToString().ToUpper() + veh.ToLower().Substring(1);

                    // Get the localized vehicle name, if it's "NULL" (no label found) then use the "properCasedModelName" created above.
                    var vehName = GetVehDisplayNameFromModel(veh) != "NULL" ? GetVehDisplayNameFromModel(veh) : properCasedModelName;

                    // Loop through all the menu items and check each item's title/text and see if it matches the current vehicle (display) name.
                    var duplicate = false;
                    for (var itemIndex = 0; itemIndex < vehicleClassMenu.Size; itemIndex++)
                    {
                        // If it matches...
                        if (vehicleClassMenu.GetMenuItems()[itemIndex].Text.ToString() == vehName)
                        {
                            // Check if the model was marked as duplicate before.
                            if (duplicateVehNames.Keys.Contains(vehName))
                            {
                                // If so, add 1 to the duplicate counter for this model name.
                                duplicateVehNames[vehName]++;
                            }

                            // If this is the first duplicate, then set it to 2.
                            else
                            {
                                duplicateVehNames[vehName] = 2;
                            }

                            // The model name is a duplicate, so get the modelname and add the duplicate amount for this model name to the end of the vehicle name.
                            vehName += $" ({duplicateVehNames[vehName].ToString()})";

                            // Then create and add a new button for this vehicle.

                            if (DoesModelExist(veh))
                            {
                                var vehBtn = new MenuItem(vehName)
                                {
                                    Enabled = true
                                };
                                vehicleClassMenu.AddMenuItem(vehBtn);
                            }
                            else
                            {
                                var vehBtn = new MenuItem(vehName, "This vehicle is not available because the model could not be found in your game files. If this is a DLC vehicle, make sure the server is streaming it.")
                                {
                                    Enabled = false
                                };
                                vehicleClassMenu.AddMenuItem(vehBtn);
                                vehBtn.RightIcon = MenuItem.Icon.LOCK;
                            }

                            // Mark duplicate as true and break from the loop because we already found the duplicate.
                            duplicate = true;
                            break;
                        }
                    }

                    // If it's not a duplicate, add the model name.
                    if (!duplicate)
                    {
                        if (DoesModelExist(veh))
                        {
                            var vehBtn = new MenuItem(vehName)
                            {
                                Enabled = true
                            };
                            vehicleClassMenu.AddMenuItem(vehBtn);
                        }
                        else
                        {
                            var vehBtn = new MenuItem(vehName, "This vehicle is not available because the model could not be found in your game files. If this is a DLC vehicle, make sure the server is streaming it.")
                            {
                                Enabled = false
                            };
                            vehicleClassMenu.AddMenuItem(vehBtn);
                            vehBtn.RightIcon = MenuItem.Icon.LOCK;
                        }
                    }
                }
                #endregion

                // Handle button presses
                vehicleClassMenu.OnItemSelect += (sender2, item2, index2) =>
                {
                    SpawnVehicle(VehicleData.Vehicles.VehicleClasses[className][index2], SpawnInVehicle, ReplaceVehicle);
                };
            }
            #endregion

            #region handle events
            // Handle button presses.
            menu.OnItemSelect += (sender, item, index) =>
            {
                if (item == spawnByName)
                {
                    // Passing "custom" as the vehicle name, will ask the user for input.
                    SpawnVehicle("custom", SpawnInVehicle, ReplaceVehicle);
                }
            };

            // Handle checkbox changes.
            menu.OnCheckboxChange += (sender, item, index, _checked) =>
            {
                if (item == spawnInVeh)
                {
                    SpawnInVehicle = _checked;
                }
                else if (item == replacePrev)
                {
                    ReplaceVehicle = _checked;
                }
            };
            #endregion
        }
Пример #25
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();
        }
Пример #26
0
        private static void SetupMenu()
        {
            if (setupDone)
            {
                return;
            }
            setupDone = true;

            MenuCheckboxItem minimapKeybind = new MenuCheckboxItem("Minimap Controls", "Holding down the Select Radar Option button will allow you to toggle the minimap on/off when this option is enabled.", UserDefaults.MiscMinimapControls);
            MenuCheckboxItem showCores      = new MenuCheckboxItem("Always Show Cores", "The cores above your radar will always be displayed when this option is enabled. The game will automatically show or hide the cores if this is disabled.", UserDefaults.MiscAlwaysShowCores);
            MenuItem         clearArea      = new MenuItem("Clear Area", "Clears the area around your player.");

            menu.AddMenuItem(minimapKeybind);
            menu.AddMenuItem(showCores);

            if (PermissionsManager.IsAllowed(Permission.MSClearArea))
            {
                menu.AddMenuItem(clearArea);
            }

            menu.OnItemSelect += (m, item, index) =>
            {
                if (item == clearArea)
                {
                    int     ent = 0;
                    int     handle;
                    Vector3 coords1 = GetEntityCoords(PlayerPedId(), true, true);
                    Vector3 coords2;

                    handle  = FindFirstObject(ref ent);
                    coords2 = GetEntityCoords(ent, true, true);
                    if (GetDistanceBetweenCoords(coords1.X, coords1.Y, coords1.Z, coords2.X, coords2.Y, coords2.Z, true) <= 100)
                    {
                        DeleteObject(ref ent);
                    }
                    while (FindNextObject(handle, ref ent))
                    {
                        coords2 = GetEntityCoords(ent, true, true);
                        if (GetDistanceBetweenCoords(coords1.X, coords1.Y, coords1.Z, coords2.X, coords2.Y, coords2.Z, true) <= 100)
                        {
                            DeleteObject(ref ent);
                        }
                    }
                    EndFindObject(handle);

                    handle = FindFirstPed(ref ent);
                    if (!IsPedAPlayer(ent))
                    {
                        coords2 = GetEntityCoords(ent, true, true);

                        if (GetDistanceBetweenCoords(coords1.X, coords1.Y, coords1.Z, coords2.X, coords2.Y, coords2.Z, true) <= 100)
                        {
                            DeletePed(ref ent);
                        }
                    }
                    while (FindNextPed(handle, ref ent))
                    {
                        if (!IsPedAPlayer(ent))
                        {
                            coords2 = GetEntityCoords(ent, true, true);
                            if (GetDistanceBetweenCoords(coords1.X, coords1.Y, coords1.Z, coords2.X, coords2.Y, coords2.Z, true) <= 100)
                            {
                                DeletePed(ref ent);
                            }
                        }
                    }
                    EndFindPed(handle);

                    handle  = FindFirstVehicle(ref ent);
                    coords2 = GetEntityCoords(ent, true, true);
                    if (GetDistanceBetweenCoords(coords1.X, coords1.Y, coords1.Z, coords2.X, coords2.Y, coords2.Z, true) <= 100)
                    {
                        DeleteVehicle(ref ent);
                    }
                    while (FindNextVehicle(handle, ref ent))
                    {
                        coords2 = GetEntityCoords(ent, true, true);
                        if (GetDistanceBetweenCoords(coords1.X, coords1.Y, coords1.Z, coords2.X, coords2.Y, coords2.Z, true) <= 100)
                        {
                            DeleteVehicle(ref ent);
                        }
                    }
                    EndFindVehicle(handle);
                }
            };

            menu.OnCheckboxChange += (m, item, index, _checked) =>
            {
                if (item == minimapKeybind)
                {
                    UserDefaults.MiscMinimapControls = _checked;
                }
                else if (item == showCores)
                {
                    UserDefaults.MiscAlwaysShowCores = _checked;
                    Function.Call((Hash)0xD4EE21B7CC7FD350, UserDefaults.MiscAlwaysShowCores); // _ALWAYS_SHOW_HORSE_CORES
                    Function.Call((Hash)0x50C803A4CD5932C5, UserDefaults.MiscAlwaysShowCores); // _ALWAYS_SHOW_PLAYER_CORES
                }
            };
        }
Пример #27
0
        public F5Menu()
        {
            menu        = new Menu(TEAMHOOFDWEGENRP, GIERIGENARROGANT);
            disciplines = new List <string>()
            {
                "Politie", "Marechaussee", "Brandweer", "Ambulance"
            };
            inmelden           = new MenuListItem("Inmelden", disciplines, 0);
            discord            = new MenuItem("Discord", "Link naar de TeamHoofdwegenRP Discord.");
            calloutsMenuButton = new MenuItem("Meldingen", "Hier kunnen meldingen worden gegenereerd.")
            {
                Label = "→→→"
            };
            voertuigenMenuButton = new MenuItem("Voertuigen", "Hier kan je een voertuig inspawnen.")
            {
                Label = "→→→"
            };
            noodknop = new MenuItem("",
                                    "Alleen gebruiken in geval van nood, stuurt een signaal naar alle collega's!")
            {
                LeftIcon = MenuItem.Icon.WARNING, Label = "~r~Noodknop"
            };
            beschikbaarBool = false;
            beschikbaar     = new MenuCheckboxItem("Beschikbaar", "Vink dit aan als je beschikbaar bent voor meldingen.", beschikbaarBool);

            calloutsMenu   = new Menu("Meldingen", GIERIGENARROGANT);
            startVTB       = new MenuItem("VTB");
            startAutobrand = new MenuItem("Autobrand");

            voertuigenMenu = new Menu("Voertuigen", GIERIGENARROGANT);
            vehicleModels  = new ArrayList();
            vehicles       = new ArrayList();
            LoadConfig();

            spoedBackupMenu     = new Menu("P1 Assistentie", "Assistentie met spoed ");
            spoedBackupMenuItem = new MenuItem("P1 Assistentie", "Hier kun je assistentie met spoed aanvragen.");
            spoedPol            = new MenuItem("P1 Politie");
            spoedKmar           = new MenuItem("P1 Marechaussee");
            spoedBrw            = new MenuItem("P1 Brandweer");
            spoedAmbu           = new MenuItem("P1 Ambulance");

            backupMenu     = new Menu("P2 Assistentie", "Assistentie zonder spoed ");
            backupMenuItem = new MenuItem("P2 Assistentie", "Hier kun je assistentie zonder spoed aanvragen.");
            regPol         = new MenuItem("P2 Politie");
            regKmar        = new MenuItem("P2 Marechaussee");
            regBrw         = new MenuItem("P2 Brandweer");
            regAmbu        = new MenuItem("P2 Ambulance");

            MenuController.MenuToggleKey = Control.SelectCharacterMichael;
            MenuController.AddMenu(menu);
            MenuController.AddSubmenu(menu, calloutsMenu);
            MenuController.AddSubmenu(menu, voertuigenMenu);
            MenuController.AddSubmenu(menu, backupMenu);
            MenuController.AddSubmenu(menu, spoedBackupMenu);
            spoedBackupMenu.AddMenuItem(spoedPol);
            spoedBackupMenu.AddMenuItem(spoedKmar);
            spoedBackupMenu.AddMenuItem(spoedBrw);
            spoedBackupMenu.AddMenuItem(spoedAmbu);

            backupMenu.AddMenuItem(regPol);
            backupMenu.AddMenuItem(regKmar);
            backupMenu.AddMenuItem(regBrw);
            backupMenu.AddMenuItem(regAmbu);

            menu.AddMenuItem(inmelden);
            menu.AddMenuItem(discord);

            calloutsMenu.AddMenuItem(startVTB);
            calloutsMenu.AddMenuItem(startAutobrand);

            foreach (MenuItem car in vehicles)
            {
                voertuigenMenu.AddMenuItem(car);
            }

            menu.OnItemSelect            += (menu, item, index) => ItemSelected(menu, item, index);
            calloutsMenu.OnItemSelect    += (menu, item, index) => ItemSelected(menu, item, index);
            voertuigenMenu.OnItemSelect  += (menu, item, index) => ItemSelected(menu, item, index);
            backupMenu.OnItemSelect      += (menu, item, index) => ItemSelected(menu, item, index);
            spoedBackupMenu.OnItemSelect += (menu, item, index) => ItemSelected(menu, item, index);
            menu.OnListItemSelect        += (menu, listItem, listIndex, itemIndex) =>
                                            ItemSelected(menu, listItem, listIndex, itemIndex);
            menu.OnCheckboxChange += (menu, item, index, _checked) => checkboxChanged(menu, item, index, _checked);

            MenuController.MenuAlignment = MenuController.MenuAlignmentOption.Right;
        }
Пример #28
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
        }
Пример #29
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();
                }
            };
        }
Пример #30
0
        public void BuildFor(SerializableData.Objectives.SerializablePickupObjective actor)
        {
            Clear();

            #region SpawnAfter
            {
                var item = new MenuListItem("Spawn After Objective", StaticData.StaticLists.NumberMenu, actor.SpawnAfter);

                item.OnListChanged += (sender, index) =>
                {
                    actor.SpawnAfter = index;
                };

                AddItem(item);
            }
            #endregion

            #region ObjectiveIndex
            {
                var item = new MenuListItem("Objective Index", StaticData.StaticLists.ObjectiveIndexList, actor.ActivateAfter);

                item.OnListChanged += (sender, index) =>
                {
                    actor.ActivateAfter = index;


                    if (string.IsNullOrEmpty(Editor.CurrentMission.ObjectiveNames[actor.ActivateAfter]))
                    {
                        MenuItems[2].SetRightBadge(NativeMenuItem.BadgeStyle.Alert);
                        MenuItems[2].SetRightLabel("");
                    }
                    else
                    {
                        var title = Editor.CurrentMission.ObjectiveNames[actor.ActivateAfter];
                        MenuItems[2].SetRightLabel(title.Length > 20 ? title.Substring(0, 20) + "..." : title);
                        MenuItems[2].SetRightBadge(NativeMenuItem.BadgeStyle.None);
                    }
                };

                AddItem(item);
            }
            #endregion
            // TODO: Change NumberMenu to max num of objectives in mission

            // Note: if adding items before weapons, change item order in VehiclePropertiesMenu

            #region Objective Name
            {
                var item = new NativeMenuItem("Objective Name");
                if (string.IsNullOrEmpty(Editor.CurrentMission.ObjectiveNames[actor.ActivateAfter]))
                {
                    item.SetRightBadge(NativeMenuItem.BadgeStyle.Alert);
                }
                else
                {
                    var title = Editor.CurrentMission.ObjectiveNames[actor.ActivateAfter];
                    item.SetRightLabel(title.Length > 20 ? title.Substring(0, 20) + "..." : title);
                }

                item.Activated += (sender, selectedItem) =>
                {
                    GameFiber.StartNew(delegate
                    {
                        ResetKey(Common.MenuControls.Back);
                        Editor.DisableControlEnabling = true;
                        string title = Util.GetUserInput();
                        if (string.IsNullOrEmpty(title))
                        {
                            item.SetRightBadge(NativeMenuItem.BadgeStyle.Alert);
                            Editor.CurrentMission.ObjectiveNames[actor.ActivateAfter] = "";
                            SetKey(Common.MenuControls.Back, GameControl.CellphoneCancel, 0);
                            Editor.DisableControlEnabling = false;
                            return;
                        }
                        item.SetRightBadge(NativeMenuItem.BadgeStyle.None);
                        title = Regex.Replace(title, "-=", "~");
                        Editor.CurrentMission.ObjectiveNames[actor.ActivateAfter] = title;
                        selectedItem.SetRightLabel(title.Length > 20 ? title.Substring(0, 20) + "..." : title);
                        SetKey(Common.MenuControls.Back, GameControl.CellphoneCancel, 0);
                    });
                };
                AddItem(item);
            }
            #endregion

            #region Weapons
            {
                var listIndex = actor.Ammo == 0
                    ? StaticData.StaticLists.AmmoChoses.FindIndex(n => n == (dynamic)9999)
                    : StaticData.StaticLists.AmmoChoses.FindIndex(n => n == (dynamic)actor.Ammo);
                var item = new MenuListItem("Ammo Count", StaticData.StaticLists.AmmoChoses, listIndex);

                item.OnListChanged += (sender, index) =>
                {
                    int newAmmo = int.Parse(((MenuListItem)sender).IndexToItem(index).ToString(), CultureInfo.InvariantCulture);
                    actor.Ammo = newAmmo;
                };

                AddItem(item);
            }
            #endregion

            #region Respawn
            {
                var item = new MenuCheckboxItem("Respawn", actor.Respawn);
                item.CheckboxEvent += (sender, @checked) =>
                {
                    actor.Respawn = @checked;
                };
                AddItem(item);
            }
            #endregion

            RefreshIndex();
        }