@aifivem/lib 0.0.0-stage → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (162) hide show
  1. package/package.json +34 -4
  2. package/src/client/action.ts +38 -0
  3. package/src/client/adminWorld.ts +95 -0
  4. package/src/client/appearance.ts +29 -0
  5. package/src/client/areaFollower.ts +41 -0
  6. package/src/client/blip.ts +79 -0
  7. package/src/client/cache.ts +66 -0
  8. package/src/client/callback.ts +70 -0
  9. package/src/client/controls.ts +73 -0
  10. package/src/client/entities.ts +83 -0
  11. package/src/client/entity.ts +26 -0
  12. package/src/client/fuel.ts +18 -0
  13. package/src/client/gestures.ts +18 -0
  14. package/src/client/headshot.ts +26 -0
  15. package/src/client/hud.ts +24 -0
  16. package/src/client/index.ts +131 -0
  17. package/src/client/inventory.ts +117 -0
  18. package/src/client/keyHints.ts +13 -0
  19. package/src/client/keybind.ts +163 -0
  20. package/src/client/localPed.ts +169 -0
  21. package/src/client/location.ts +54 -0
  22. package/src/client/mdt.ts +10 -0
  23. package/src/client/medical.ts +28 -0
  24. package/src/client/membership.ts +41 -0
  25. package/src/client/menu/dialogs.ts +77 -0
  26. package/src/client/menu/minigames.ts +79 -0
  27. package/src/client/menu/requests.ts +65 -0
  28. package/src/client/modelScan/def.ts +29 -0
  29. package/src/client/modelScan/objectIndex.ts +41 -0
  30. package/src/client/modelScan/scan.ts +69 -0
  31. package/src/client/modelScan/scanner.ts +164 -0
  32. package/src/client/netEvent.ts +40 -0
  33. package/src/client/notify.ts +14 -0
  34. package/src/client/nuiScreen.ts +87 -0
  35. package/src/client/player/anim.ts +98 -0
  36. package/src/client/player/fade.ts +17 -0
  37. package/src/client/player/player.ts +80 -0
  38. package/src/client/player/teleport.ts +87 -0
  39. package/src/client/playerData.ts +83 -0
  40. package/src/client/players.ts +44 -0
  41. package/src/client/points/interact.ts +144 -0
  42. package/src/client/points/modelHost.ts +117 -0
  43. package/src/client/points/modelPoint.ts +181 -0
  44. package/src/client/points/point.ts +159 -0
  45. package/src/client/points/points.ts +170 -0
  46. package/src/client/points/targets/adapter.ts +40 -0
  47. package/src/client/points/targets/interactTarget.ts +45 -0
  48. package/src/client/points/targets/optionShape.ts +22 -0
  49. package/src/client/points/targets/oxTarget.ts +42 -0
  50. package/src/client/points/targets/qbTarget.ts +71 -0
  51. package/src/client/points/targets/targets.ts +20 -0
  52. package/src/client/preview.ts +51 -0
  53. package/src/client/progress.ts +132 -0
  54. package/src/client/prompt.ts +26 -0
  55. package/src/client/prop.ts +79 -0
  56. package/src/client/radial.ts +16 -0
  57. package/src/client/raycast.ts +48 -0
  58. package/src/client/scriptCamera.ts +167 -0
  59. package/src/client/seatbelt.ts +18 -0
  60. package/src/client/shot.ts +29 -0
  61. package/src/client/streaming.ts +91 -0
  62. package/src/client/tickLoop.ts +18 -0
  63. package/src/client/vehicleKeys.ts +14 -0
  64. package/src/client/vehicleProps.ts +107 -0
  65. package/src/client/vehicles.ts +46 -0
  66. package/src/client/waypoint.ts +10 -0
  67. package/src/client/world.ts +10 -0
  68. package/src/client/zoneEngine.ts +174 -0
  69. package/src/client/zones.ts +161 -0
  70. package/src/fivem/byResource.ts +146 -0
  71. package/src/fivem/callbackNames.ts +12 -0
  72. package/src/fivem/exports.ts +70 -0
  73. package/src/fivem/index.ts +13 -0
  74. package/src/fivem/locale.ts +57 -0
  75. package/src/fivem/playerData.ts +13 -0
  76. package/src/fivem/scheduler/every.ts +101 -0
  77. package/src/fivem/scheduler/group.ts +97 -0
  78. package/src/fivem/scheduler/scheduler.ts +77 -0
  79. package/src/fivem/state/entityState.ts +75 -0
  80. package/src/fivem/state/globalState.ts +80 -0
  81. package/src/fivem/state/mirror.ts +47 -0
  82. package/src/fivem/state/playerState.ts +60 -0
  83. package/src/server/admin/descriptions.ts +57 -0
  84. package/src/server/admin/edit.ts +127 -0
  85. package/src/server/admin/jsonSchema.ts +156 -0
  86. package/src/server/admin/panel.ts +167 -0
  87. package/src/server/admin/panelFiles.ts +128 -0
  88. package/src/server/admin/patch.ts +46 -0
  89. package/src/server/admin/validate.ts +147 -0
  90. package/src/server/appearance.ts +28 -0
  91. package/src/server/areaStream/areaStream.ts +141 -0
  92. package/src/server/areaStream/followers.ts +154 -0
  93. package/src/server/areaStream/grid.ts +74 -0
  94. package/src/server/areaStream/options.ts +16 -0
  95. package/src/server/banking.ts +15 -0
  96. package/src/server/bans.ts +47 -0
  97. package/src/server/billing.ts +20 -0
  98. package/src/server/buckets.ts +12 -0
  99. package/src/server/callback.ts +112 -0
  100. package/src/server/characters.ts +129 -0
  101. package/src/server/command/addCommand.ts +83 -0
  102. package/src/server/command/command.ts +116 -0
  103. package/src/server/command/commandSet.ts +74 -0
  104. package/src/server/dataFile.ts +81 -0
  105. package/src/server/database.ts +117 -0
  106. package/src/server/definitions.ts +65 -0
  107. package/src/server/dispatch.ts +13 -0
  108. package/src/server/doors.ts +15 -0
  109. package/src/server/ems.ts +15 -0
  110. package/src/server/fuel.ts +15 -0
  111. package/src/server/garages.ts +34 -0
  112. package/src/server/gate.ts +148 -0
  113. package/src/server/index.ts +165 -0
  114. package/src/server/inventory.ts +106 -0
  115. package/src/server/jobs.ts +42 -0
  116. package/src/server/log.ts +21 -0
  117. package/src/server/mdt.ts +12 -0
  118. package/src/server/medical.ts +16 -0
  119. package/src/server/minigameFor.ts +65 -0
  120. package/src/server/money.ts +70 -0
  121. package/src/server/netEntity.ts +19 -0
  122. package/src/server/netEvent.ts +58 -0
  123. package/src/server/notify.ts +17 -0
  124. package/src/server/online/mirror.ts +176 -0
  125. package/src/server/online/online.ts +190 -0
  126. package/src/server/pending.ts +70 -0
  127. package/src/server/phone.ts +22 -0
  128. package/src/server/players.ts +197 -0
  129. package/src/server/position.ts +31 -0
  130. package/src/server/primeTime.ts +7 -0
  131. package/src/server/prison.ts +15 -0
  132. package/src/server/progressFor.ts +62 -0
  133. package/src/server/proximity.ts +98 -0
  134. package/src/server/rateLimit.ts +53 -0
  135. package/src/server/state.ts +45 -0
  136. package/src/server/stress.ts +25 -0
  137. package/src/server/vehicle/nearby.ts +66 -0
  138. package/src/server/vehicle/plate.ts +14 -0
  139. package/src/server/vehicle/spawn.ts +125 -0
  140. package/src/server/vehicle/vehicleType.ts +50 -0
  141. package/src/server/vehicleKeys.ts +23 -0
  142. package/src/server/watchers.ts +46 -0
  143. package/src/server/world.ts +16 -0
  144. package/src/shared/access.ts +94 -0
  145. package/src/shared/action.ts +28 -0
  146. package/src/shared/blipStyle.ts +26 -0
  147. package/src/shared/clock.ts +22 -0
  148. package/src/shared/format.ts +36 -0
  149. package/src/shared/grid.ts +20 -0
  150. package/src/shared/index.ts +179 -0
  151. package/src/shared/lang.ts +39 -0
  152. package/src/shared/placePed.ts +96 -0
  153. package/src/shared/random.ts +11 -0
  154. package/src/shared/read.ts +60 -0
  155. package/src/shared/records.ts +148 -0
  156. package/src/shared/spec.ts +20 -0
  157. package/src/shared/strict.ts +70 -0
  158. package/src/shared/vec.ts +48 -0
  159. package/src/shared/vehicleProps.ts +138 -0
  160. package/src/shared/wait.ts +27 -0
  161. package/src/shared/zone.ts +144 -0
  162. package/README.md +0 -3
@@ -0,0 +1,18 @@
1
+ import { CORE } from "@aifivem/shared";
2
+ import { resourceExport } from "../fivem/exports";
3
+
4
+ const core = resourceExport(CORE.resource);
5
+
6
+ /** Hands up, pointing and emotes of whatever emote script runs, through ai-core (tgiann-emotes, rpemotes). */
7
+ export const gestures = {
8
+ isHandsUp: (): boolean => core.IsHandsUp(),
9
+ isPointing: (): boolean => core.IsPointing(),
10
+ /** The emote script answering (its resource name), or null when none runs. */
11
+ provider: (): string | null => core.GetGestureProvider(),
12
+ /** Plays an emote by its command name (`e <name>`) in the running emote script; false without one. */
13
+ playEmote: (name: string): boolean => core.PlayEmote(name),
14
+ /** Stops the emote the player plays (cuffed, knocked down); false without an emote script. */
15
+ cancelEmote: (): boolean => core.CancelEmote(),
16
+ /** The emote script that plays emotes, or null when none runs. */
17
+ emoteProvider: (): string | null => core.GetEmoteProvider(),
18
+ };
@@ -0,0 +1,26 @@
1
+ import { waitFor } from "../shared";
2
+
3
+ /**
4
+ * Registers a headshot of a ped and resolves once the game rendered it: the handle and its texture name (a
5
+ * `https://nui-img/<txd>/<txd>` picture), or null after `timeoutMs`. Call `UnregisterPedheadshot(handle)` when it is
6
+ * no longer shown.
7
+ */
8
+ export async function pedHeadshot(
9
+ ped: number,
10
+ transparent = false,
11
+ timeoutMs = 5000,
12
+ ): Promise<{ handle: number; txd: string } | null> {
13
+ if (!DoesEntityExist(ped)) return null;
14
+ const handle = transparent
15
+ ? RegisterPedheadshotTransparent(ped)
16
+ : RegisterPedheadshot(ped);
17
+ const ready = await waitFor(
18
+ () => (IsPedheadshotReady(handle) && IsPedheadshotValid(handle)) || undefined,
19
+ timeoutMs,
20
+ ).catch(() => false);
21
+ if (!ready) {
22
+ UnregisterPedheadshot(handle);
23
+ return null;
24
+ }
25
+ return { handle, txd: GetPedheadshotTxdString(handle) };
26
+ }
@@ -0,0 +1,24 @@
1
+ import { CORE } from "@aifivem/shared";
2
+ import { resourceExport } from "../fivem/exports";
3
+
4
+ const core = resourceExport(CORE.resource);
5
+
6
+ /**
7
+ * HUDs (ai-hud, tgiann-lumihud...) through ai-core: a full-screen UI hides them on open and shows them on close.
8
+ * Reasons are per resource and counted, so two screens open at once keep the HUD hidden until both close.
9
+ */
10
+ export const hud = {
11
+ hide: (reason: string): void => core.HideHud(reason),
12
+ show: (reason: string): void => core.ShowHud(reason),
13
+ /** Whether HUDs show now (no full-screen UI open). */
14
+ get visible(): boolean {
15
+ return core.IsHudVisible();
16
+ },
17
+ /** Runs `fn(visible)` when HUDs show or hide (for a HUD resource). */
18
+ onChange(fn: (visible: boolean) => void): void {
19
+ on(
20
+ CORE.clientHudVisibleEvent,
21
+ (visible: unknown) => typeof visible === "boolean" && fn(visible),
22
+ );
23
+ },
24
+ };
@@ -0,0 +1,131 @@
1
+ /** Client-only helpers. Import from "@aifivem/lib/client". */
2
+
3
+ export { TickLoop } from "./tickLoop";
4
+ export { AreaFollower } from "./areaFollower";
5
+ export { ScriptCamera } from "./scriptCamera";
6
+ export { medical } from "./medical";
7
+ export { fuel } from "./fuel";
8
+ export { mdt } from "./mdt";
9
+ export {
10
+ NuiScreen,
11
+ type NuiPageMessage,
12
+ type NuiScreenOptions,
13
+ } from "./nuiScreen";
14
+ export { every, type EveryOptions, type Job } from "../fivem/scheduler/every";
15
+ export {
16
+ ByResource,
17
+ caller,
18
+ onStop,
19
+ plateOf,
20
+ Reasons,
21
+ } from "../fivem/byResource";
22
+ export { onServerCallback, triggerServerCallback } from "./callback";
23
+ export { fromServer, onServerEvent } from "./netEvent";
24
+ export { AdminWorld } from "./adminWorld";
25
+ export { Zones, type ZoneOptions, type ZoneShape } from "./zones";
26
+ export { ZoneEngine } from "./zoneEngine";
27
+ export { ModelScanner } from "./modelScan/scanner";
28
+ export { readModelScanDef, type ModelScanDef } from "./modelScan/def";
29
+ export { cache, onCache, readPlayerState, readWeapon } from "./cache";
30
+ export { hidePrompt, onPromptPressed, showPrompt } from "./prompt";
31
+ export { Points } from "./points/points";
32
+ export type { PointOptions } from "./points/point";
33
+ export type {
34
+ ModelPointOptions,
35
+ VehiclePointOptions,
36
+ } from "./points/modelPoint";
37
+ export { LocalPed, type LocalPedOptions } from "./localPed";
38
+ export { Blips, createBlip, type BlipOptions, type BlipStyle } from "./blip";
39
+ export { fadeIn, fadeOut } from "./player/fade";
40
+ export { player } from "./player/player";
41
+ export type { AnimOptions, HoldAnimOptions } from "./player/anim";
42
+ export type { TeleportOptions } from "./player/teleport";
43
+ export { notify } from "./notify";
44
+ export {
45
+ cancelProgress,
46
+ isProgressRunning,
47
+ progress,
48
+ type ProgressOptions,
49
+ } from "./progress";
50
+ export { input, itemPicker, menu } from "./menu/dialogs";
51
+ export {
52
+ lockpick,
53
+ skillCheck,
54
+ type LockpickOptions,
55
+ } from "./menu/minigames";
56
+ export type { MenuListeners } from "./menu/requests";
57
+ export { inventory } from "./inventory";
58
+ export { vehicleKeys } from "./vehicleKeys";
59
+ export {
60
+ getVehicleProps,
61
+ setVehicleProps,
62
+ setVehicleSetup,
63
+ } from "./vehicleProps";
64
+ export { getPlayerData, onPlayerData, seedPlayerData } from "./playerData";
65
+ export {
66
+ allows,
67
+ hasJob,
68
+ inGang,
69
+ onDutyIn,
70
+ onMembershipChange,
71
+ } from "./membership";
72
+ export { Keybind, type KeybindOptions } from "./keybind";
73
+ export {
74
+ requestAnimDict,
75
+ requestAnimSet,
76
+ requestModel,
77
+ requestPtfxAsset,
78
+ requestScaleformMovie,
79
+ requestTextureDict,
80
+ requestWeaponAsset,
81
+ } from "./streaming";
82
+ export {
83
+ groundZ,
84
+ locationName,
85
+ vehicleLabel,
86
+ type LocationName,
87
+ } from "./location";
88
+ export { pedHeadshot } from "./headshot";
89
+ export { waypoint } from "./waypoint";
90
+ export { attachProp, type AttachPropOptions } from "./prop";
91
+ export { PreviewVehicle } from "./preview";
92
+ export {
93
+ callExport,
94
+ isResourceStarted,
95
+ optionalExport,
96
+ provideExport,
97
+ registerExport,
98
+ resourceExport,
99
+ } from "../fivem/exports";
100
+ export { createLocale, loadLocaleTexts, LOCALE_CONVAR } from "../fivem/locale";
101
+ export { EntityState } from "../fivem/state/entityState";
102
+ export { GlobalGroup, GlobalKey } from "../fivem/state/globalState";
103
+ export { PlayerState } from "../fivem/state/playerState";
104
+ export {
105
+ stateBoolean,
106
+ stateNumber,
107
+ stateString,
108
+ type StateParse,
109
+ } from "../fivem/state/mirror";
110
+ export { controls } from "./controls";
111
+ export { drivenVehicle, nearestVehicle } from "./vehicles";
112
+ export {
113
+ entitiesInArea,
114
+ isSpawnClear,
115
+ nearestEntity,
116
+ type EntityKind,
117
+ type NearestEntity,
118
+ } from "./entities";
119
+ export { entityFromNetId, waitForEntity } from "./entity";
120
+ export { raycast, type RaycastOptions, type RayHit } from "./raycast";
121
+ export { nearestPlayer, playerPed } from "./players";
122
+ export { onShot } from "./shot";
123
+ export { callAction, type CallActionOptions } from "./action";
124
+ export { isActionOk, replyError } from "../shared/action";
125
+ export { hud } from "./hud";
126
+ export { world } from "./world";
127
+ export { gestures } from "./gestures";
128
+ export { seatbelt } from "./seatbelt";
129
+ export { appearance } from "./appearance";
130
+ export { keyHints } from "./keyHints";
131
+ export { radial } from "./radial";
@@ -0,0 +1,117 @@
1
+ import {
2
+ CLIENT_ITEM_COUNT_EVENT,
3
+ CORE,
4
+ type HeldWeapon,
5
+ type InventoryStack,
6
+ type ItemDefinition,
7
+ } from "@aifivem/shared";
8
+ import { resourceExport } from "../fivem/exports";
9
+ import { isRecord } from "../shared";
10
+
11
+ const core = resourceExport(CORE.resource);
12
+
13
+ /** ai-core's answer, checked: another resource's export returns unknown data. */
14
+ function toHeldWeapon(value: unknown): HeldWeapon | null {
15
+ if (!isRecord(value) || typeof value.name !== "string") return null;
16
+ return {
17
+ name: value.name,
18
+ label: typeof value.label === "string" ? value.label : value.name,
19
+ image: typeof value.image === "string" ? value.image : undefined,
20
+ };
21
+ }
22
+
23
+ /** The local player's inventory through ai-core's inventory layer (the inventory the server picked answers). */
24
+ export const inventory = {
25
+ /** Opens the player's own inventory screen. */
26
+ openInventory: (): void => core.OpenInventory(),
27
+ /** Whether the player holds at least `count` of an item. */
28
+ hasItem: (item: string, count = 1): boolean => core.HasItem(item, count),
29
+ /** The weapon item in the player's hand (name, label, picture), or null; read it on `onCache("weapon")`, not per frame. */
30
+ currentWeapon: (): HeldWeapon | null => toHeldWeapon(core.GetCurrentWeapon()),
31
+ /** How many of an item the player holds; null when the active inventory has no client count. */
32
+ itemCount: (item: string): number | null => {
33
+ const n: unknown = core.GetItemCount(item);
34
+ return typeof n === "number" ? n : null;
35
+ },
36
+ /** An item's label, weight, flags and picture from ai-core's client mirror; null when unknown. */
37
+ itemDefinition: (name: string): ItemDefinition | null =>
38
+ toDefinition(core.GetItemDefinition(name)),
39
+ /** Every item definition of ai-core's client mirror, by name. */
40
+ itemDefinitions: (): Record<string, ItemDefinition> => {
41
+ const all: unknown = core.GetItemDefinitions();
42
+ const out: Record<string, ItemDefinition> = {};
43
+ if (isRecord(all))
44
+ for (const [name, def] of Object.entries(all)) {
45
+ const read = toDefinition(def);
46
+ if (read) out[name] = read;
47
+ }
48
+ return out;
49
+ },
50
+ /** Every stack the player holds; null when the active inventory has no client list (ask your server). */
51
+ items: (): InventoryStack[] | null => {
52
+ const list: unknown = core.GetItems();
53
+ return Array.isArray(list) ? list.flatMap(toStack) : null;
54
+ },
55
+ /** The player's stacks by slot; null when the active inventory has no client list. */
56
+ itemsBySlot: (): Record<number, InventoryStack> | null => {
57
+ const list = inventory.items();
58
+ if (!list) return null;
59
+ const out: Record<number, InventoryStack> = {};
60
+ for (const stack of list) out[stack.slot] = stack;
61
+ return out;
62
+ },
63
+ /** The first stack of an item the player holds; null when none (or no client list). */
64
+ firstStack: (item: string): InventoryStack | null =>
65
+ inventory.items()?.find((stack) => stack.name === item) ?? null,
66
+ /** Runs `handler(item, count, previous)` each time the player's total of an item changes in the active inventory. */
67
+ onCount: (
68
+ handler: (item: string, count: number, previous: number) => void,
69
+ ): void => {
70
+ on(
71
+ CLIENT_ITEM_COUNT_EVENT,
72
+ (item: unknown, count: unknown, previous: unknown) => {
73
+ if (typeof item === "string" && typeof count === "number")
74
+ handler(item, count, typeof previous === "number" ? previous : 0);
75
+ },
76
+ );
77
+ },
78
+ };
79
+
80
+ /** One stack of ai-core's answer, checked; none when it is not one. */
81
+ function toStack(value: unknown): InventoryStack[] {
82
+ if (
83
+ !isRecord(value) ||
84
+ typeof value.name !== "string" ||
85
+ typeof value.count !== "number" ||
86
+ typeof value.slot !== "number"
87
+ )
88
+ return [];
89
+ return [
90
+ {
91
+ name: value.name,
92
+ label: typeof value.label === "string" ? value.label : value.name,
93
+ count: value.count,
94
+ slot: value.slot,
95
+ metadata: isRecord(value.metadata) ? value.metadata : {},
96
+ },
97
+ ];
98
+ }
99
+
100
+ /** ai-core's answer, checked like `toHeldWeapon`. */
101
+ function toDefinition(value: unknown): ItemDefinition | null {
102
+ if (
103
+ !isRecord(value) ||
104
+ typeof value.name !== "string" ||
105
+ typeof value.label !== "string"
106
+ )
107
+ return null;
108
+ return {
109
+ name: value.name,
110
+ label: value.label,
111
+ weight: typeof value.weight === "number" ? value.weight : 0,
112
+ unique: value.unique === true,
113
+ close: value.close !== false,
114
+ description: typeof value.description === "string" ? value.description : "",
115
+ image: typeof value.image === "string" ? value.image : undefined,
116
+ };
117
+ }
@@ -0,0 +1,13 @@
1
+ import { CORE, type KeyHintRequest } from "@aifivem/shared";
2
+ import { resourceExport } from "../fivem/exports";
3
+
4
+ const core = resourceExport(CORE.resource);
5
+
6
+ /**
7
+ * Key hints a script shows for a while (admin noclip keys, a minigame's controls) next to the ones keybinds declare
8
+ * with `hint`; HUDs list them on the left. `keybind` shows that keybind's current key, `key` a literal text.
9
+ */
10
+ export const keyHints = {
11
+ show: (id: string, hint: KeyHintRequest): void => core.ShowKeyHint(id, hint),
12
+ hide: (id: string): void => core.HideKeyHint(id),
13
+ };
@@ -0,0 +1,163 @@
1
+ import {
2
+ CORE,
3
+ KEYBIND,
4
+ type KeybindInfo,
5
+ type KeyHintWhen,
6
+ } from "@aifivem/shared";
7
+ import { isResourceStarted } from "../fivem/exports";
8
+
9
+ export interface KeybindOptions {
10
+ /** Stable id, unique on the server, without the key (`inventory_open`); the mapping command is `<name>_<key>`. */
11
+ name: string;
12
+ /** Shown in GTA's key settings and the admin panel: a lang text, never a literal. */
13
+ description: string;
14
+ /** The script's default key; the admin panel's Keybinds tab can set another one. */
15
+ defaultKey?: string;
16
+ /** Input mapper: "keyboard" (default), "MOUSE_BUTTON" for mouse buttons, "PAD_DIGITALBUTTON" for pads. */
17
+ defaultMapper?: string;
18
+ allowInPauseMenu?: boolean;
19
+ disabled?: boolean;
20
+ onPressed?: () => void;
21
+ onReleased?: () => void;
22
+ /** HUDs list the key in their key hints: on foot, in a vehicle or always (the owner can change it in the panel). */
23
+ hint?: KeyHintWhen;
24
+ /** Font Awesome solid icon name (without `fa-`) HUDs draw next to the hint. */
25
+ icon?: string;
26
+ /** A short hint text (a lang text, one or two words); `description` when absent. */
27
+ hintLabel?: string;
28
+ }
29
+
30
+ const resource = GetCurrentResourceName();
31
+ /** This resource's keybinds by name: ai-core answers each with its key at start and again when the panel changes it. */
32
+ const keybinds = new Map<string, (key: string) => void>();
33
+ let listening = false;
34
+
35
+ /** Asks ai-core's client for the key (it knows the panel's keybind defaults); without ai-core the script's own. */
36
+ function requestKey(info: KeybindInfo, apply: (key: string) => void): void {
37
+ // ai-core's own keybinds are made while it is still "starting".
38
+ if (resource !== CORE.resource && !isResourceStarted(CORE.resource))
39
+ return apply(info.defaultKey);
40
+ if (!listening) {
41
+ listening = true;
42
+ on(KEYBIND.keyEvent, (owner: unknown, name: unknown, key: unknown) => {
43
+ if (
44
+ owner === resource &&
45
+ typeof name === "string" &&
46
+ typeof key === "string"
47
+ )
48
+ keybinds.get(name)?.(key);
49
+ });
50
+ }
51
+ let answered = false;
52
+ keybinds.set(info.name, (key) => {
53
+ answered = true;
54
+ apply(key);
55
+ });
56
+ emit(KEYBIND.announceEvent, info);
57
+ // ai-core answers once it knows the panel values (one server round trip at most); never leave a key unbound.
58
+ setTimeout(() => {
59
+ if (!answered) apply(info.defaultKey);
60
+ }, 15_000);
61
+ }
62
+
63
+ /**
64
+ * A key the player can rebind in GTA's settings (RegisterKeyMapping); no per-frame key polling. The default key
65
+ * comes from ai-core's admin panel when set there: the mapping command carries the key (`+<name>_<key>`), so a new
66
+ * default makes a new mapping that every player gets. It is registered once ai-core answered (at start).
67
+ */
68
+ export class Keybind {
69
+ readonly name: string;
70
+ private disabled: boolean;
71
+ private pressed = false;
72
+ private hash = 0;
73
+ /** The mapping command in use; earlier ones (older keys) stay registered but do nothing. */
74
+ private command = "";
75
+ private readonly registered = new Set<string>();
76
+ /** The key the current mapping was registered with. */
77
+ private boundKey = "";
78
+
79
+ constructor(private readonly options: KeybindOptions) {
80
+ this.name = options.name;
81
+ this.disabled = options.disabled ?? false;
82
+ const info: KeybindInfo = {
83
+ resource,
84
+ name: options.name,
85
+ description: options.description,
86
+ defaultKey: options.defaultKey ?? "",
87
+ mapper: options.defaultMapper ?? "keyboard",
88
+ hint: options.hint,
89
+ icon: options.icon,
90
+ hintLabel: options.hintLabel,
91
+ };
92
+ requestKey(info, (key) => this.register(key.toUpperCase()));
93
+ }
94
+
95
+ /**
96
+ * Registers the mapping of a key; a later key (a panel change) registers its own mapping and the old one stops
97
+ * acting. FiveM keeps every registered mapping and the player's binding per command, so the key is in the name.
98
+ */
99
+ private register(key: string): void {
100
+ const command = key ? `${this.name}_${key}` : this.name;
101
+ if (command === this.command) return;
102
+ this.command = command;
103
+ this.boundKey = key;
104
+ if (this.registered.has(command)) {
105
+ this.hash = GetHashKey(`+${command}`) | 0x80000000;
106
+ return;
107
+ }
108
+ this.registered.add(command);
109
+ this.hash = GetHashKey(`+${command}`) | 0x80000000;
110
+ RegisterCommand(
111
+ `+${command}`,
112
+ () => command === this.command && this.press(true),
113
+ false,
114
+ );
115
+ RegisterCommand(
116
+ `-${command}`,
117
+ () => command === this.command && this.press(false),
118
+ false,
119
+ );
120
+ RegisterKeyMapping(
121
+ `+${command}`,
122
+ this.options.description,
123
+ this.options.defaultMapper ?? "keyboard",
124
+ key,
125
+ );
126
+ // The +/- commands are internal; keep them out of chat suggestions.
127
+ setTimeout(() => {
128
+ emit("chat:removeSuggestion", `/+${command}`);
129
+ emit("chat:removeSuggestion", `/-${command}`);
130
+ }, 500);
131
+ }
132
+
133
+ private press(down: boolean): void {
134
+ if (
135
+ this.disabled ||
136
+ (!this.options.allowInPauseMenu && IsPauseMenuActive())
137
+ )
138
+ return;
139
+ this.pressed = down;
140
+ if (down) this.options.onPressed?.();
141
+ else this.options.onReleased?.();
142
+ }
143
+
144
+ /** Whether the key is held now. */
145
+ get isPressed(): boolean {
146
+ return this.pressed;
147
+ }
148
+
149
+ /**
150
+ * The key the player has bound right now, for HUD hints and NUI close keys ("" until the mapping is registered).
151
+ * GTA names keys with a picture (F1-F12, Tab...) by an icon code (`b_171`): those give the registered key instead.
152
+ */
153
+ get currentKey(): string {
154
+ if (!this.hash) return "";
155
+ const button = GetControlInstructionalButton(0, this.hash, true);
156
+ return button.startsWith("t_") ? button.slice(2) : this.boundKey;
157
+ }
158
+
159
+ disable(disabled: boolean): void {
160
+ this.disabled = disabled;
161
+ this.pressed = false;
162
+ }
163
+ }
@@ -0,0 +1,169 @@
1
+ import { createLogger } from "../shared";
2
+ import { requestAnimDict, requestModel } from "./streaming";
3
+ import { Zones } from "./zones";
4
+
5
+ const log = createLogger(GetCurrentResourceName());
6
+
7
+ export interface LocalPedOptions {
8
+ /** Model name or hash. */
9
+ model: string | number;
10
+ coords: { x: number; y: number; z: number; heading: number };
11
+ /** `coords.z` is the floor (panel points): the ped stands on it. Otherwise z is the ped's own root. Default true. */
12
+ ground?: boolean;
13
+ /** A scenario it plays (`WORLD_HUMAN_CLIPBOARD`), or an animation loop. */
14
+ scenario?: string;
15
+ anim?: { dict: string; clip: string };
16
+ /** Spawned when the player comes this close, removed past it (default 50 m). */
17
+ distance?: number;
18
+ /**
19
+ * Attached to an entity (a bed, a vehicle, another ped) at a bone with an offset and rotation; `entity` may be a
20
+ * function read at each spawn (an entity found from a network id). Not frozen while attached. `coords` stays where
21
+ * the ped is created and the distance is measured from.
22
+ */
23
+ attach?: {
24
+ entity: number | (() => number);
25
+ /** Bone index (`GetEntityBoneIndexByName`, `GetPedBoneIndex`); default 0, the entity's root. */
26
+ bone?: number;
27
+ offset?: { x: number; y: number; z: number };
28
+ rotation?: { x: number; y: number; z: number };
29
+ };
30
+ /** Sitting in a vehicle seat (-1 driver, 0 front passenger...); `vehicle` may be a function read at each spawn. */
31
+ seat?: { vehicle: number | (() => number); seat: number };
32
+ /** After the ped appears (target options, props) and before it goes. */
33
+ onSpawn?: (ped: number) => void;
34
+ onDespawn?: (ped: number) => void;
35
+ }
36
+
37
+ /** One zone set for every local ped of this resource: peds exist only while their player is near. */
38
+ const zones = new Zones();
39
+ let nextId = 0;
40
+
41
+ /**
42
+ * A ped only this client sees (a shopkeeper, a job NPC): created when the player comes near, deleted when they leave,
43
+ * frozen, invincible and deaf to events. Never networked, so strict entity lockdown does not matter.
44
+ */
45
+ export class LocalPed {
46
+ private readonly id = `ped:${++nextId}`;
47
+ private handle = 0;
48
+ private wanted = false;
49
+
50
+ constructor(private readonly options: LocalPedOptions) {
51
+ const { x, y, z } = options.coords;
52
+ zones.add(this.id, {
53
+ shape: {
54
+ type: "sphere",
55
+ center: { x, y, z },
56
+ radius: options.distance ?? 50,
57
+ },
58
+ interval: 1000,
59
+ onEnter: () => void this.spawn(),
60
+ onExit: () => this.despawn(),
61
+ });
62
+ }
63
+
64
+ /** The ped while it exists, else 0. */
65
+ get entity(): number {
66
+ return this.handle;
67
+ }
68
+
69
+ /** Deletes the ped for good. */
70
+ remove(): void {
71
+ zones.remove(this.id);
72
+ this.despawn();
73
+ }
74
+
75
+ private async spawn(): Promise<void> {
76
+ this.wanted = true;
77
+ const o = this.options;
78
+ try {
79
+ const hash = await requestModel(o.model);
80
+ if (o.anim) await requestAnimDict(o.anim.dict);
81
+ // The player may have left while the model loaded.
82
+ if (!this.wanted || this.handle) return;
83
+ const { x, y, z, heading } = o.coords;
84
+ const ped = CreatePed(
85
+ 4,
86
+ hash,
87
+ x,
88
+ y,
89
+ o.ground === false ? z : z - 1,
90
+ heading,
91
+ false,
92
+ false,
93
+ );
94
+ SetModelAsNoLongerNeeded(hash);
95
+ if (!this.place(ped)) FreezeEntityPosition(ped, true);
96
+ SetEntityInvincible(ped, true);
97
+ SetBlockingOfNonTemporaryEvents(ped, true);
98
+ SetPedCanRagdoll(ped, false);
99
+ if (o.scenario) TaskStartScenarioInPlace(ped, o.scenario, 0, true);
100
+ else if (o.anim)
101
+ TaskPlayAnim(
102
+ ped,
103
+ o.anim.dict,
104
+ o.anim.clip,
105
+ 8,
106
+ 8,
107
+ -1,
108
+ 1,
109
+ 0,
110
+ false,
111
+ false,
112
+ false,
113
+ );
114
+ this.handle = ped;
115
+ o.onSpawn?.(ped);
116
+ } catch (error) {
117
+ log.error(`local ped ${o.model} could not be created`, error);
118
+ }
119
+ }
120
+
121
+ /** Puts the new ped into its seat or attaches it; false when it stands free (no target entity right now). */
122
+ private place(ped: number): boolean {
123
+ const read = (e: number | (() => number)) =>
124
+ typeof e === "function" ? e() : e;
125
+ const { seat, attach } = this.options;
126
+ if (seat) {
127
+ const vehicle = read(seat.vehicle);
128
+ if (!vehicle || !DoesEntityExist(vehicle)) return false;
129
+ SetPedIntoVehicle(ped, vehicle, seat.seat);
130
+ return true;
131
+ }
132
+ if (!attach) return false;
133
+ const entity = read(attach.entity);
134
+ if (!entity || !DoesEntityExist(entity)) return false;
135
+ const o = attach.offset ?? { x: 0, y: 0, z: 0 };
136
+ const r = attach.rotation ?? { x: 0, y: 0, z: 0 };
137
+ AttachEntityToEntity(
138
+ ped,
139
+ entity,
140
+ attach.bone ?? 0,
141
+ o.x,
142
+ o.y,
143
+ o.z,
144
+ r.x,
145
+ r.y,
146
+ r.z,
147
+ false,
148
+ false,
149
+ false,
150
+ false,
151
+ 2,
152
+ true,
153
+ );
154
+ return true;
155
+ }
156
+
157
+ private despawn(): void {
158
+ this.wanted = false;
159
+ if (!this.handle) return;
160
+ const ped = this.handle;
161
+ this.handle = 0;
162
+ this.options.onDespawn?.(ped);
163
+ DeleteEntity(ped);
164
+ }
165
+ }
166
+
167
+ on("onResourceStop", (resource: string) => {
168
+ if (resource === GetCurrentResourceName()) zones.clear();
169
+ });