Compare commits

...

164 Commits

Author SHA1 Message Date
McKlean
30de9a2d9c Version Bump 2025-06-18 20:52:04 +01:00
Jim Shield
f39678002f Fix progressbars getting stuck on ox_lib 2025-06-18 12:02:03 +01:00
McKlean
3e402cae3d Commit[progressBar]: ox progress options
- Added ability to choose circle/bar type
- Added ability for props when using progbar
2025-06-16 19:02:46 +01:00
Jim Shield
b4aa1b3eda Version Bump
`2.0.15 - 2.0.16`
2025-06-16 11:05:46 +01:00
Jim Shield
0f9bab00ef add openBossmenu() function 2025-06-16 00:10:32 +01:00
Jim Shield
9d8706e8c6 Tidy up setThirst() and setHunger() functions
added debug print and fixed non-esx functions setting needs wrong
2025-06-14 22:32:58 +01:00
Jim Shield
6ba1e14888 Change crafting menu slightly to make it more readable 2025-06-14 14:44:16 +01:00
Jim Shield
0454f8c0a9 Add full support for JPR-Inventory
Thanks to JPR for providing access to make this possible

https://jpresources.tebex.io/package/5284060
2025-06-13 23:25:32 +01:00
Jim Shield
e17d8f2b93 Merge pull request #46 from oosayeroo/main 2025-06-13 18:43:21 +01:00
oosayeroo
b44dfa91e5 Merge branch 'jimathy:main' into main 2025-06-11 18:44:49 +01:00
oosayeroo
51d4c88694 light fix (in case of missing Crafting Var)
- added check for missing Config.Crafting variables

- reduces errors in scripts if not added to config
2025-06-11 18:43:31 +01:00
Jim Shield
f5f502875e Comment out a couple debug prints for now 2025-06-11 16:30:51 +01:00
Jim Shield
9c769f4e8e Update frameworkCache.lua 2025-06-11 16:30:29 +01:00
Jim Shield
87cdd5502e Change QBInvNew export because i forgor
I forgot that it needed to check the client side too for the change, but I set it to check for a server only export

got lucky and realised `HasItem` is an export on both client and server
2025-06-10 21:47:12 +01:00
Jim Shield
68d713a8dc Add warnings for QB if theres an error in shared files
If `jim_bridge` attempts to find shared files, and it returns `nil` it will print an error message stating it couldn't find them.

So..people can stop blaming me for my script not working when its an error in their vehicles.lua
2025-06-10 18:29:10 +01:00
Jim Shield
dd34f8aab1 Add auto checkers for QBInvNew
I had to add a checker for if old qbinv was being used or new qbinv

This was made into a variable, but this update makes the script auto set it if it can't find an export. Automating the process
2025-06-10 18:26:57 +01:00
Jim Shield
4a3fb8db4d Add "support" for CodeM shops
This is a tricky one to support

They handle their shops inside their script with no way to add one from the outside

They give the ability to trigger a shop from outside the script, but not create one

This just adds that trigger for now
2025-06-07 19:50:34 +01:00
Jim Shield
59733de08e support for npwd_qbx_mail addon for sending mail 2025-06-07 19:48:18 +01:00
Jim Shield
2b7a1c2e6d Start working on billPlayer() function
The intention here is to try and add multiple "billing" script functions, so the user can pre-set it for scripts that use `jim_bridge`

Currently only handles `jim-payments`
2025-06-07 18:14:53 +01:00
Jim Shield
5db9e88bb9 add function checkExportExists()
Workaround function made to detect if new QB Inventory functions are available

This can be used in other situations like checking if a script is working correctly or not and the export has been registered
2025-06-07 18:13:06 +01:00
Jim Shield
a5b1f750dd Fix weapons caching for ox_inv
I completely overlooked the fact that when ox_inv shows weapon info, it does it with the upper case version `WEAPON_PISTOL` while my scripts were looking for `weapon_pistol`

making my scripts think they didn't exist

This fixes that
2025-06-06 19:36:12 +01:00
Jim Shield
4c514b459e Merge branch 'main' of https://github.com/jimathy/jim_bridge 2025-06-06 01:02:34 +01:00
Jim Shield
32b99d14e1 Version Bump
`2.0.14` - `2.0.15`
2025-06-06 01:01:31 +01:00
Jim Shield
de8f7c050c Complete refactor of handling of framework info
I've moved the framework caching to a new file `frameworkCache.lua`

This now caches the framework data once when `jim_bridge` starts

Then in `coreloader.lua` now, the information that is cached is now called from that script

This also includes better handling of ESX cached data and should stop errors

This greatly optimizes the loading of all my scripts and lowers server load to speed up server start times

I have been testing this for just under a week and 6 different test servers and it appears to work fine
2025-06-06 00:50:13 +01:00
Jim Shield
9c4c92e696 Move GTA notify, target, skillcheck to /ui_modules
I've separated the built-in custom native GTA Notifications, skillcheck and draw text targets to separate files to be loaded along side `jim_bridge`

This now makes it so they only load once instead of with every single script, and each one can call on it

This change also makes these systems able to be called outside of `jim_bridge`

For example in my test server I'm currently using:

```lua
function QBCore.Functions.Notify(text, texttype, length, icon)
    CreateThread(function()
        exports.jim_bridge:Notify(nil, text, icon)
    end)
end
```
2025-06-06 00:45:08 +01:00
Jim Shield
0cedd85afb Add optional warmenu.lua for gta menus 2025-06-06 00:39:24 +01:00
Jim Shield
1bb125ed31 Add clearStash() function 2025-06-06 00:38:51 +01:00
Jim Shield
72778235b8 Merge pull request #45 from oosayeroo/main 2025-06-06 00:37:33 +01:00
Jim Shield
76c34b8c03 Unify isInventoryOpen() function
This should fix issues for crafting complaining inventories are open when they aren't

I was trying to use per inventory checks for them being open until I realised I could just use `IsNuiFocused()` for all inventories to check if there was an nui on the screen that used the mouse, this should be a good workaround for it
2025-06-04 13:53:49 +01:00
Jim Shield
3ca2da2990 Try and enhance built in draw text with job+item checks 2025-06-03 22:22:49 +01:00
Jim Shield
d3035efd5c breakout from inventory exploit during crafting 2025-06-03 16:56:56 +01:00
oosayeroo
64a74a8928 Merge branch 'jimathy:main' into main 2025-06-03 08:54:36 +01:00
oosayeroo
e0fcf23dba added simple "doesItemExist(item)" function
- very simple function to check existance of an item
2025-06-03 08:52:06 +01:00
Jim Shield
ad1ce5f9ea Fix Old QBinv and new/old Psinv stashes being wiped
This appeared to only happen with `jim-mechanic` repair from stash, due to the stashitem's table not being sent to the function
Making it save an empty table to the database

But this was possible in other places too

I've added fallbacks for if it didn't receive a table, grab a fresh one from cache/database
2025-06-02 11:20:47 +01:00
Jim Shield
c3ce0ccc54 Version Bump
`2.0.13` - `2.0.14`
2025-05-31 12:18:44 +01:00
Jim Shield
0b7c96f66a Possibly fix QS Stashes wiping at script start 2025-05-31 12:12:15 +01:00
Jim Shield
3daa6a9772 Better workarounds for no info yet to getPlayer() 2025-05-26 19:10:54 +01:00
Jim Shield
c86cdf9227 Remove "Offline" check from canCarry() 2025-05-26 16:21:25 +01:00
Jim Shield
ca78c1b100 Load QBOX Weaps into Item list 2025-05-26 16:10:41 +01:00
Jim Shield
398701c4d7 attempt to fix support of ox_core job gathering 2025-05-26 16:08:51 +01:00
Jim Shield
00e420fd45 Add fix for ox_core injecting ox_lib itself 2025-05-26 15:58:49 +01:00
Jim Shield
a07cbc467d Merge branch 'main' of https://github.com/jimathy/jim_bridge 2025-05-24 11:01:24 +01:00
Jim Shield
ccd5144e7b Merge pull request #44 from dragon703/main 2025-05-24 11:00:13 +01:00
Jim Shield
195182f850 Merge pull request #43 from oosayeroo/main 2025-05-24 10:56:20 +01:00
Aditya Ray
c2b48c444c Support of Society Bank Features using Tgiann-Bank
Modified functions for fetching society account balance, charging society account and funding society accounts using Tgiann-Bank script.
2025-05-23 17:03:06 +05:30
Jim Shield
156b44a49b change blipinfo stuff to jim-blipcontroller 2025-05-21 21:04:29 +01:00
Jim Shield
a48b83155c add fallback to sellMenu if no locale system 2025-05-21 18:23:38 +01:00
Jim Shield
e455d1b43d getPlayer() fallback if player hasn't loaded yet 2025-05-21 15:38:56 +01:00
Jim Shield
14c2a79673 Version Bump
`2.0.12` - `2.0.13`
2025-05-19 23:39:46 +01:00
Jim Shield
97a1d97678 add random number helper
This function was created to help create random numbers
When you create a table of items with a random hunger value for example
`hunger = math.random(10, 20)` this will be set at script start and never change
using `hunger = {10, 20}` and then calling this function will make it generate a random number every time
It also fallsback if it simply recieved a number instead of a table
-- For example:
-- local hunger = {10, 20}
-- local hungerAmount = GetRandomTiming(hunger)
-- print(hungerAmount) -- number between 10, 20
2025-05-19 19:53:52 +01:00
Jim Shield
5001642504 Update version.txt 2025-05-19 17:14:41 +01:00
Jim Shield
5f413a2823 Update version checkers to support mini changelogs 2025-05-19 17:10:14 +01:00
Jim Shield
4d04682b33 Version Bump
`2.0.11` - `2.0.12`
2025-05-18 22:34:08 +01:00
Jim Shield
cb38d275d1 People were asking how to remove a print
I kept getting people asking how to remove prints because it "was filling up their f8 menu and looked like errors"

So I've made the "success" coreloader prints to be debugmode only.
2025-05-18 16:32:29 +01:00
Jim Shield
84cfe1c97d Fix stash stash opening for some inventories
Mainly older inventories may have had issues with custom stash sizes when opening them

This should fix compatibility with changing slots and max weight with them on trigger
2025-05-18 16:31:30 +01:00
Jim Shield
47b01df621 Remove coords from openGrabBox 2025-05-17 20:38:21 +01:00
Jim Shield
7e073b16ec Update starter.lua 2025-05-17 20:23:32 +01:00
Jim Shield
ab4298fa2d Change coreloader prints to a debugPrint 2025-05-17 19:19:15 +01:00
Jim Shield
7997ea45b7 change "Shared Load Detected" to a debugPrint 2025-05-17 19:16:24 +01:00
Jim Shield
7aa9d90d0d Improve ESX Job cache builder
When collecting Jobs from the server it tries it's best to determine which role is the "Boss"

It checks first of the Job Grade label containing the word "Boss"

If it can't find it, it then uses the highest number grade and adds `.isBoss = true` to it
2025-05-17 16:48:23 +01:00
oosayeroo
451e4cbbdb better documentation layout
- seperated the 2000+ lines in ReadMe.md into seperate files.
 - useful if things expand
 - better readability for users
 - more organised layout
2025-05-16 14:28:41 +01:00
Jim Shield
520758b355 Version Bump
`2.0.10` - `2.0.11`
2025-05-15 20:20:47 +01:00
Jim Shield
e4e9ef0fb2 add openGrabBox event for items like murderbag 2025-05-15 20:02:39 +01:00
Jim Shield
ada724069b Revert qs-inv server inv grab
Found the real issue that was causing the scripts to not think you had items, basically reverting this change as i didn't like having it in the first place
2025-05-15 19:59:51 +01:00
Jim Shield
9198068a19 Adjust hasItem function for QS-Inv
Apparently qs-inv reports two variables on the item data for how you have
`count` and `amount`
while other inventories appear to only have one of those

I'm assuming for compatibility sake

Apparently the `count` is updated differently, and `hasItem()` was checking for this first

I've swapped round the checks and appears to work better
2025-05-15 19:55:14 +01:00
Jim Shield
263d5160aa Add delay for checking for inventory items on qb
Custom inventories apparently load items separately/later into qbshared

so the script starts thinking there is definitely 0 items but its checking too early, this forces it to wait until its available to continue
2025-05-15 15:31:41 +01:00
Jim Shield
65137207ae add fallback for hasItem if no inventory is found 2025-05-14 23:38:34 +01:00
Jim Shield
3bd9935346 Skip item for sellmenu if item isn't in shared
Adds an item check before creating the sellmenu as to avoid errors
2025-05-14 23:36:46 +01:00
Jim Shield
23e2488cd1 fix typo for qs-inv callback for inventory 2025-05-14 16:09:02 +01:00
Jim Shield
e9bbdd4ce0 Version Bump
`2.0.09` - `2.0.10`
2025-05-13 22:02:37 +01:00
Jim Shield
f5a7ec9291 fix inventory exploit trigger blocking crafting
The inventory exploit check when crafting never released crafting so you couldn't craft again until reconnecting or script restart
2025-05-13 21:57:19 +01:00
Jim Shield
d80ea38a39 Fix sell menu throwing errors on openning
It was checking the wrong table name for amounts and getting `nil`
2025-05-13 21:56:18 +01:00
Jim Shield
e64912622b Testing a fix with QS-INV item checks
So..from what I can gather, QS-Inv doesn't seem to be updating the client cache of the players inventory correctly

This is all speculation, I can't check this myself

When `hasItem()` is used, its essentially reading from the client's cache.
This seemingly is only updated when there is a new item in a slot, **not** when the amount of an item in that slot changes

The only way to circumvent this is a workaround to the players inventory from the server side using a callback. This is painful to do because it can increase server load when checking multiples of items
2025-05-13 17:57:27 +01:00
Jim Shield
04b25e2c06 create waitForSharedLoad() function
This my attempt to aid ESX loading, essentially my scripts server side now need to be locked behind `onResourceStart()` because of ESX

Loading ESX into my scripts was delaying half of it and breaking the other half

This function forcibly waits until everythings loaded and then continues

This shouldn't affect other frameworks loading ability

My tests so far have been a success with it
2025-05-12 22:59:31 +01:00
Jim Shield
51473bf0b8 Version Bump
`2.0.08` - `2.0.09`
2025-05-12 13:52:14 +01:00
Jim Shield
921b973f81 Try and fix ESX loading
So information and request for help.

The issue here is that my scripts require Job and Vehicle information when the script starts, to do a debug check if the job exists for the location.

ESX doesn't share this with the client for some reason, so this requires me to request it from the server side at script ensure.

This is causing issues because it delays loading of the rest of `jim_bridge` while it slowly requests `ESX.GetJobs()` table from server side

This is delayed even more when the script is placed towards the top of the server load order and it needs to load other things like MLO's

As its trying to load this the rest of the script carries on loading with missing information.

So it loads the script thinking there are 0 jobs and breaks it.

If anyone knows of a better way of doing this then please help.
The only partial solution is to start my scripts last in the server load order
2025-05-12 13:51:32 +01:00
Jim Shield
42d08ccf4c Tidy up the stashRemoveItem function 2025-05-12 13:44:37 +01:00
Jim Shield
68412d8006 Enforce numbers when changing stats
if the value ends up being `nil` this *should* force it to 0

Also added a check for if it can actually give `randomReward` before trying to
2025-05-11 14:16:02 +01:00
Jim Shield
4c89ec3190 Version Bump
`2.0.07` - `2.0.08`
2025-05-10 19:55:51 +01:00
Jim Shield
b2fa1ef247 Update starter.lua
Updated and putting into use the core file loader function in starter.lua
2025-05-10 19:54:31 +01:00
Jim Shield
9872c77591 Only allow script version checks for my scripts
Added a check to version check for if "Jimathy" is the author, this then stops it and doesn't check for the versions on my github repositories
2025-05-10 19:20:47 +01:00
Jim Shield
7ecb2f18e9 Refactor ESX Core loading
I realised I was loading ESX the stupidest way

I think I was loading ESX object, then instantly clearing it and then used workarounds to try and reload it (thinking is hard ok)

It should now load correctly and faster

also I realised my custom `onPlayerLoaded()` function was loading too fast, so I've added a delay to it but removed the while loops for esx checks that could potentially break the script
2025-05-07 23:01:29 +01:00
Jim Shield
d0c09f3e00 switch old ps-inv stash call back to old event
older ps didn't call `ps-inventory` for stash, just `inventory`
2025-05-07 21:12:38 +01:00
Jim Shield
c1e38a93bd Version Bump
`2.0.06` - `2.0.07`
2025-05-07 16:42:00 +01:00
Jim Shield
6a3041524a Re-add old qb-inv support for canCarry()
When updating to use the new export for qb-inv, I accidently removed the old functions, this readds them and fixes support for it
2025-05-07 16:38:57 +01:00
Jim Shield
f069db5c61 Update QBInv stash retrieval
Now uses GetInventory to grab the stash from its cache instead of directly from database

Also fixes old qb inv support for stash retrieval
2025-05-07 16:36:18 +01:00
Jim Shield
3b768d5c7d update isStarted() fuction
Add fallback for if somehow the script name being checked was sent as `nil`, if `nil` it returns false
2025-05-07 13:56:26 +01:00
Jim Shield
6b8698353b Expand on the core file loading system
This is still not in use for now, but it WILL be used in the future

I'm getting too many support tickets about the "Failed to load" warning in console about files they don't have/need
(if you don't run `ox_core` don't worry about `ox_core` not loading)

This system is intended to load it through the script instead of `fxmanifest.lua`

It is intended to check if the user has the required script and also warn them if it's not started (load order issue), or just load it as if it were told to in the fxmanifest
2025-05-07 13:55:12 +01:00
Jim Shield
5868312388 fix ps-inv/lj-inv check
If you didn't have either PS-Inventory or LJ-Inventory, this ended up breaking loading as it ended up checking is `nil` was started
2025-05-07 13:32:54 +01:00
Jim Shield
b0b139b179 Rework ps-inventory support
PS-Inv used to be exactly the same as QB-Inv so alot of the function calls were shared

This separates them and makes it easier to make changes to support their inventory

Also unified the calls for server side functions into single functions instead of having separate per inventory

Also moves:
- `invImg()` to inventories.lua
- `registerStash()` to stashcontrol.lua
2025-05-07 12:58:39 +01:00
Jim Shield
4bf4806b9e workaround for a prop claiming it couldn't find W
this is just a quick workaround, if a prop is created without a heading, it auto sets it to 0
2025-05-07 12:54:23 +01:00
Jim Shield
826e745fc3 fallback for the fallback
Not having the server convars added to the server.cfg was causing issues for some users

it should have worked, but this forces things to gta if you don't have any values set for them anywhere

I've added fallbacks to "gta" settings to hopefully stop fivem errors
2025-05-07 01:59:03 +01:00
Jim Shield
bc2867984c Version Bump
`2.0.05` - `2.0.06`
2025-05-06 10:53:34 +01:00
Jim Shield
31633bc61d crafting exploit fixes
This has several changes

When crafting, it now checks if the inventory is open and stops crafting dead and warns the player with a print.

Multicraft now checks if you have space in your inventory for the items and limits the max amount craftable

Also fixes the "title" of the qb-input box when crafting

Also changed the anim flag for the "placing items" to hopefully keep you in place
2025-05-06 00:17:07 +01:00
Jim Shield
1623feacf1 fix multicraft for qb-input side
I forgot to correct the result as qb-input returns strings, this fixes that

Also added a fallback for if the user deletes the value and tries to craft `nil`
2025-05-05 22:52:46 +01:00
Jim Shield
a203657e2a Add event to clear AuthEvent for player
When a player logs out and back in (switches character) it was thinking that the `AuthEvent` was being called more than once, triggering a warning message

This should clear the event when a player unloads and then allows them to request a new one
2025-05-05 20:01:15 +01:00
Jim Shield
1f4a2ee3d9 refactor checkStashItem()
This'll probably break it, (it works for me) but refactored the stash item check, it was calling `stashHasItem()` for every ingredient check, now it sends the whole table of ingredients per item to craft and checks them together instead of separately

Also removes a `Wait()`, as it shouldn't need it with this change..maybe
2025-05-05 12:28:30 +01:00
Jim Shield
e9c54cbdd4 multiCraft() refactor
An attempt to speed up `multiCraft()` function creation logic

Before it created a table of items while it was trying to check them I've separated this so it just gets that out of the way and checks items in it's own `for` loop

Also added a `maxCreation` variable that users can edit if needed which decides how many of an item can be created (I'll change this soon probably to tie into the config options in scripts for multicraft again soon

Also removed a few `Wait()`s that were there to help it not get confused, but after testing I believe this didn't make a difference, let me know if there's any issues with stuff like it saying it can craft when you dont have the items
2025-05-05 12:24:38 +01:00
Jim Shield
4e8a15590f make a checkToken() event its own function
Several events were calling very similar check token events, so I've just moved them to one to help unify it and help future debugging
2025-05-05 11:44:51 +01:00
Jim Shield
c745d51832 Fix up dupwarn and additem auth messages
Forgot to update this, now prints an optional message if available

and made dupeWarn kick message less specific
2025-05-04 20:33:51 +01:00
Jim Shield
f9b97b7505 Version bump 2.0.05 2025-05-04 16:24:55 +01:00
Jim Shield
489da64c5e add a new warning for token auth 2025-05-04 15:40:20 +01:00
Jim Shield
07c35cd917 workaround for ox_inventory returning a bool
I think, if ox_inventory checks a stash that doesn't exist yet, it returns a boolean or `nil`

This checks for that and instead returns a table to hopefully stop the scripts from breaking
2025-05-04 15:21:02 +01:00
Jim Shield
3f72a21d75 Update bigMessageInstance.lua 2025-05-03 20:28:13 +01:00
Jim Shield
4ad6170a49 Fix ox_target items variable
Completely overlooked that ox_target item variable is `items` not `item`

changes
```lua
                item = opts[i].item or nil,
```
to:
```lua
                items = opts[i].item or nil,
```
2025-05-03 00:11:28 +01:00
Jim Shield
18df0817b1 Make version checks a bit more obvious
Adds more obvious prints if the current version is outdated

(and also repeats it every 20 minutes)
2025-05-02 22:22:47 +01:00
Jim Shield
0eca7ae29e Fix CodeM item slot check for metadata function
The slot data for CodeM apparently returns as a string, this fixes it trying to compare a string to a number

```lua
            if v.name == item and v.slot <= lowestSlot then
```
to
```lua
            if v.name == item and tonumber(v.slot) <= lowestSlot then
```
2025-05-02 22:20:26 +01:00
Jim Shield
6a5913230f Add better fallbacks for if no metadata table is found
```lua
                durability = v.info.durability
```
to:
```lua
                durability = v.info and v.info.durability or nil
```
2025-05-02 22:16:51 +01:00
Jim Shield
b7a284e051 Fix new duty sync
This should have been placed in a `onPlayerLoaded()` but it was checking at script start for player info before that info was able to be grabbed
2025-05-02 12:29:02 +01:00
Jim Shield
0accdda2dd version bump
`2.0.04`
2025-05-02 11:36:54 +01:00
Jim Shield
37b855d7a7 Better syncing of onDuty variable
Added a check to the script start to get the current players duty (helpful if yours saves the duty through restarts)

Also added core specific triggers for job/duty changes to help keep these in sync
2025-05-02 11:20:09 +01:00
Jim Shield
7432dd5118 revert qbinv dectetion
Wasn't playing as well as I thought it would..
2025-05-01 20:05:00 +01:00
Jim Shield
59ff34c9cc Add exploit protection for :Crafting:GetItem
I unfortunately forgot to add this before when adding the extra exploit protection. Now demands an auth token before allowing crafting results to help reduce exploiters calling it externally
2025-05-01 18:07:39 +01:00
Jim Shield
b81ada265b Better support for RedM's RSG Core
Nothing public uses this yet, but its very similar to QBCore which makes it very for me to support

Nothing special to note, just improves the integration for future ventures into RedM
2025-05-01 17:49:37 +01:00
Jim Shield
65c9c6c586 Add automated check for QBInv version
Currently if you still have the old qb-inventory or a css edit it would require you to manually edit the starter.lua
```lua
QBInvNew = true
```

I'm testing a change to grab the version and return true of false if its above `2.0.0` (200)
```lua
local qbInvVer = GetResourceMetadata(Exports.QBInv, 'version', nil):gsub("%.", "")
QBInvNew = tonumber(qbInvVer) >= 200
```
If this causes issue's I'll revert this
2025-05-01 17:08:21 +01:00
Jim Shield
278cbb4d34 fix discord bot yml 2025-05-01 13:36:44 +01:00
Jim Shield
381c19e701 add gitbot yml 2025-05-01 00:20:35 +01:00
Jim Shield
fc2ebefc9e fix CodeM server side inventory info grab 2025-04-30 17:54:04 +01:00
Jim Shield
423b75e7d9 Tgiann Inv support added 2025-04-30 17:53:26 +01:00
Jim Shield
e984a437df attempt to fix shops for QS-Inv 2025-04-30 16:54:33 +01:00
Jim Shield
0818dae0df change qs-inv metadata call to info 2025-04-30 13:21:39 +01:00
Jim Shield
771a2a3217 fix quasar crafting stash item removal 2025-04-29 23:26:10 +01:00
Jim Shield
04b3f87b32 change CodeM metadata check to info 2025-04-29 19:55:30 +01:00
Jim Shield
6c3d0ffc5e change CodeM client inv check to getUserInventory() 2025-04-29 19:55:09 +01:00
Jim Shield
3f093ce934 fix QS-Inv registerStash function 2025-04-29 17:43:37 +01:00
Jim Shield
9a47ec59b0 bump fxmanifest version 2025-04-29 17:24:20 +01:00
Jim Shield
69ce8d9225 remove nui from jim_bridge, i think its killing things 2025-04-29 17:23:28 +01:00
Jim Shield
93b884de01 Bump to 2.0.01 2025-04-29 12:31:05 +01:00
Jim Shield
a308f82be9 version bump 2025-04-29 12:27:00 +01:00
Jim Shield
b3100a336c possible fix for lib error 2025-04-29 12:26:49 +01:00
Jim Shield
8f7f9bb009 force stash to a table when removing items 2025-04-29 02:37:47 +01:00
Jim Shield
25dadae446 Merge pull request #41 from jimathy/1.2 2025-04-28 18:19:38 +01:00
Jim Shield
1d588c4f41 Add a complete readme with documentation 2025-04-22 19:17:34 +01:00
Jim Shield
ac58fe4bb7 Fix and enhance update checker 2025-04-22 19:17:03 +01:00
Jim Shield
45c5af8e81 Fix duplicate functions and typos 2025-04-22 19:16:31 +01:00
Jim Shield
673d9e3a12 fix alt forcing nui focus 2025-04-20 23:44:09 +01:00
Jim Shield
738e11c8e3 Add support for built in nui menu 2025-04-20 19:17:40 +01:00
Jim Shield
842379e8f9 Add override convar checks 2025-04-20 19:17:16 +01:00
Jim Shield
d1bb796d5f implement inbuilt nui menu 2025-04-20 01:22:32 +01:00
Jim Shield
b7db98ffdc esx fixes 2025-04-18 19:45:56 +01:00
Jim Shield
6ce6770df4 add checks for if MySQL has loaded for ESX 2025-04-18 16:14:42 +01:00
Jim Shield
56ef3b75b2 Fix change dui functions 2025-04-14 21:58:38 +01:00
Jim Shield
bd1be5e953 add function to get animal anim table for that ped 2025-04-13 19:07:02 +01:00
Jim Shield
8f72968e76 Create FUNDING.yml 2025-04-13 13:26:09 +01:00
Jim Shield
b27f91ac87 fix playerdata check for isDead in server 2025-04-12 01:09:21 +01:00
Jim Shield
35357c07a3 add isDead and isDown to getPlayer() 2025-04-12 00:19:22 +01:00
Jim Shield
943436467e add ox checkbox option for input 2025-04-12 00:18:48 +01:00
Jim Shield
747fd272d4 fix bigmessage scaleform being local 2025-04-12 00:17:47 +01:00
Jim Shield
3ec00956df Enhance drawtext feature 2025-04-08 17:51:30 +01:00
Jim Shield
1248102635 Add more support for RedM RSGInv 2025-04-08 17:48:38 +01:00
Jim Shield
2be706a860 hopefully fix esx loading 2025-04-08 17:47:12 +01:00
Jim Shield
2da2c56705 add basic support for RedM (RSGCore) 2025-04-07 20:52:59 +01:00
Jim Shield
4d8305c844 changes for beta branch 2025-04-01 14:15:50 +01:00
Jim Shield
8611bc6d3c I am still alive 2025-03-26 21:43:48 +00:00
Jim Shield
2572f86030 input compat fixes 2025-03-11 22:41:13 +00:00
Jim Shield
83ba74bc12 fixes 2025-03-08 20:55:05 +00:00
Jim Shield
6bfb549fd0 refactor + attempt better support for other inventories 2025-03-08 13:44:05 +00:00
Jim Shield
31a7ac2951 general fixes and updates 2025-03-07 13:32:10 +00:00
Jim Shield
1cb2bdb525 fixes for jim-crafting changes 2025-03-07 13:30:17 +00:00
Jim Shield
daa9dca142 fix createCallback complaining on client side 2025-03-07 13:29:43 +00:00
Jim Shield
c947993e9e Add multiscript banking functions 2025-03-07 13:27:47 +00:00
Jim Shield
8dd2b7ae9a Beta: Fixes for existing scripts + feature for jim-crafting 2025-03-06 23:49:07 +00:00
Jim Shield
8eb98bff29 (Beta) Fixes for multiframework support 2025-03-01 12:58:43 +00:00
Jim Shield
f9812a689e Add files via upload 2025-02-22 13:21:54 +00:00
84 changed files with 14082 additions and 7797 deletions

12
.github/FUNDING.yml vendored Normal file
View File

@@ -0,0 +1,12 @@
# These are supported funding model platforms
github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
patreon: # Replace with a single Patreon username
open_collective: # Replace with a single Open Collective username
ko_fi: jixelpatterns
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
liberapay: # Replace with a single Liberapay username
issuehunt: # Replace with a single IssueHunt username
otechie: # Replace with a single Otechie username
custom: ['https://jimathy666.tebex.io/']

17
.github/workflows/notify-discord.yml vendored Normal file
View File

@@ -0,0 +1,17 @@
name: Discord Commit Notifier
on:
push:
branches:
- '*' # triggers on all branches
jobs:
notify:
runs-on: ubuntu-latest
steps:
- name: Discord Commits
uses: Sniddl/discord-commits@v1.6
with:
webhook: ${{ secrets.DISCORD_WEBHOOK }}
template: "avatar-with-link"
include-extras: true

88
README.md Normal file
View File

@@ -0,0 +1,88 @@
# Jim_Bridge
This script is intended to be used with my all my scripts (soon)
It was started due to wanting to bring the same features from some scripts into others with minimal work and without multiple updates fer script
It BRIDGES frameworks and cores together through this script and does it best to detect what is being used to automate the process
- Having certain functions in one place makes it easier to update, enchance and fix things already in place
- This brings the possibility of branching to mutliple frameworks as I've added some already:
- `"qb-core"`
- `"qbx-core"`
- `"ox_core"`
- `"es_extended"` - requires ox_lib and ox_inventory
- `"rsg-core"` - basic support for RedM's RSG Core
All of my scripts will use this script and be added as a dependancy
This was originally designed to be used for my scripts but has grown into a whole framework of unified functions that anyone can use for their own, I encourage it
------
## I want this script to grow with help of others who know more about other cores, I'm not a book of framework knowledge
This script was designed by me through over a year of research and testing.
Some of it of it hasn't been personally tested but the information has been gathered through documentation on other scripts
I hope it works as well I intend, but feel free to do pull requests if you know how to fix an issue
(Please also keep it to a similar format to prevent breakages in other scripts)
------
## Installation
The installation of this script is simple
- REMOVE `-main` from the folder name, like any other github hosted script
- It just needs to start before any script that requires it
- It can start before core scripts if you want
- For example with `qb-core` I personally place this script in `resources > [standalone]`
### Optional
I've added the ability to add override server convars to your server.cfg
- This can be used to ensure you don't have silly mistakes like forgetting to change what inventory system you use
- Also it can force debug mode off, to ensure your live server doesn't accidently get polyzones and debug information showing
- This isn't required but helpful if you are like me
```
# Jim Config Settings
# These optional but forces settings for all jim scripts
#-------
# Add this to your live server.cfg and set to true to force debug mode off
# Set to false if to dev server to allow debug mode
setr jim_DisableDebug true
setr jim_DisableEventDebug true
# Force the default setting for what framework scripts should be used
setr jim_menuScript qb # qb, ox, gta, jim
setr jim_notifyScript gta # qb, ox, gta, esx, okok, red
setr jim_drawTextScript qb # qb, ox, gta, esx
setr jim_progressBarScript qb # qb, ox, gta, esx
setr jim_skillCheckScript qb # qb, ox, gta
setr jim_dontUseTarget false # Set to true to disable target systems and use draw text 3d
```
-----
## Support for different frameworks and scripts
In `starter.lua` is the list of script folder names, this is already setup but this is for people who have customised/renamed their cores or scripts
# WIP
## Documentation
For organised documentation please see the new `documentation` folder within this resource
## Usage
In your own resource, simply call the desired function exported from `jim_bridge`. Each function is built to work across multiple frameworks, offering compatibility and consistency.
```lua
-- Example usage:
createCallback("myCallback", function(data)
print("Callback received:", data)
end)
triggerCallback("myCallback", "Hello World")
```
---

67
_versioncheck.lua Normal file
View File

@@ -0,0 +1,67 @@
local function parseVersion(version)
local parts = {}
for num in version:gmatch("%d+") do
table.insert(parts, tonumber(num))
end
return parts
end
local function compareVersions(current, newest)
local currentParts = parseVersion(current)
local newestParts = parseVersion(newest)
for i = 1, math.max(#currentParts, #newestParts) do
local c = currentParts[i] or 0
local n = newestParts[i] or 0
if c < n then return -1
elseif c > n then return 1 end
end
return 0 -- equal
end
function CheckBridgeVersion()
if IsDuplicityVersion() then
CreateThread(function()
Wait(4000)
local currentVersionRaw = GetResourceMetadata("jim_bridge", 'version')
--PerformHttpRequest('https://raw.githubusercontent.com/jimathy/UpdateVersions/master/test.txt', function(err, body, headers)
PerformHttpRequest('https://raw.githubusercontent.com/jimathy/jim_bridge/master/version.txt', function(err, body, headers)
if not body then
print("^1Unable to run version check for ^7'^3jim_bridge^7' (^3"..currentVersionRaw.."^7)")
return
end
local lines = {}
for line in body:gmatch("[^\r\n]+") do
table.insert(lines, line)
end
local newestVersionRaw = lines[1] or "0.0.0"
local changelog = {}
for i = 2, #lines do
table.insert(changelog, lines[i])
end
local compareResult = compareVersions(currentVersionRaw, newestVersionRaw)
if compareResult == 0 then
print("^7'^3jim_bridge^7' - ^2You are running the latest version^7. ^7(^3"..currentVersionRaw.."^7)")
elseif compareResult < 0 then
print("^1----------------------------------------------------------------------^7")
print("^7'^3jim_bridge^7' - ^1You are running an outdated version^7! ^7(^3"..currentVersionRaw.."^7 → ^3"..newestVersionRaw.."^7)")
for _, line in ipairs(changelog) do
print((line:find("http") and "^7" or "^5")..line)
end
print("^1----------------------------------------------------------------------^7")
SetTimeout(1200000, function()
CheckBridgeVersion()
end)
else
print("^7'^3jim_bridge^7' - ^5You are running a newer version ^7(^3"..currentVersionRaw.."^7 ← ^3"..newestVersionRaw.."^7)")
end
end)
end)
end
end
CheckBridgeVersion()

View File

@@ -0,0 +1,58 @@
## Animal Ped Support
### isAnimal.lua
This module provides logic to detect if a Ped or model is an animal and classify it into specific categories (cat, dog, coyote, etc.). Useful for wildlife, animal roles, or pet systems.
❔At player load in, it attempts to get what kind of ped/animal you are but there are functions to double check in scripts
❔Alot of this is used to determine what models/animations are available
Global flags:
- `isCat`, `isDog`, `isBigDog`, `isSmallDog`, `isCoyote`, `isAnimal` — used to store classification of the player's current ped.
- **isPedAnimal(ped?)**
- Checks if a ped is an animal based on predefined animal models.
- Sets global `isAnimal` to true if matched.
- **Example:**
```lua
local isPlayerAnimal = isPedAnimal()
local isOtherPedAnimal = isPedAnimal(GetPedInVehicleSeat(vehicle, -1))
```
- **isCat(ped)**
- Returns true if the ped model matches a cat.
- **Example:**
```lua
if isCat() then print("You're a cat!") end
```
- **isDog(ped)**
- Returns two values:
- `true`, `true` — if ped is a big dog
- `true`, `false` — if ped is a small dog
- `false`, `nil` — if not a dog
- **Example:**
```lua
local isDog, isBig = isDog()
if isDog then print(isBig and "Big Dog" or "Small Dog") end
```
- **getAnimalModels()**
- Returns a flat list of all registered animal model hashes.
- Can be used to check ped models against
- **Example:**
```lua
for _, model in pairs(getAnimalModels()) do print(model) end
```
- **getAnimalAnims(ped)**
- Returns the animation set defined for the given animal model.
- **Example:**
```lua
local anims = getAnimalAnims(PlayerPedId())
if anims then playAnim(anims.sitDict, anims.sitAnim) end
```

View File

@@ -0,0 +1,177 @@
### helpers.lua
This utility module provides functions for resource checks, debugging, formatting, coordinate math, vector calculations, progress bars, and drawing tools.
- **isStarted(script)**
- Returns `true` if a resource is started.
- **Example:**
```lua
if isStarted("myResource") then print("Resource is running") end
```
- **getScript()**
- Caches and returns the name of the current resource.
- Easier than typing `GetCurrentResourceName()` over and over
- **Example:**
```lua
print("Current script:", getScript())
```
- **isServer()**
- Returns true if running on the server.
- This was mainly made becuase `IsDuplicityVersion()` kept confusing me
- **Example:**
```lua
if isServer() then print("Server-side!") end
```
- **debugPrint(...)** / **eventPrint(...)**
- Prints messages with debug context if debugMode is enabled.
- **Example:**
```lua
debugPrint("Loaded object:", objName)
```
- **jsonPrint(table)**
- Pretty-prints a table with colorized JSON if debugMode is enabled.
- **Example:**
```lua
jsonPrint(myData)
```
- **keyGen()**
- Generates a 3-character unique ID.
- Good grabbing randomly generated strings
- **Example:**
```lua
print("Generated Key:", keyGen())
```
- **cv(amount)**
- Comma-separates a number (e.g., `1000000` to `1,000,000`).
- **Example:**
```lua
print(cv(1000000)) -- "1,000,000"
```
- **formatCoord(vec)**
- Outputs a formatted string from vector types.
- Compacts and adds console colours to the vector to be printed
- **Example:**
```lua
print(formatCoord(vector3(123.45, 678.9, 10.0)))
```
- **getCenterOfZones(coords)**
- Returns average center position of a vector3 list.
- A few use cases, but I used it to see how well spaced blips were together
- **Example:**
```lua
local center = getCenterOfZones({vector3(0,0,0), vector3(10,10,0)})
```
- **countTable(tbl)**
- Returns the number of entries in a table.
- Simple function to print how many "entires" are in a table
- **Example:**
```lua
print(countTable({a=1,b=2,c=3})) -- 3
```
- **pairsByKeys(tbl)**
- Iterator for sorted keys.
- **Example:**
```lua
for k, v in pairsByKeys(myTable) do print(k, v) end
```
- **concatenateText(tbl)**
- Joins string table entries with newlines.
- **Example:**
```lua
print(concatenateText({"Line 1", "Line 2"}))
```
- **RotationToDirection(rot)**
- Converts a heading vector to a directional vector.
- **Example:**
```lua
local dir = RotationToDirection(rotation)
```
- **basicBar(percent)**
- Returns a bar like `████░░░░░` at 50%.
- Basically a progress bar but as a string, I use this in drawTexts when progressbars aren't able to be used
- **Example:**
```lua
print(basicBar(50))
```
- **normalizeVector(vec)**
- Returns a normalized version of a vector3.
- **Example:**
```lua
local norm = normalizeVector(vector3(3,4,0))
```
- **drawLine(start, end, color)** / **drawSphere(pos, color)**
- Debug drawing helpers.
- Stays visible for more than one frame
- **Example:**
```lua
drawLine(vector3(0,0,0), vector3(10,10,10), vector4(255,0,0,255))
drawSphere(vector3(5,5,5), vector4(0,255,0,255))
```
- **PerformRaycast(start, end, entity?, flags?)**
- Raycast with material detection. Returns ray hit data.
- **Example:**
```lua
local hit, hitPos, material = PerformRaycast(startVec, endVec, playerPed, 1)
if hit == 1 then
print("Hit at position:", hitPos)
print("Material:", material)
end
```
- **adjustForGround(coords)**
- Adjusts a z-coordinate to ground height.
- **Example:**
```lua
coords = adjustForGround(vector3(100, 200, 300))
```
- **ensureNetToVeh(id)** / **ensureNetToEnt(id)**
- Resolves net ID to entity safely.
- **Example:**
```lua
local veh = ensureNetToVeh(netId)
```
- **sendLog(text)** / **sendServerLog(data)**
- Logging helpers, includes player name, coords, script source.
- **Example:**
```lua
sendLog("Suspicious activity detected")
```
- **GetGroundMaterialAtPosition(coords)**
- Returns the material hash + readable name from the surface below coords.
- **Example:**
```lua
local hash, name = GetGroundMaterialAtPosition(vector3(0,0,0))
```
- **GetPropDimensions(model)**
- Loads a model and returns width, depth, height.
- I use this to parse a model to create a box target instead of entity target when creating distProps/distPeds
- **Example:**
```lua
local w,d,h = GetPropDimensions("prop_barrel_01a")
```
- **GetEntityForwardVector(entity)**
- Returns the forward direction vector based on entity heading.
- **Example:**
```lua
local fwd = GetEntityForwardVector(PlayerPedId())
```

View File

@@ -0,0 +1,89 @@
### loaders.lua
This module provides loading utilities for common asset types such as models, animations, texture dictionaries, and audio banks. It also provides animation and sound helpers.
- **loadModel(model)**
- Loads a model into memory if valid and not already loaded.
- **Example:**
```lua
loadModel('prop_chair_01a')
```
- **unloadModel(model)**
- Unloads a model from memory.
- **Example:**
```lua
unloadModel('prop_chair_01a')
```
- **loadAnimDict(animDict)**
- Loads an animation dictionary into memory.
- **Example:**
```lua
loadAnimDict('amb@world_human_hang_out_street@male_c@base')
```
- **unloadAnimDict(animDict)**
- Removes an animation dictionary from memory.
- **Example:**
```lua
unloadAnimDict('amb@world_human_hang_out_street@male_c@base')
```
- **loadPtfxDict(ptFxName)**
- Loads a particle effect (ptfx) dictionary.
- **Example:**
```lua
loadPtfxDict('core')
```
- **unloadPtfxDict(dict)**
- Unloads a particle effect dictionary from memory.
- **Example:**
```lua
unloadPtfxDict('core')
```
- **loadTextureDict(dict)**
- Loads a streamed texture dictionary.
- **Example:**
```lua
loadTextureDict('commonmenu')
```
- **loadScriptBank(bank)**
- Loads a script audio bank.
- Returns true on success.
- **Example:**
```lua
local success = loadScriptBank('DLC_HEISTS_GENERAL_FRONTEND_SOUNDS')
```
- **loadAmbientBank(bank)**
- Loads an ambient audio bank.
- Returns true on success.
- **Example:**
```lua
local success = loadAmbientBank('AMB_REVERB_GENERIC')
```
- **playAnim(animDict, animName, duration?, flag?, ped?, speed?)**
- Plays an animation on a ped.
- Loads the dictionary if not already loaded.
- **Example:**
```lua
playAnim('amb@world_human_hang_out_street@male_c@base', 'base', 5000, 1, PlayerPedId(), 1.0)
```
- **stopAnim(animDict, animName, ped?)**
- Stops an animation and unloads the dictionary.
- **Example:**
```lua
stopAnim('amb@world_human_hang_out_street@male_c@base', 'base', PlayerPedId())
```
- **playGameSound(audioBank, soundSet, soundRef, coords, synced, range?)**
- Plays a game sound from a coordinate or entity.
- **Example:**
```lua
playGameSound('DLC_HEIST_HACKING_SNAKE_SOUNDS', 'Beep', vector3(0, 0, 0), false, 15.0)
```

View File

@@ -0,0 +1,38 @@
### callback.lua
These functions wrap the native callback handling of the selected framework (e.g., OX, QBCore, ESX) instead of implementing a standalone callback system, ensuring full compatibility.
- **createCallback(callbackName, funct)**
- Registers a callback function with the appropriate framework.
- This function checks which framework is started (e.g., OX, QB, ESX) and registers the callback accordingly.
- It adapts the callback function to match the expected signature for the framework.
- **Example:**
```lua
local table = { ["info"] = "HI" }
createCallback('myCallback', function(source, ...)
return table
end)
createCallback("callback:checkVehicleOwned", function(source, plate)
local result = isVehicleOwned(plate)
if result then
return true
else
return false
end
end)
```
- **triggerCallback(callbackName, ...)**
- Triggers a server callback and returns the result.
- This function uses the appropriate framework's method to call the server-side callback and awaits the result.
- **Example:**
```lua
local result = triggerCallback('myCallback')
jsonPrint(result)
local result = triggerCallback("callback:checkVehicleOwned", plate)
print(result)
```

View File

@@ -0,0 +1,28 @@
### cameras.lua
This module provides utilities for managing temporary in-game cameras, useful for cutscenes, cinematic views, or scripted perspectives.
- **createTempCam(ent, coords)**
- Creates a temporary camera at the specified coordinates or relative to an entity.
- If `ent` is an entity, the camera position is calculated as an offset from the entity's position using `GetOffsetFromEntityInWorldCoords`.
- If `ent` is a `vector3`, it is used directly as the camera's position.
- **Example:**
```lua
local cam = createTempCam(PlayerPedId(), GetEntityCoords(PlayerPedId()) + vector3(0, 2.0, 1.0))
```
- **startTempCam(cam)**
- Activates and renders the temporary camera.
- **Example:**
```lua
startTempCam(cam)
```
- **stopTempCam()**
- Deactivates and deletes all currently running custom camera, restoring normal view.
- **Example:**
```lua
stopTempCam()
```

View File

@@ -0,0 +1,45 @@
### contextmenus.lua
These functions provide a unified way to interact with different context menu systems, such as OX and WarMenu, depending on what's available on the server.
- **openMenu(Menu, data)**
- Opens a context menu using the preferred menu system.
- Automatically selects between supported systems like OX or WarMenu based on availability.
- The `Menu` parameter should be a list of menu entries, and the `data` parameter can be used to set headers, subtexts, and actions like `onBack`, `onExit`, and `canClose`.
- **Example:**
```lua
openMenu({
{ header = "Option 1", txt = "Description 1", onSelect = function() print("Option 1 selected") end },
{ header = "Option 2", txt = "Description 2", onSelect = function() print("Option 2 selected") end },
}, {
header = "Main Menu",
headertxt = "Select an option",
onBack = function() print("Return selected") end,
onExit = function() print("Menu closed") end,
canClose = true,
})
```
- **isOx()**
- Checks whether the OX context menu system is available on the server.
- Allows to do specific things if ox_lib menu is in use
- **Example:**
```lua
if isOx() then
print("OX Context Menu is available")
end
```
- **isWarMenuOpen()**
- Returns whether WarMenu is currently open.
- Useful to prevent opening a new menu if one is already active.
- **Example:**
```lua
if not isWarMenuOpen() then
openMenu("main_menu", menuData)
end
```
- Returns whether the WarMenu is currently open.

View File

@@ -0,0 +1,39 @@
### crafting.lua
These functions support crafting logic, such as opening crafting menus, handling multi-craft operations, and creating item data from recipes.
- **craftingMenu(data)**
- Opens a menu for selecting the quantity to craft.
- Presents the player with multiple crafting quantities based on `Config.Crafting.MultiCraftAmounts`.
- **Parameters:**
- `item` (`string`): The item to craft.
- `craft` (`table`): The crafting recipe.
- `craftable` (`table`): Crafting options.
- `coords` (`vector3`): Where crafting occurs.
- `stashName` (`string`): The stash name(s) for item availability.
- `onBack` (`function`): Callback when returning.
- `metadata` (`table`, optional): Metadata for the crafted item.
- **Example:**
```lua
craftingMenu({
craftable = {
Header = "Weapon Crafting",
Recipes = {
[1] = {
["weapon_pistol"] = { ["steel"] = 5, ["plastic"] = 2 },
amount = 1,
},
-- More recipes...
},
Anims = {
animDict = "amb@prop_human_parking_meter@male@idle_a",
anim = "idle_a",
},
},
coords = vector3(100.0, 200.0, 300.0),
stashTable = "crafting_stash",
job = "mechanic",
onBack = function() print("Returning to previous menu") end,
})
```

View File

@@ -0,0 +1,25 @@
### drawText.lua
These functions handle drawing and hiding styled on-screen prompts or UI overlays, compatible with different styling frameworks such as OX Lib.
- **drawText(image, input, style, oxStyleTable)**
- Displays styled text or prompts on screen.
- Designed to adapt styling depending on which UI system (e.g., OX) is in use.
- **Parameters:**
- `image` (`string`): Optional icon or image path.
- `input` (`string`): The main text to display.
- `style` (`string|table`): Preset or custom styling.
- `oxStyleTable` (`table`, optional): Extended style options if using OX UI.
- **Example:**
```lua
drawText("img_link", { "Test line 1", "Test Line 2" }, "~g~")
```
- **hideText()**
- Hides any active text or UI element previously drawn with `drawText()`.
- **Example:**
```lua
hideText()
```

View File

@@ -0,0 +1,31 @@
### duifunctions.lua
These functions support dynamic UI image rendering in 3D environments using runtime texture dictionaries. Ideal for integrating `nui://` or external `http://` image URLs into MLOs or world props.
- **createDui(name, http, size, txd))**
- Sets up a runtime texture dictionary and links an image from a `nui://` or `http://` URL.
- This function should be used once to create the texture dictionary needed for rendering Dui images.
- **Example:**
```lua
createDui("logo", "https://example.com/logo.png", { x = 512, y = 256 }, scriptTxd)
```
- **DuiSelect(data)**
- Updates the URL on an existing texture dictionary to change the rendered image.
- Can be used at runtime to swap out visuals in MLOs or props.
- **Parameters:**
- `textureDict` (`string`): The texture dictionary to target.
- `texture` (`string`): The specific texture name to override.
- `url` (`string`): The new image URL.
- `width`, `height` (`number`): The texture resolution.
- **Example:**
```lua
DuiSelect({
name = "logo",
texn = "logoTex",
texd = "someTxd",
size = { x = 512, y = 256 }
})
```

View File

@@ -0,0 +1,25 @@
### input.lua
This function displays a customizable input dialog for user text or number entry. It supports both simple and complex input structures.
- **createInput(title, opts)**
- Opens a styled input dialog with configurable fields, labels, input types, and validation.
- Supports multiple field types including `text`, `number`, `password`, `checkbox`, `color`, `slider`, and more.
- **Parameters:**
- `title` (`string`): Title displayed at the top of the input box.
- `opts` (`table`): A table of fields with attributes like `label`, `name`, `type`, `value`, and more.
- **Example:**
```lua
local userInput = createInput("Enter Details", {
{ type = "text", text = "Name", name = "playerName", isRequired = true },
{ type = "number", text = "Age", name = "playerAge", min = 18, max = 99 },
{ type = "radio", label = "Gender", name = "playerGender", options = {
{ text = "Male", value = "male" },
{ text = "Female", value = "female" },
{ text = "Other", value = "other" },
}},
})
if userInput then
print(json.encode(userInput))
end
```

View File

@@ -0,0 +1,144 @@
### inventories.lua
These functions manage inventory locking, item checking, and player inventory retrieval.
- **lockInv(toggle)**
- Locks or unlocks the player's inventory.
- Freezes/unfreezes movement and toggles hotbar state.
- **Example:**
```lua
lockInv(true) -- Lock inventory
lockInv(false) -- Unlock inventory
```
- **hasItem(items, amount, src)**
- Checks if a player has the specified item(s) in sufficient quantity.
- **Returns:**
- `boolean`: Whether the player has the item(s).
- `table`: Details of available item counts.
- **Example:**
```lua
local hasAll, details = hasItem({"health_potion", "mana_potion"}, 2, playerId)
if hasAll then
-- Proceed with action
else
-- Inform the player about missing items
end
```
- **getPlayerInv(src)**
- Retrieves the players current inventory.
- May be used for inventory UI, logging, or crafting systems.
- **Example:**
```lua
local inventory = getPlayerInv(playerId)
for k, item in pairs(inventory) do
print(item.name, item.amount)
end
```
### itemcontrol.lua
This module includes a variety of utility functions for managing items in player inventories, including giving, removing, durability, and use logic.
- **createUseableItem(item, funct)**
⚠️ This doesn't work for `ox_inv`, you will need to add the event info to it's `items.lua`
- Registers a useable item and binds it to a callback function.
- **Example:**
```lua
createUseableItem("bandage", function(source)
-- Heal logic here
end)
```
- **invImg(item)**
- Returns the inventory image path for an item.
- Automatically grabs the inventory image link based on inventory script
- **Example:**
```lua
local imagePath = invImg("water_bottle")
print(imagePath)
```
- **addItem(item, amount, info, src)**
⚠️ Requires Auth callback if called from client side
- Adds a specific amount of an item to a player's inventory.
- Automatically attempts to add items using detected inventory script
- **Example:**
```lua
-- Client Side
addItem("lockpick", 3, {})
-- Server Side
addItem("lockpick", 3, {}, source)
```
- **removeItem(item, amount, src, slot)**
- Removes a specific amount of an item from a players inventory.
- Automatically attempts to remove item using detected inventory script
- **Example:**
```lua
-- Client Side
removeItem(
"ammo_pistol",
30,
nil,
slot --[[optional]]--
)
-- Server Side
removeItem(
"ammo_pistol",
30,
source,
slot --[[optional]]--
)
```
- **dupeWarn(src, item, amount)**
- Logs or handles a potential duplication exploit involving an item.
- This is called automatically if a player has been triggered exploit detection
- Disabled if debugMode is enabled
- **breakTool(data)**
- Breaks a tool or item, often due to exceeding durability.
- **Example:**
```lua
breakTool({ item = "drill", damage = 10 })
```
- **getDurability(item)**
- Returns the current durability value of a given item.
- Searched for the lowest slot number (eg. slot 1) and retreives that items durability
- **Example:**
```lua
local durability, slot = getDurability("drill")
if durability then
print("Durability:", durability)
print("Slot:", slot)
end
```
- **canCarry(itemTable, src)**
⚠️ Currently server side only
- Checks if a player can carry the item(s) specified in `itemTable`.
- **Example:**
```lua
local carryCheck = canCarry({ ["health_potion"] = 2, ["mana_potion"] = 3 }, playerId)
if carryCheck["health_potion"] and carryCheck["mana_potion"] then
-- Player can carry items.
else
-- Notify player.
end
```

View File

@@ -0,0 +1,64 @@
### jobfunctions.lua
This module provides functions for managing job-based logic, such as checking player roles, toggling duty status, and simulating job-related interactions.
- **makeBossRoles(role)**
- Sets up boss-level permissions or access for the specified job role.
- Often used to determine if a player can access job menus or perform administrative actions.
- Used mainly for creating boss locked target tables
- **Example:**
```lua
makeBossRoles("police")
```
- **jobCheck(job)**
- Simple check if the player has the specified job.
- **Example:**
```lua
if jobCheck("mechanic") then
-- Allow mechanic features.
else
-- Deny access.
end
```
- **toggleDuty()**
- Toggles the players on/off duty status, typically used for jobs like police, EMS, etc.
- **Example:**
```lua
toggleDuty()
```
- **washHands(data)**
- Simulates the action of washing hands, used in job scripts or medical job logic.
- Currently only animation and a notfication
- **Example:**
```lua
washHands({ coords = vector3(200.0, 300.0, 40.0) })
```
- **useToilet(data)**
- Triggers toilet-use interaction, likely includes animation or sound.
- Currently only animation and a notfication
- **Example:**
```lua
useToilet({ urinal = true })
-- Player uses a urinal with corresponding animations and notifications
useToilet({ urinal = false, sitcoords = vector4(215.76, -810.12, 29.73, 90.0) })
-- Player sits down to use a toilet with corresponding animations and notifications
```
- **useDoor(data)**
- Handles interactions with doors that aren't openable and teleports the player
- eg. Recycle Center, it's used to teleport the player from outside a building to the IPL
- **Example:**
```lua
useDoor({ telecoords = vector4(215.76, -810.12, 29.73, 90.0) })
```

View File

@@ -0,0 +1,156 @@
### makeBlip.lua
This module provides simple utilities for adding static or entity-based blips to the minimap.
❔ This has basic support for RedM too
- **makeBlip(data)**
- This function adds a map blip at the provided coordinates and sets various display properties such as sprite, color, scale, and more.
- It also handles attaching a preview image to the blip if certain resources are running and a preview is provided.
- **Example:**
```lua
local blipData = {
coords = vector3(123.4, 567.8, 90.1),
sprite = 1,
col = 2,
scale = 0.8,
disp = 4,
category = 7,
name = "My Blip",
preview = "http://example.com/preview.png"
}
local blip = makeBlip(blipData)
```
- **makeEntityBlip(data)**
- This function adds a map blip attached to the provided entity and sets various display properties such as sprite, color, scale, and more.
- It also handles attaching a preview image to the blip if certain resources are running and a preview is provided.
- **Example:**
```lua
local blipData = {
entity = myEntity,
sprite = 1,
col = 2,
scale = 0.8,
disp = 4,
category = 7,
name = "Entity Blip",
preview = "http://example.com/preview.png"
}
local blip = makeEntityBlip(blipData)
```
### makePed.lua
This module provides tools to create persistent or distance-based NPCs with optional animations, scenarios, and config randomization.
- **makeDistPed(data, coords, freeze, collision, scenario, anim, synced)**
- Creates a ped that only spawns when nearby (performance optimization).
- **Example:**
```lua
makeDistPed({model = "a_m_y_business_03" }, -- model data
vector4(450.0, -980.0, 30.0, 100.0), -- coords
true, -- freeze entity
false, -- collision
'WORLD_HUMAN_STAND_IMPATIENT', -- Scenario Animation
{ dict = "amb@world_human_clipboard@male@idle_a", anim = "idle_c" }, -- Anim Table
true -- Network Synced
)
```
- **makePed(data, coords, freeze, collision, scenario, anim, synced)**
- Spawns a ped with more persistent behavior at the given location.
- Supports animation playback and freezing.
- **Example:**
```lua
makePed({model = "a_m_y_business_03" }, -- model data
vector4(450.0, -980.0, 30.0, 100.0), -- coords
true, -- freeze entity
false, -- collision
'WORLD_HUMAN_STAND_IMPATIENT', -- Scenario Animation
{ dict = "amb@world_human_clipboard@male@idle_a", anim = "idle_c" }, -- Anim Table
true -- Network Synced
)
```
- **GenerateRandomPedData(data)**
- Returns randomized ped model/configuration based on input table.
- Useful for dynamic NPC generation.
- **Example:**
```lua
local pedData = GenerateRandomPedData({ model = `MP_M_Freemode_01`, custom = {} })
```
### makeProp.lua
This module allows you to spawn static or distance-loaded props in the world.
- **makeProp(data, freeze, synced)**
- This function loads the model, creates the object, sets its heading, and freezes it if specified.
- **Example:**
```lua
local propData = {
prop = 'prop_chair_01a',
coords = vector4(123.4, 567.8, 90.1, 180.0)
}
local prop = makeProp(propData, true, false)
```
- **makeDistProp(data, freeze, synced, range)**
- Same as `makeProp`, but only spawns if the player is within the specified range.
- **Example:**
```lua
local propData = {
prop = 'prop_chair_01a',
coords = vector4(123.4, 567.8, 90.1, 180.0)
}
makeDistProp(propData, true, false)
```
- **destroyProp(entity)**
- Removes a previously created or targeted prop from the world.
- **Example:**
```lua
destroyProp(barrel)
```
### makeVeh.lua
This module provides functionality for spawning vehicles, including distance-based optimization and entity management.
- **makeVeh(model, coords)**
- This function loads the vehicle model, creates the vehicle in the world at the given coordinates, sets initial properties, and returns the vehicle handle.
- **Example:**
```lua
local vehicle = makeVeh("adder", vector3(250.0, -1000.0, 30.0))
```
- **makeDistVehicle(data, radius, onEnter, onExit)**
- Creates a vehicle that spawns when the player enters a designated polyzone area.
- This is used for `jim-parking` to create a static vehicle that can't move
- **Example:**
```lua
makeDistVehicle({
model = "blista",
coords = vector3(400.0, -800.0, 30.0),
heading = 180.0
}, 50.0)
```
- **removeDistVehicleZone(zoneId)**
- Removes a previously created distance-based vehicle zone.
- **Example:**
```lua
removeDistVehicleZone("garage_zone_1")
```
- **deleteVehicle(vehicle)**
- Deletes a specified vehicle entity.
- **Example:**
```lua
deleteVehicle(vehicle)
```

View File

@@ -0,0 +1,32 @@
### metaHandlers.lua
This module provides access and control over player metadata, which is useful for storing temporary or persistent player-specific values like stats, states, or tags.
- **GetPlayer(source)**
⚠️ Server side only
- Retrieves the player object (as defined by the framework in use) from the given `source` ID.
- **Example:**
```lua
local player = GetPlayer(playerId)
```
- **GetMetadata(player, key)**
- Retrieves the value of a metadata field from the given player.
- If called client-side (player is nil), it triggers a server callback to retrieve metadata.
- **Example:**
```lua
local stress = GetMetadata(player, "stress")
print("Player stress level:", stress)
```
- **SetMetadata(player, key, value)**
⚠️ Server side only
- Updates or assigns a value to a specific metadata key for a player.
- The function updates the player's metadata using the active core export.
- **Example:**
```lua
SetMetadata(player, "stress", 0)
```

View File

@@ -0,0 +1,21 @@
### notify.lua
This module provides a unified interface to trigger styled notifications across supported frameworks.
- **triggerNotify(title, message, type, src)**
- Sends a notification to a player (or to the entire client if `src` is `nil`).
- The notification style is determined by `type` (e.g., `success`, `error`, `info`).
- **Parameters:**
- `title` (`string`): The title or header of the notification.
- `message` (`string`): The body or detail text.
- `type` (`string`): Type of message (e.g., "success", "error", "info").
- `src` (`number`, optional): Server ID of the player to notify (omit to notify locally).
- **Example:**
```lua
-- Client-side usage without specifying a player (shows to the current player)
triggerNotify("Success", "You have completed the task!", "success")
-- Server-side usage specifying a player by their server ID
triggerNotify("Alert", "You have been warned for misconduct.", "error", source)
```

View File

@@ -0,0 +1,21 @@
### phones.lua
This module allows you to send in-game mail/messages to player phones, depending on the phone system integrated (e.g., QB, NPWD).
- **sendPhoneMail(data)**
- Sends a mail message to a player's in-game phone app.
- Typically used to notify players about deliveries, missions, or reminders.
- **Parameters:**
- `data` (`table`): Must contain phone/mail system-compatible fields like `sender`, `subject`, `message`, and `receiver`.
- **Example:**
```lua
sendPhoneMail({
subject = "Welcome!",
sender = "Admin",
message = "Thank you for joining our server.",
actions = {
{ label = "Reply", action = replyFunction }
}
})
```

View File

@@ -0,0 +1,115 @@
### playerfunctions.lua
This module contains helper functions for manipulating player states, interactions, and utility checks.
- **instantLookEnt(ent, ent2)**
- Instantly turns an entity to face a target (entity or coordinates) without animation.
- **Example:**
```lua
instantLookEnt(nil, vector3(200.0, 300.0, 40.0))
instantLookEnt(ped1, ped2)
```
- **lookEnt(entity)**
- Makes the current player look toward the given entity.
- Usually called after when opening a menu or something similar to make the player visually face the location
- **Example:**
```lua
lookEnt(vector3(200.0, 300.0, 40.0))
lookEnt(pedEntity)
```
- **setThirst(src, thirst)**
⚠️ Server Side Only
- Sets the thirst level of a player.
- **Example:**
```lua
setThirst(source, 75)
```
- **setHunger(src, hunger)**
⚠️ Server Side Only
- Sets the hunger level of a player.
- **Example:**
```lua
setHunger(source, 50)
```
- **chargePlayer(cost, moneyType, newsrc)**
⚠️ Server Side Only
- Deducts money from a player of the specified type (`cash`, `bank`, etc).
- **Example:**
```lua
chargePlayer(100, "cash", source)
```
- **fundPlayer(fund, moneyType, newsrc)**
⚠️ Server Side Only
- Adds money to a player's balance of a given type.
- **Example:**
```lua
fundPlayer(250, "bank", source)
```
- **ConsumeSuccess(itemName, type, data)**
- Handles logic when an item is successfully consumed (e.g., food, drink, etc).
- Supports hunger and thirst info directly from table eg. `{ hunger = 10, thirst = 20 }`
- **Example:**
```lua
ConsumeSuccess("health_pack", "food", { hunger = 10 })
ConsumeSuccess("beer", "alcohol", { thirst = 20 })
```
- **hasJob(job, source, grade)**
- Checks if a player has a certain job and optionally checks for a specific grade.
- Similar to `jobCheck()` but also retrieves as much player job info as possible
- **Example:**
```lua
-- Check if the player has the 'police' job and is on duty
local hasPoliceJob, isOnDuty = hasJob("police")
if hasPoliceJob and isOnDuty then
-- Grant access to police-specific features
end
-- Check if a specific player has the 'gang_leader' job with at least grade 2
local hasGangLeaderJob, _ = hasJob("gang_leader", playerId, 2)
if hasGangLeaderJob then
-- Allow gang leader actions
end
```
- **getPlayer(source)**
- Retrieves basic player information (name, cash, bank, job, etc.) based on the active core/inventory system.
- Can be called server-side (passing a player source) or client-side (for current player).
- Called often in my scripts as its makes use of frameworks "GetPlayerData" etc.
- **Example:**
```lua
-- Get information for a specific player
local playerInfo = getPlayer(playerId)
print(playerInfo.name, playerInfo.cash, playerInfo.bank)
-- Get information for the current player (client-side)
local myInfo = getPlayer()
print(myInfo.name, myInfo.cash, myInfo.bank)
```
- **GetPlayersFromCoords(coords, radius)**
- Returns a list of players within a specified radius of a set of coordinates.
- **Example:**
```lua
local nearby = GetPlayersFromCoords(GetEntityCoords(PlayerPedId()), 10.0)
for _, playerId in pairs(nearby) do
print("Nearby player ID:", playerId)
end
```

View File

@@ -0,0 +1,44 @@
### polyZone.lua
This module provides helpers for creating and removing polygon or circular zones using PolyZone-compatible data structures.
- **createPoly(data)**
- Creates a polygonal zone using the detected polyzone library (ox_lib or PolyZone).
- Automatically checks which polyzone script is active. When using ox_lib, it converts the provided 2D points to 3D (setting a constant z value) and sets a thickness value.
- For PolyZone, it creates the zone and attaches onEnter and onExit callbacks for ease of use.
- **Example:**
```lua
createPoly({
name = 'testZone',
debug = true,
points = { vec2(100.0, 100.0), vec2(200.0, 100.0), vec2(200.0, 200.0), vec2(100.0, 200.0) },
onEnter = function() print("Entered Test Zone") end,
onExit = function() print("Exited Test Zone") end,
})
```
- **createCirclePoly(data)**
- When using ox_lib, it creates a sphere zone. For PolyZone, it creates a CircleZone and attaches onEnter and onExit callbacks.
- **Example:**
```lua
createCirclePoly({
name = 'circleZone',
coords = vector3(150.0, 150.0, 20.0),
radius = 50.0,
onEnter = function() print("Entered Circle Zone") end,
onExit = function() print("Exited Circle Zone") end,
})
```
- **removePolyZone(Location)**
- Removes a previously created polygon or circle zone by name.
- Detects the active polyzone library and calls the appropriate removal method.
- **Example:**
```lua
local zone = createPoly({...})
---
removePolyZone(zone)
```

View File

@@ -0,0 +1,23 @@
### progressBars.lua
This module provides a unified progress bar system compatible with various UI frameworks.
❔It also contains an experimental "Shared Progressbar" system which was created for things like "giving an item to another player"
- **progressBar(data)**
- Displays a progress bar using the current configured system (e.g., ox_lib, qb, etc).
- **Example:**
```lua
local success = progressBar({
label = "Processing...",
time = 5000,
dict = "amb@world_human_hang_out_street@female_hold_arm@base",
anim = "base",
flag = 49,
cancel = true,
})
if success then
print("Success!")
else
print("Cancelled")
end
```

View File

@@ -0,0 +1,24 @@
### scaleEntity.lua
This utility provides a simple interface to scale an entity (ped, object, vehicle) in the world.
⚠️ **Important:** Unless the model's collision is removed or modified, the scale will reset when interacted with by other entities (e.g., walking into it, driving over it).
- **scaleEntity(entity, scale)**
- Scales the specified entity by the given factor.
- **Parameters:**
- `entity` (`number`): Entity handle (ped, object, vehicle).
- `scale` (`number`): Scale factor (e.g., `1.0` is normal size, `0.5` is half size).
- **Example:**
```lua
scaleEntity(PlayerPedId(), 0.8) -- Shrinks player slightly
```
- **resetScale(entity)**
- Resets the entity's scale back to its original default.
- **Example:**
```lua
resetScale(PlayerPedId()) -- Return to default size
```

View File

@@ -0,0 +1,63 @@
### shops.lua
This module provides functions to open, sell to, and register in-game shops and markets.
- **sellMenu(data)**
- Opens a UI menu for selling items to a vendor or market system.
- A simple system for the ability to sell all of an item in a players inventory
- Good for money making eg. pawn shops
- **Example:**
```lua
sellMenu({
sellTable = {
Header = "Sell Items",
Items = {
["gold_ring"] = 100,
["diamond"] = 500,
},
},
ped = pedEntity,
onBack = function() print("Returning to previous menu") end,
})
```
- **sellAnim(data)**
- Plays an animation during the selling process for immersion.
- Used in sellMenu, but can be called externally if needed
- **Example:**
```lua
sellAnim({
item = "gold_ring",
price = 100,
ped = pedEntity,
onBack = function() print("Sold Items") end,
)
```
- **openShop(data)**
- Opens a shop interface for purchasing items.
- Checks job/gang restrictions, then uses the active inventory system to open the shop.
- **Example:**
```lua
openShop({
shop = "weapon_shop",
items = weaponShopItems,
coords = vector3(100.0, 200.0, 300.0),
job = "police",
})
```
- **registerShop(name, label, items, society)**
- Registers a named shop with associated items and an optional society for fund handling.
- Supports either OXInv or QBInv (with QBInvNew flag).
- **Example:**
```lua
registerShop("fishing_shop", "Bait & Tackle", {
{ item = "fishing_rod", price = 50 },
{ item = "bait", price = 5 }
}, "fishing_society")
```

View File

@@ -0,0 +1,16 @@
### skillcheck.lua
This module provides a UI-based skill check system, useful for crafting, hacking, or other interactive gameplay scenarios.
- **skillCheck()**
- Starts a skill check minigame sequence using the provided configuration.
- Configuration may define speed, difficulty, bar size, or success zones.
- **Example:**
```lua
if skillCheck() then
print("Success!")
else
print("Failed :(")
end
```

View File

@@ -0,0 +1,28 @@
### societybank.lua
This module handles financial operations for society accounts, typically used for jobs or organizations.
- **getSocietyAccount(society)**
- Retrieves the current balance for the specified society.
- **Example:**
```lua
local balance = getSocietyAccount("police")
print("Police account balance: $"..balance)
```
- **chargeSociety(society, amount)**
- Deducts a specified amount from the society's account.
- **Example:**
```lua
chargeSociety("police", 500)
```
- **fundSociety(society, amount)**
- Adds funds to a societys account.
- **Example:**
```lua
fundSociety("ambulance", 1200)
```

View File

@@ -0,0 +1,44 @@
### stashcontrol.lua
This module handles logic for interacting with stashes—shared inventories for crafting, jobs, or storage systems.
- **checkStashItem(stashes, itemTable)**
- Retrieves (or updates) a local stash cache entry with a timeout.
- **Example:**
```lua
local found, foundinStash = checkStashItem({"crafting_stash"}, { item = "steel", amount = 2 })
if found then print("Found item in "..foundInStash) end
```
- **openStash(data)**
- Opens a stash using the active inventory system.
- Checks for job or gang restrictions before opening the stash.
- **Example:**
```lua
openStash({
stash = "playerStash",
label = "Player Stash",
coords = vector3(100, 200, 30)
})
```
- **getStash(stashName)**
- Retrieves the stash data by name (usually used for querying contents).
- **Example:**
```lua
local items = getStash("playerStash")
for k, v in pairs(items) do
print(k)
end
```
- **stashRemoveItem(stashItems, stashName, items)**
- Removes specified items from a stash. Used during crafting or transfers.
- **Example:**
```lua
stashRemoveItem(currentItems, "playerStash", { iron = 2, wood = 5 })
```

View File

@@ -0,0 +1,108 @@
### targets.lua
⚠️ This module provides utility functions for adding and removing interaction targets with entities, models, zones, and coordinates. Supports common targeting frameworks like `ox_target`, `qb-target`, and more.
- **createEntityTarget(entity, opts, dist)**
- Adds interaction targets to a specific in-world entity.
- **Example:**
```lua
createEntityTarget(entityId, {
{
action = function()
openStorage()
end,
icon = "fas fa-box",
job = "police",
label = "Open Storage",
},
}, 2.0)
```
- **createBoxTarget(data, opts, dist)**
- Creates an interactable box zone with configurable options.
- **Example:**
```lua
createBoxTarget(
{
'storageBox',
vector3(100.0, 200.0, 30.0),
2.0,
2.0,
{
name = 'storageBox',
heading = 100.0,
debugPoly = true,
minZ = 27.0,
maxZ = 32.0,
},
},
{
{
action = function()
openStorage()
end,
icon = "fas fa-box",
job = "police",
label = "Open Storage",
},
}, 2.0)
```
- **createCircleTarget(data, opts, dist)**
- Creates an interactable circular zone.
- **Example:**
```lua
createCircleTarget({
name = 'centralPark',
coords = vector3(200.0, 300.0, 40.0),
radius = 50.0,
options = { debugPoly = false }
}, {
{ icon = "fas fa-tree", label = "Relax", action = relaxAction }
}, 2.0)
```
- **createModelTarget(models, opts, dist)**
- Adds interactions to all matching models globally.
- **Example:**
```lua
createModelTarget({ model1, model2 },
{
{
action = function()
openStorage()
end,
icon = "fas fa-box",
job = "police",
label = "Open Storage",
},
}, 2.0)
```
- **removeEntityTarget(entity)**
- Removes all targets linked to the specified entity.
- **Example:**
```lua
removeEntityTarget(vehicle)
```
- **removeZoneTarget(target)**
- Removes a named zone-based target.
- **Example:**
```lua
removeZoneTarget("shop_box")
```
- **removeModelTarget(model)**
- Removes interactions tied to a model globally.
- **Example:**
```lua
removeModelTarget("prop_vend_soda")
```

View File

@@ -0,0 +1,63 @@
### vehicles.lua
This module provides utilities for reading, modifying, and interacting with vehicle properties and positioning.
- **searchCar(vehicle)**
- Searches the 'Vehicles' table for a specific vehicle's details.
- If the vehicle differs from the last searched, it retrieves its model and updates the carInfo table.
- The table includes the vehicle's name, price, and class information.
- **Example:**
```lua
local info = searchCar(vehicleEntity)
print(info.name, info.price, info.class.name, info.class.index)
```
- **getVehicleProperties(vehicle)**
- Retrieves the properties of a given vehicle using the active framework.
- **Example:**
```lua
local props = getVehicleProperties(vehicle)
if props then
print(json.encode(props))
end
```
- **setVehicleProperties(vehicle, props)**
- Sets the properties of a given vehicle if changes are detected.
- It compares the current properties with the new ones and applies the update using the active framework.
- **Example:**
```lua
setVehicleProperties(vehicle, props)
```
- **checkDifferences(vehicle, newProps)**
- Checks for differences between the current and new vehicle properties.
- Compares properties using JSON encoding for deep comparison and logs differences.
- **Example:**
```lua
if checkDifferences(vehicleEntity, newProperties) then
setVehicleProperties(vehicleEntity, newProperties)
end
```
- **pushVehicle(entity)**
- This function ensures that the vehicle is controlled by the current player and is set as a mission entity.
- It requests network control and sets the vehicle accordingly to synchronize changes across clients.
- **Example:**
```lua
pushVehicle(vehicle)
```
- **getClosestVehicle(coords, src)**
- Finds the closest vehicle to the specified coordinates.
- The function uses different APIs based on whether a source is provided.
- **Example:**
```lua
local closestVeh, distance = getClosestVehicle({ x = 100, y = 200, z = 30 }, source)
```

View File

@@ -0,0 +1,37 @@
### wrapperfunctions.lua
Provides wrapper compatibility functions for command and inventory stash systems across different frameworks (OX, QB, ESX, QS, etc).
- **registerCommand(command, options)**
⚠️ Server Side Only
- Registers a command using the appropriate framework's API.
- **Parameters:**
- `command`: Command name (string)
- `options`: Table including help, params, callback, autocomplete, restrictedGroup
- **Example:**
```lua
registerCommand("greet", {
"Greets the player",
{ name = "name", help = "Name of the player to greet" },
function(source, args) print("Hello, "..args[1].."!") end,
nil,
"admin"
})
```
- **registerStash(name, label, slots?, weight?, owner?, coords?)**
⚠️ Server Side Only
- Registers a stash using OX, QS, or Origen inventory systems.
- **Example:**
```lua
registerStash(
"playerStash",
"Player Stash",
100,
8000000,
"player123",
{ x = 100.0, y = 200.0, z = 30.0 }
)
```

129
documentation/scaleforms.md Normal file
View File

@@ -0,0 +1,129 @@
## Scaleforms
### debugScaleform.lua
This module renders debug text in-game when `debugMode` is enabled. Useful for live diagnostics or UI placement feedback.
- **debugScaleForm(textTable, loc)**
- Displays an overlay of lines of text at the specified screen location.
- **Note:** This only works if `debugMode` is set to `true`.
- **Parameters:**
- `textTable` (`table`): A list of strings to display.
- `loc` (`vector2`, optional): Top-left anchor point on screen (default: `vec2(0.05, 0.65)`).
- **Example:**
```lua
CreateThread(function()
while true do
debugScaleForm({
"Line 1: Debug info",
"Line 2: More info"
})
Wait(0)
end
end)
```
### instructionalButtons.lua
This module renders instructional button prompts using native scaleforms in GTA V and RedM.
⚠️ **Note:** Because it uses native scaleforms, it must be run inside a `while` loop to remain visible.
- **makeInstructionalButtons(info)**
- Draws instructional buttons using the GTA scaleform `instructional_buttons`.
- **Parameters:**
- `info` (`table`): An array of tables, where each entry contains:
- `keys` (`table`): Control key codes (e.g., `{38, 29}`).
- `text` (`string`): The label for the button.
- **Example:**
```lua
CreateThread(function()
while true do
makeInstructionalButtons({
{ keys = {38, 29}, text = "Open Menu" },
{ keys = {45}, text = "Close Menu" }
})
Wait(0)
end
end)
```
- **makeRedInstructionalButtons(info, title)**
- Experimental: Displays prompts using RedM-style `PromptSetGroup` API.
- **Note:** Still must be run in a loop for visibility.
- **Example:**
```lua
CreateThread(function()
while true do
makeRedInstructionalButtons({
{ keys = {0x760A9C6F}, text = "Mount Horse" },
{ keys = {0x4CC0E2FE}, text = "Dismount" }
}, "Horse Controls")
Wait(0)
end
end)
```
### scaleform_basic.lua
This module includes helper functions for 3D text rendering and UI overlays using basic native scaleform techniques.
- **DrawText3D(coord, text, highlight)**
- Draws 3D text in the world at the given coordinates, with optional highlight.
- Includes a semi-transparent black background box for visibility.
- **Parameters:**
- `coord` (`vector3`): World position to draw text.
- `text` (`string`): Text content.
- `highlight` (`boolean`, optional): Highlights `~w~` sections with yellow.
- **Example:**
```lua
CreateThread(function()
while true do
DrawText3D(vector3(100, 200, 300), "Hello World", true)
Wait(0)
end
end)
```
- **DisplayHelpMsg(text)**
- Shows a help message in the top-left corner of the screen.
- **Example:**
```lua
DisplayHelpMsg("Press E to interact")
```
- **displaySpinner(text)**
- Shows a busy spinner with a message (e.g., "Saving...").
- **Example:**
```lua
displaySpinner("Saving data...")
```
- **stopSpinner()**
- Hides any active busy spinner (client-only).
- **Example:**
```lua
stopSpinner()
```
### timerBars.lua
This module provides a native scaleform-based timer bar HUD. Ideal for displaying tasks, loading indicators, or time-sensitive objectives.
- **createTimerHud(title, data, alpha)**
⚠️ This was an attempt to recreate the gta native shooting ranges )fairly specific use case)
- Draws a timer bar with custom label and right-aligned values using the native GTA HUD system.
- **Parameters:**
- `title` (`string`): Title/header displayed on the bar.
- `data` (`table`): List of `label = value` entries to display (max 4 rows).
- `alpha` (`number`, optional): Opacity of the bar (0-255).
- **Example:**
```lua
CreateThread(function()
while true do
createTimerHud("Timer Bar", {
{ stat = "Health", value = "85%" },
{ stat = "Armor", value = "50%", multi = 2 },
{ stat = "Stamina", value = "100%" },
}, 180)
Wait(0)
end
end)
```

303
frameworkCache.lua Normal file
View File

@@ -0,0 +1,303 @@
--[[
Cached Resource Initialization Module
--------------------------------------
Initializes shared resource data (Items, Vehicles, Jobs, Gangs) once and caches it
to improve performance and reduce redundant data fetching across scripts.
]]
-- Define resource names used in different frameworks
local Exports = {
QBExport = "qb-core",
QBXExport = "qbx_core",
ESXExport = "es_extended",
OXCoreExport = "ox_core",
OXInv = "ox_inventory",
QBInv = "qb-inventory",
PSInv = "ps-inventory",
QSInv = "qs-inventory",
CoreInv = "core_inventory",
CodeMInv = "codem-inventory",
OrigenInv = "origen_inventory",
TgiannInv = "tgiann-inventory",
JPRInv = "jpr-inventory",
OXLibExport = "ox_lib",
QBMenuExport = "qb-menu",
QBTargetExport = "qb-target",
OXTargetExport = "ox_target",
-- REDM
RSGExport = "rsg-core",
RSGInv = "rsg-inventory"
}
-- Prevent reloading if cache is already initialized
if _G.__jimBridgeDataCache then return end
_G.__jimBridgeDataCache = {}
local cache = _G.__jimBridgeDataCache
-- Helper function to check if resource exists in server (instead of if it is already started)
local function checkExists(resourceName)
return GetResourceState(resourceName):find("start") or GetResourceState(resourceName):find("stopped")
end
-- Ensure oxmysql resource is loaded
local fileLoader = assert(load(LoadResourceFile("oxmysql", ('lib/MySQL.lua')), ('@@oxmysql/lib/MySQL.lua')))
fileLoader()
if checkExists(Exports.OXCoreExport) then
-- Detected OX_Core in server, wait for it to be started if needed
while GetResourceState(Exports.OXCoreExport) ~= "started" do Wait(100) end
local fileLoader = assert(load(LoadResourceFile(Exports.OXCoreExport, ('lib/init.lua')), ('@@'..Exports.OXCoreExport..'/lib/init.lua')))
fileLoader()
end
if checkExists(Exports.ESXExport) then
-- Detected ESX in server, wait for it to be started if needed
while GetResourceState(Exports.ESXExport) ~= "started" do Wait(100) end
local fileLoader = assert(load(LoadResourceFile(Exports.ESXExport, ('/imports.lua')), ('@@'..Exports.ESXExport..'/imports.lua')))
fileLoader()
end
-- Initialize variables for caching
local Items, Vehicles, Jobs, Gangs, Core = nil, nil, nil, nil, nil
local itemResource, jobResource, vehResource = "", "", ""
-- Print just to announce it knows the exports/scripts exist in the server
for _, v in pairs(Exports) do
if checkExists(v) then
print("^6Bridge^7: '^3"..v.."^7' detected")
end
end
---------------------
---- Load Items -----
---------------------
-- Items initialization based on detected inventory system
if checkExists(Exports.OXInv) then
-- Wait for OX Inventory to start if it's not already started
while GetResourceState(Exports.OXInv) ~= "started" do Wait(100) end
itemResource = Exports.OXInv
Items = exports[Exports.OXInv]:Items()
-- Get Weapon info and duplicate them if they are uppercase
-- (duplicate incase anything checks for the uppercase version)
for k, v in pairs(Items) do
if k:find("WEAPON") then
Items[k:lower()] = Items[k]
Items[k:lower()].image = k..".png"
end
Items[k].image = (v.client and v.client.image) and v.client.image:gsub("nui://"..Exports.OXInv.."/web/images/", "") or k..".png"
Items[k].hunger = v.client and v.client.hunger
Items[k].thirst = v.client and v.client.thirst
end
elseif checkExists(Exports.QBExport) then
while GetResourceState(Exports.QBExport) ~= "started" do Wait(100) end
itemResource = Exports.QBExport
Core = exports[Exports.QBExport]:GetCoreObject()
Items = Core.Shared.Items
if Items == nil then
print("^1ERROR^7: ^1Can NOT find shared ^7Items ^1table^7, ^1possible error in that file^7?")
Items = {} -- Fallback to an empty table
end
elseif checkExists(Exports.ESXExport) then
itemResource = Exports.ESXExport
if GetResourceState(Exports.QSInv):find("start") then
Items = exports[Exports.QSInv]:GetItemList()
else
Items = ESX.GetItems()
while not next(Items) do
Items = ESX.GetItems()
Wait(1000)
end
end
elseif checkExists(Exports.RSGExport) then
while GetResourceState(Exports.RSGExport) ~= "started" do Wait(100) end
itemResource = Exports.RSGExport
Core = exports[Exports.RSGExport]:GetCoreObject()
Items = Core.Shared.Items
if Items == nil then
print("^1ERROR^7: ^1Can NOT find shared ^7Items ^1table^7, ^1possible error in that file^7?")
Items = {} -- Fallback to an empty table
end
end
---------------------
--- Load Vehicles ---
---------------------
-- Vehicle loading depending on framework
if checkExists(Exports.QBXExport) or checkExists(Exports.QBExport) then
vehResource = Exports.QBExport
Core = Core or exports[Exports.QBExport]:GetCoreObject()
Vehicles = Core.Shared.Vehicles
if Vehicles == nil then
print("^1ERROR^7: ^1Can NOT find shared ^7Vehicles ^1table^7, ^1possible error in that file^7?")
Vehicles = {} -- Fallback to an empty table
end
elseif checkExists(Exports.OXCoreExport) then
vehResource = Exports.OXCoreExport
Vehicles = {}
for k, v in pairs(Ox.GetVehicleData()) do
Vehicles[k] = {
model = k, hash = GetHashKey(k),
price = v.price,
name = v.name,
brand = v.make
}
end
elseif checkExists(Exports.ESXExport) then
vehResource = Exports.ESXExport
while not MySQL do Wait(1000) end
Vehicles = {}
for _, v in pairs(MySQL.query.await('SELECT model, price, name FROM vehicles')) do
Vehicles[v.model] = {
model = v.model,
hash = GetHashKey(v.model),
price = v.price,
name = v.name,
}
end
elseif checkExists(Exports.RSGExport) then
vehResource = Exports.RSGExport
Core = Core or exports[Exports.RSGExport]:GetCoreObject()
Vehicles = Core.Shared.Vehicles
if Vehicles == nil then
print("^1ERROR^7: ^1Can NOT find shared ^7Vehicles ^1table^7, ^1possible error in that file^7?")
Vehicles = {} -- Fallback to an empty table
end
end
---------------------
----- Load Jobs -----
---------------------
-- Jobs loading based on framework
if checkExists(Exports.QBXExport) then
jobResource = Exports.QBXExport
Core = Core or exports[Exports.QBXExport]:GetCoreObject()
Jobs, Gangs = exports[Exports.QBXExport]:GetJobs(), exports[Exports.QBXExport]:GetGangs()
if Jobs == nil then
print("^1ERROR^7: ^1Can NOT find shared ^7Jobs ^1table^7, ^1possible error in that file^7?")
Jobs = {} -- Fallback to an empty table
end
elseif checkExists(Exports.OXCoreExport) then
jobResource = Exports.OXCoreExport
Jobs = {}
while not MySQL do Wait(1000) end
local tempJobs = MySQL.query.await('SELECT * FROM `ox_groups`')
local tempGrades = MySQL.query.await('SELECT * FROM `ox_group_grades`')
local gradeMap = {}
for _, grade in pairs(tempGrades) do
gradeMap[grade.group] = gradeMap[grade.group] or {}
gradeMap[grade.group][grade.grade] = { name = grade.label }
end
for _, job in pairs(tempJobs) do
Jobs[job.name] = {
label = job.label,
grades = gradeMap[job.name] or {}
}
end
Gangs = Jobs
elseif checkExists(Exports.QBExport) then
jobResource = Exports.QBExport
Core = Core or exports[Exports.QBExport]:GetCoreObject()
Jobs, Gangs = Core.Shared.Jobs, Core.Shared.Gangs
elseif checkExists(Exports.ESXExport) then
jobResource = Exports.ESXExport
ESX = exports[Exports.ESXExport]:getSharedObject()
Jobs = ESX.GetJobs()
while not next(Jobs) do
Wait(100)
Jobs = ESX.GetJobs()
end
for Role, Grades in pairs(Jobs) do
-- Check for if user has added grades
if Grades.grades == nil or not next(Grades.grades) then
goto continue
end
for grade, info in pairs(Grades.grades) do
if info.label and info.label:find("[Bb]oss") then
Jobs[Role].grades[grade].isBoss = true
goto continue
end
end
local highestGrade = nil
for k in pairs(Grades.grades) do
local num = tonumber(k)
if num and (not highestGrade or num > highestGrade) then
highestGrade = num
end
end
if highestGrade then
Jobs[Role].grades[tostring(highestGrade)].isBoss = true
end
::continue::
end
Gangs = Jobs
elseif checkExists(Exports.RSGExport) then
jobResource = Exports.RSGExport
Core = Core or exports[Exports.RSGExport]:GetCoreObject()
Jobs, Gangs = Core.Shared.Jobs, Core.Shared.Gangs
if Jobs == nil then
print("^1ERROR^7: ^1Can NOT find shared ^7Jobs ^1table^7, ^1possible error in that file^7?")
Jobs = {} -- Fallback to an empty table
end
end
-- Save to global cache
cache.Items = Items
cache.Vehicles = Vehicles
cache.Jobs = Jobs
cache.Gangs = Gangs
CreateThread(function()
local counts = {
Items = 0,
Vehicles = 0,
Jobs = 0,
Gangs = 0,
}
for k, v in pairs(cache) do
for count in pairs(v) do
counts[k] += 1
end
end
print("^6FrameworkCache^7: ^2Loaded ^5"..tostring(counts.Items).."^2 Items from ^7"..itemResource)
print("^6FrameworkCache^7: ^2Loaded ^5"..tostring(counts.Vehicles).."^2 Vehicles from ^7"..vehResource)
print("^6FrameworkCache^7: ^2Loaded ^5"..tostring(counts.Jobs).."^2 Jobs from ^7"..jobResource)
print("^6FrameworkCache^7: ^2Loaded ^5"..tostring(counts.Gangs).."^2 Gangs from ^7"..jobResource)
end)
RegisterNetEvent("jim_bridge:requestCache", function()
local src = source
TriggerClientEvent("jim_bridge:receiveCache", src, _G.__jimBridgeDataCache)
end)
exports("GetSharedData", function()
-- Wait for data to be ready before returning it
local timeout = GetGameTimer() + 5000
while (
not _G.__jimBridgeDataCache or
(not _G.__jimBridgeDataCache.Items or next(_G.__jimBridgeDataCache.Items) == nil) or
(not _G.__jimBridgeDataCache.Vehicles or next(_G.__jimBridgeDataCache.Vehicles) == nil) or
(not _G.__jimBridgeDataCache.Jobs or next(_G.__jimBridgeDataCache.Jobs) == nil)
) and GetGameTimer() < timeout do
Wait(50)
end
return _G.__jimBridgeDataCache
end)

View File

@@ -1,14 +1,26 @@
name "Jim_Bridge" name "Jim_Bridge"
author "Jimathy" author "Jimathy"
version "2.0" version "2.0.17"
description "Framework Bridge By Jimathy" description "Framework Bridge By Jimathy"
fx_version "cerulean" fx_version "cerulean"
game "gta5" rdr3_warning 'I acknowledge that this is a prerelease build of RedM, and I am aware my resources *will* become incompatible once RedM ships.'
games { 'gta5', 'rdr3' }
lua54 'yes' lua54 'yes'
files { files {
'starter.lua', 'starter.lua',
'shared/*.lua', 'shared/*.lua',
'shared/make/*.lua', 'shared/make/*.lua',
'shared/scaleforms/*.lua', 'shared/scaleforms/*.lua',
} }
-- Version checker
server_scripts {
'frameworkCache.lua',
'_versioncheck.lua'
}
client_scripts {
'ui_modules/*.lua'
}

View File

@@ -1,92 +1,138 @@
--- Executes a function when the player character is loaded into the game. --[[
--- Player & Resource Event Utility Functions
--- This function sets up event listeners for player loading based on the game framework detected (e.g., QB, ESX, OX). -------------------------------------------
--- This module provides functions to:
--- If `onStart` is `true`, it will also attempt to execute the function on resource start after ensuring the player is logged in. (Helpful for debugging) • Execute code when the player character is loaded or unloaded.
• Execute code on resource start and stop.
• Wait for the player to be logged in before proceeding.
]]
-------------------------------------------------------------
-- Player Loaded and Unloaded Events
-------------------------------------------------------------
--- Executes a function when the player character is loaded.
--- If onStart is true, the function will also run on resource start (after ensuring the player is logged in).
--- ---
--- @param func function The function to execute when the player is loaded. --- @param func function The function to execute when the player is loaded.
--- @param onStart boolean (optional) If `true`, the function will also execute on resource start. Default is `false`. --- @param onStart boolean (optional) If true, also execute on resource start. Default is false.
---
--- @usage --- @usage
--- ```lua --- ```lua
--- onPlayerLoaded(function() --- onPlayerLoaded(function()
--- -- Your code here --- print("Player logged in")
--- -- Your initialization code here.
--- end, true) --- end, true)
--- ``` --- ```
function onPlayerLoaded(func, onStart) function onPlayerLoaded(func, onStart)
local onPlayerName = "" local onPlayerFramework = ""
local loaded = false local loaded = false
if onStart then if onStart then
onResourceStart(function() onResourceStart(function()
if not LocalPlayer.state.isLoggedIn then if not waitForLogin() then return end
Wait(3000)
if not LocalPlayer.state.isLoggedIn then -- If the player is not logged in after waiting, skip execution loaded = true
return debugPrint("^6Bridge^7: ^3onResourceStart^7()^2 executed through ^3onPlayerLoaded^7()")
end
end
loaded = true -- Mark as already loaded
debugPrint("^6Bridge^7: ^2Loading ^3onResourceStart^7() ^2through ^3onPlayerLoaded^7()")
Wait(2000) Wait(2000)
func() func()
end, true) end, true)
end end
if not loaded then if not loaded then
local tempFunc = function() local tempFunc = function()
debugPrint("^6Bridge^7: ^2Executing ^3onPlayerLoaded^7()") Wait(2000)
debugPrint("^6Bridge^7: ^2Executing onPlayerLoaded")
func() func()
end end
if isStarted(QBExport) or isStarted(QBXExport) then onPlayerName = QBExport
if isStarted(QBExport) or isStarted(QBXExport) then
onPlayerFramework = QBExport
AddEventHandler('QBCore:Client:OnPlayerLoaded', tempFunc) AddEventHandler('QBCore:Client:OnPlayerLoaded', tempFunc)
elseif isStarted(ESXExport) then onPlayerName = ESXExport elseif isStarted(ESXExport) then
AddEventHandler('esx:playerLoaded', tempFunc) onPlayerFramework = ESXExport
elseif isStarted(OXCoreExport) then onPlayerName = OXCoreExport AddEventHandler('esx:playerLoaded', function()
AddEventHandler('ox:playerLoaded', tempFunc) if waitForSharedLoad() then
if isStarted(ESXExport) then Wait(1000) end
tempFunc()
end end
if onPlayerName ~= "" then end
debugPrint("^6Bridge^7: ^2Registering ^3onPlayerLoaded^2 with ^7"..onPlayerName) )
elseif isStarted(OXCoreExport) then
onPlayerFramework = OXCoreExport
AddEventHandler('ox:playerLoaded', tempFunc)
elseif isStarted(RSGExport) then
onPlayerFramework = RSGExport
AddEventHandler('RSGCore:Client:OnPlayerLoaded', tempFunc)
end
if onPlayerFramework ~= "" then
debugPrint("^6Bridge^7: ^2Registering ^3onPlayerLoaded^7()^2 with ^3" .. onPlayerFramework.."^7")
else else
print("^4ERROR^7: ^2No Core detected for onPlayerLoaded ^7- ^2Check ^3exports^1.^2lua^7") print("^4ERROR^7: No supported core detected for onPlayerLoaded - Check starter.lua")
end end
end end
end end
--- Executes a function when the player character is unloaded.
--- @param func function The function to execute when the player unloads.
--- @usage
--- ```lua
--- onPlayerUnload(function()
--- print("Player has logged out of their character")
--- -- Your cleanup code here.
--- end)
--- ```
function onPlayerUnload(func)
AddEventHandler('QBCore:Client:OnPlayerUnload', function() func() end)
AddEventHandler('ox:playerLogout', function() func() end)
AddEventHandler('RSGCore:Client:OnPlayerUnload', function() func() end)
--AddEventHandler('esx:playerLogout', function() func() end)
-- ^ Only server side for now, need a way to send it to client if not already available
end
-------------------------------------------------------------
-- Resource Start and Stop Events
-------------------------------------------------------------
--- Executes a function when the resource starts. --- Executes a function when the resource starts.
--- --- @param func function The function to execute.
--- This function wraps the `onResourceStart` event, allowing you to execute code when the resource starts. --- @param thisScript boolean (optional) If true, only runs when this resource starts (default true).
---
--- @param func function The function to execute on resource start.
--- @param thisScript boolean (optional) If `true`, only runs the function when this resource starts. Default is `true`.
---
--- @usage --- @usage
--- ```lua --- ```lua
--- onResourceStart(function() --- onResourceStart(function()
--- -- Your code here --- print("Script ensured")
--- -- Initialization code on resource start.
--- end, true) --- end, true)
--- ``` --- ```
local hasPrinted = false
function onResourceStart(func, thisScript) function onResourceStart(func, thisScript)
debugPrint("^6Bridge^7: ^2Registering ^3onResourceStart^2") debugPrint("^6Bridge^7: ^2Registering ^3onResourceStart^7()")
AddEventHandler('onResourceStart', function(resourceName) AddEventHandler('onResourceStart', function(resourceName)
if getScript() == resourceName and (thisScript or true) then if getScript() == resourceName and (thisScript or true) then
if waitForSharedLoad() then
if not hasPrinted then
debugPrint("^6Bridge^7: ^2Shared Load Detected^7.")
hasPrinted = true
end
if isStarted(ESXExport) then Wait(10000) end
func() func()
end end
end
end) end)
end end
--- Executes a function when the resource stops. --- Executes a function when the resource stops.
--- --- @param func function The function to execute.
--- This function wraps the `onResourceStop` event, allowing you to execute code when the resource stops. --- @param thisScript boolean (optional) If true, only runs when this resource stops (default true).
---
--- @param func function The function to execute on resource stop.
--- @param thisScript boolean (optional) If `true`, only runs the function when this resource stops. Default is `true`.
---
--- @usage --- @usage
--- ```lua --- ```lua
--- onResourceStop(function() --- onResourceStop(function()
--- -- Cleanup code here --- -- Cleanup code here.
--- end, true) --- end, true)
--- ``` --- ```
function onResourceStop(func, thisScript) function onResourceStop(func, thisScript)
debugPrint("^6Bridge^7: ^2Registering ^3onResourceStop^2") debugPrint("^6Bridge^7: ^2Registering ^3onResourceStop^7()")
AddEventHandler('onResourceStop', function(resourceName) AddEventHandler('onResourceStop', function(resourceName)
if getScript() == resourceName and (thisScript or true) then if getScript() == resourceName and (thisScript or true) then
func() func()
@@ -94,17 +140,90 @@ function onResourceStop(func, thisScript)
end) end)
end end
--- Waits until the player is logged in before continuing execution. -------------------------------------------------------------
--- -- Wait for Login
--- This function blocks execution until `LocalPlayer.state.isLoggedIn` is `true`. -------------------------------------------------------------
---
--- Blocks execution until the player is logged in.
--- @usage --- @usage
--- ```lua
--- waitForLogin() --- waitForLogin()
--- ```
function waitForLogin() function waitForLogin()
while not LocalPlayer.state.isLoggedIn do local timeout = 10000 -- 10 seconds in milliseconds
debugPrint("Waiting") local startTime = GetGameTimer()
local loggedIn = false
if isStarted(ESXExport) then
while (GetGameTimer() - startTime) < timeout do
local playerData = ESX.GetPlayerData()
if playerData and playerData.job then
loggedIn = true
break
end
Wait(100) Wait(100)
end end
elseif isStarted(OXCoreExport) then
if OxPlayer["stateId"] then
loggedIn = true
end
while not OxPlayer["stateId"] do
Wait(1000)
debugPrint("Waiting for stateId to class as logged in")
if OxPlayer.get["stateId"] then
loggedIn = true
break
end
end
else
-- For other frameworks, use LocalPlayer.state.isLoggedIn.
while not LocalPlayer.state.isLoggedIn and (GetGameTimer() - startTime) < timeout do
Wait(100)
end
loggedIn = LocalPlayer.state.isLoggedIn
end
if not loggedIn then
print("^4Error^7: ^2Timeout reached while waiting for player login^7.")
return false
else
debugPrint("^6Bridge^7: ^2Player Login Detected^7.")
return true
end
end
local messageShown = false
function waitForSharedLoad()
local timeout = 100000 -- 10 seconds in milliseconds
local startTime = GetGameTimer()
local loaded = true
--Wait(1000)
local count = {}
local loop = 0
while ((not Jobs or not next(Jobs)) and (not Items or not next(Items)) and (not Vehicles or not next(Vehicles))) and (GetGameTimer() - startTime) < timeout do
if not messageShown then
if (not Jobs or not next(Jobs)) then
debugPrint("^4Debug^7: ^2Waiting for Jobs to be loaded")
end
if (not Items or not next(Items)) then
debugPrint("^4Debug^7: ^2Waiting for Items to be loaded")
end
if (not Vehicles or not next(Vehicles)) then
debugPrint("^4Debug^7: ^2Waiting for Vehicles to be loaded")
end
end
messageShown = true
--print((GetGameTimer() - startTime) < timeout)
Wait(1000)
if Jobs and Items and Vehicles then
--print("^6Bridge^7: ^2Jobs, Items, and Vehicles Loaded^7.")
loaded = true
break
end
loop += 1
end
if not loaded then
print("^4Error^7: ^1Timeout reached while waiting for shared load^7.")
return false
else
return true
end
end end

View File

@@ -0,0 +1,100 @@
function parseVersion(version)
local parts = {}
for num in version:gmatch("%d+") do
table.insert(parts, tonumber(num))
end
return parts
end
function compareVersions(current, newest)
local currentParts = parseVersion(current)
local newestParts = parseVersion(newest)
for i = 1, math.max(#currentParts, #newestParts) do
local c = currentParts[i] or 0
local n = newestParts[i] or 0
if c < n then return -1
elseif c > n then return 1 end
end
return 0
end
function capitalize(str)
return (str:gsub("^%l", string.upper):gsub("%-%l", function(letter) return "-" .. string.upper(letter:sub(2)) end))
end
local scriptName = ("^2"..capitalize(getScript()):gsub("%-", "^7-^2"):gsub("%_", "^7_^2")) or ""
local scriptVersion = ("^5"..GetResourceMetadata(getScript(), 'version', nil):gsub("%.", "^7.^5")) or ""
local scriptDescription = ("^2"..GetResourceMetadata(getScript(), 'description', nil)) or ""
local scriptAuthor = ("^2by ^4"..GetResourceMetadata(getScript(), 'author', nil):gsub("%and", "^7and^4")) or ""
print(scriptName.." ^7v"..scriptVersion.."^7 - "..scriptDescription.." "..scriptAuthor.."^7")
function CheckVersion()
if isServer() and GetResourceMetadata(getScript(), 'author', nil) == "Jimathy" then
CreateThread(function()
Wait(4000)
local script = getScript()
local currentVersionRaw = GetResourceMetadata(script, 'version')
PerformHttpRequest('https://raw.githubusercontent.com/jimathy/UpdateVersions/master/'..script..'.txt', function(err, newestVersionRaw, headers)
if not newestVersionRaw then
-- fallback
PerformHttpRequest('https://raw.githubusercontent.com/jimathy/'..script..'/master/version.txt', function(err, fallbackVersionRaw, headers)
if not fallbackVersionRaw then
print("^1Currently unable to run a version check for ^7'^3"..script.."^7' (^3"..currentVersionRaw.."^7)")
return
end
local lines = {}
for line in fallbackVersionRaw:gmatch("[^\r\n]+") do table.insert(lines, line) end
local fallbackVersion = (lines[1] or "0.0.0"):gsub("v", "")
local changelog = {}
for i = 2, #lines do table.insert(changelog, lines[i]) end
local compareResult = compareVersions(currentVersionRaw, fallbackVersion)
if compareResult == 0 then
print("^7'^3"..script.."^7' - ^2You are running the latest version^7. (^3"..currentVersionRaw.."^7)")
elseif compareResult < 0 then
print("^1----------------------------------------------------------------------^7")
print("^7'^3"..script.."^7' - ^1You are currently running an outdated version^7! (^3"..currentVersionRaw.."^7 → ^3"..fallbackVersion.."^7)")
if #changelog > 0 then
for _, line in ipairs(changelog) do
print((line:find("http") and "^7" or "^5")..line)
end
end
print("^1----------------------------------------------------------------------^7")
SetTimeout(1200000, function() CheckVersion() end)
else
print("^7'^3"..script.."^7' - ^5You are running a newer version ^7(^3"..currentVersionRaw.."^7 ← ^3"..fallbackVersion.."^7)")
end
end)
else
local lines = {}
for line in newestVersionRaw:gmatch("[^\r\n]+") do table.insert(lines, line) end
local newestVersion = (lines[1] or "0.0.0"):gsub("v", "")
local changelog = {}
for i = 2, #lines do table.insert(changelog, lines[i]) end
local compareResult = compareVersions(currentVersionRaw, newestVersion)
if compareResult == 0 then
print("^7'^3"..script.."^7' - ^2You are running the latest version^7. (^3"..currentVersionRaw.."^7)")
elseif compareResult < 0 then
print("^1----------------------------------------------------------------------^7")
print("^7'^3"..script.."^7' - ^1You are currently running an outdated version^7! (^3"..currentVersionRaw.."^7 → ^3"..newestVersion.."^7)")
if #changelog > 0 then
for _, line in ipairs(changelog) do
print((line:find("http") and "^7" or "^5")..line)
end
end
print("^1----------------------------------------------------------------------^7")
SetTimeout(1200000, function() CheckVersion() end)
else
print("^7'^3"..script.."^7' - ^5You are running a newer version ^7(^3"..currentVersionRaw.."^7 ← ^3"..newestVersion.."^7)")
end
end
end)
end)
end
end
CheckVersion()

View File

@@ -8,11 +8,23 @@
--- ---
---@usage ---@usage
--- ```lua --- ```lua
--- local table = { ["info"] = "HI" }
--- createCallback('myCallback', function(source, ...) --- createCallback('myCallback', function(source, ...)
--- -- Your callback code here --- return table
--- end)
---
--- createCallback("callback:checkVehicleOwned", function(source, plate)
--- local result = isVehicleOwned(plate)
--- if result then
--- return true
--- else
--- return false
--- end
--- end) --- end)
--- ``` --- ```
function createCallback(callbackName, funct) function createCallback(callbackName, funct)
if isServer() then
debugPrint("^6Bridge^7: ^3Registering callback^7:", callbackName)
if isStarted(OXLibExport) then if isStarted(OXLibExport) then
lib.callback.register(callbackName, funct) lib.callback.register(callbackName, funct)
else else
@@ -31,6 +43,7 @@ function createCallback(callbackName, funct)
end end
end end
end end
end
--- Triggers a server callback and returns the result. --- Triggers a server callback and returns the result.
--- ---
@@ -43,10 +56,15 @@ end
--- ---
---@usage ---@usage
--- ```lua --- ```lua
--- local result = triggerCallback('myCallback', arg1, arg2) --- local result = triggerCallback('myCallback')
--- jsonPrint(result)
---
--- local result = triggerCallback("callback:checkVehicleOwned", plate)
--- print(result)
--- ``` --- ```
function triggerCallback(callbackName, ...) function triggerCallback(callbackName, ...)
local result = nil local result = nil
debugPrint("^6Bridge^7: ^3Triggering callback^7:", callbackName)
if isStarted(OXLibExport) then if isStarted(OXLibExport) then
result = lib.callback.await(callbackName, false, ...) result = lib.callback.await(callbackName, false, ...)
elseif isStarted(QBExport) then elseif isStarted(QBExport) then
@@ -55,6 +73,7 @@ function triggerCallback(callbackName, ...)
p:resolve(cbResult) p:resolve(cbResult)
end, ...) end, ...)
result = Citizen.Await(p) result = Citizen.Await(p)
Wait(10)
elseif isStarted(ESXExport) then elseif isStarted(ESXExport) then
local p = promise.new() local p = promise.new()
ESX.TriggerServerCallback(callbackName, function(cbResult) ESX.TriggerServerCallback(callbackName, function(cbResult)

View File

@@ -1,25 +1,37 @@
--[[
Menu Opening Module
---------------------
This module provides a unified function to open menus using the configured menu system.
Supported systems include:
• jim_bridge (built-in nui menu that works on any framework)
• ox (or ox_context)
• qb (using QBMenuExport)
• gta (using WarMenu)
• esx (using ESX.UI.Menu)
]]
--- Opens a menu using the configured menu system. --- Opens a menu using the configured menu system.
--- ---
--- This function translates code and creates menus in several different menu scripts, depending on the configured menu system specified in `Config.System.Menu`. --- This function translates code and creates menus in several different menu scripts, depending on the configured menu system specified in `Config.System.Menu`.
--- ---
---@param Menu table A table containing the menu options to display. ---@param Menu table A table containing the menu options to display.
--- Each menu item can include: --- Each menu item can include:
--- - **header** (`string`): The text to display for the menu item. --- - header (`string`): The text to display for the menu item.
--- - **txt** (`string`, optional): Additional text or description. --- - txt (`string`, optional): Additional text or description.
--- - **icon** (`string`, optional): Icon to display with the menu item. --- - icon (`string`, optional): Icon to display with the menu item.
--- - **onSelect** (`function`, optional): Function to execute when the menu item is selected. --- - onSelect (`function`, optional): Function to execute when the menu item is selected.
--- - **arrow** (`boolean`, optional): Whether to display an arrow next to the item (for certain menus). --- - arrow (`boolean`, optional): Whether to display an arrow next to the item (for certain menus).
--- - **params** (`table`, optional): Additional parameters, such as events and arguments. --- - params (`table`, optional): Additional parameters, such as events and arguments.
--- - **isMenuHeader** (`boolean`, optional): Marks the item as a header. --- - isMenuHeader (`boolean`, optional): Marks the item as a header.
--- - **disabled** (`boolean`, optional): Disables the menu item if `true`. --- - disabled (`boolean`, optional): Disables the menu item if `true`.
--- ---
---@param data table A table containing configuration data for the menu. ---@param data table A table containing configuration data for the menu.
--- - **header** (`string`): The header/title of the menu. --- - header (`string`): The header/title of the menu.
--- - **headertxt** (`string`, optional): Additional header text. --- - headertxt (`string`, optional): Additional header text.
--- - **onBack** (`function`, optional): Function to call when the "Return" option is selected. --- - onBack (`function`, optional): Function to call when the "Return" option is selected.
--- - **onExit** (`function`, optional): Function to call when the menu is exited. --- - onExit (`function`, optional): Function to call when the menu is exited.
--- - **onSelected** (`function`, optional): Function to call when a menu item is selected (for certain menu systems). --- - onSelected (`function`, optional): Function to call when a menu item is selected (for certain menu systems).
--- - **canClose** (`boolean`, optional): Whether the menu can be closed by the user. --- - canClose (`boolean`, optional): Whether the menu can be closed by the user.
--- ---
---@usage ---@usage
--- ```lua --- ```lua
@@ -39,17 +51,42 @@ function openMenu(Menu, data)
if data.onBack then if data.onBack then
table.insert(Menu, 1, { table.insert(Menu, 1, {
icon = "fas fa-circle-arrow-left", icon = "fas fa-circle-arrow-left",
title = "Return", header = " ",
onSelect = data.onBack, txt = "Return",
params = {
isAction = true,
event = data.onBack,
},
})
elseif data.canClose then
table.insert(Menu, 1, {
icon = "fas fa-circle-xmark",
header = " ",
txt = "Close",
params = {
isAction = true,
event = data.onExit and data.onExit or (function() exports[QBMenuExport]:closeMenu() end),
},
}) })
end end
exports["jim-nui"]:openMenu({ if data.header ~= nil then
title = data.header..(data.headertxt and " -- "..data.headertxt or ""), local tempMenu = {}
canClose = data.canClose and data.canClose or nil, for k, v in pairs(Menu) do tempMenu[k + 1] = v end
onClose = (data.onBack and data.onBack) or (data.onExit and data.onExit) or nil, tempMenu[1] = { header = data.header, txt = data.headertxt or "", isMenuHeader = true }
onExit = data.onExit and data.onExit or nil, Menu = tempMenu
options = Menu, end
}) for k in pairs(Menu) do
if not Menu[k].params or not Menu[k].params.event then
Menu[k].params = {
isAction = true,
event = Menu[k].onSelect or function() end,
}
end
if not Menu[k].header then Menu[k].header = " " end
if Menu[k].arrow then Menu[k].icon = "fas fa-angle-right" end
Menu[k].isMenuHeader = Menu[k].isMenuHeader or Menu[k].disable
end
TriggerEvent("jim_bridge:client:openMenu", Menu)
elseif Config.System.Menu == "ox" then elseif Config.System.Menu == "ox" then
local index = nil local index = nil
@@ -65,6 +102,7 @@ function openMenu(Menu, data)
if data.onSelected and Menu[k].arrow then if data.onSelected and Menu[k].arrow then
Menu[k].icon = "fas fa-angle-right" Menu[k].icon = "fas fa-angle-right"
end end
-- If no title, use header or txt as title/label.
if not Menu[k].title then if not Menu[k].title then
if Menu[k].header ~= nil and Menu[k].header ~= "" then if Menu[k].header ~= nil and Menu[k].header ~= "" then
Menu[k].title = Menu[k].header Menu[k].title = Menu[k].header
@@ -75,12 +113,13 @@ function openMenu(Menu, data)
Menu[k].label = Menu[k].txt Menu[k].label = Menu[k].txt
end end
end end
-- Copy parameters from 'params' if available.
if Menu[k].params then if Menu[k].params then
Menu[k].event = Menu[k].params.event Menu[k].event = Menu[k].params.event
Menu[k].args = Menu[k].params.args or {} Menu[k].args = Menu[k].params.args or {}
end end
if Menu[k].isMenuHeader then if Menu[k].isMenuHeader then
Menu[k].disabled = true Menu[k].readOnly = true
end end
end end
local menuID = 'Menu' local menuID = 'Menu'
@@ -143,28 +182,19 @@ function openMenu(Menu, data)
end end
for k in pairs(Menu) do for k in pairs(Menu) do
if not Menu[k].params or not Menu[k].params.event then if not Menu[k].params or not Menu[k].params.event then
if Menu[k].onSelect then
Menu[k].params = { Menu[k].params = {
isAction = true, isAction = true,
event = Menu[k].onSelect, event = Menu[k].onSelect or function() end,
} }
else
Menu[k].params = {
isAction = true,
event = function() end,
}
end
end end
if not Menu[k].header then Menu[k].header = " " end if not Menu[k].header then Menu[k].header = " " end
if Menu[k].arrow then Menu[k].icon = "fas fa-angle-right" end if Menu[k].arrow then Menu[k].icon = "fas fa-angle-right" end
Menu[k].isMenuHeader = Menu[k].isMenuHeader or Menu[k].disable
end end
exports[QBMenuExport]:openMenu(Menu) exports[QBMenuExport]:openMenu(Menu)
elseif Config.System.Menu == "gta" then elseif Config.System.Menu == "gta" then
WarMenu.CreateMenu(tostring(Menu), WarMenu.CreateMenu(tostring(Menu), data.header, " ", {
data.header,
data.headertxt or " ",
{
titleColor = { 222, 255, 255 }, titleColor = { 222, 255, 255 },
maxOptionCountOnScreen = 15, maxOptionCountOnScreen = 15,
width = 0.25, width = 0.25,
@@ -202,6 +232,7 @@ function openMenu(Menu, data)
if pressed and not Menu[k].isMenuHeader then if pressed and not Menu[k].isMenuHeader then
WarMenu.CloseMenu() WarMenu.CloseMenu()
close = false close = false
Wait(10)
Menu[k].onSelect() Menu[k].onSelect()
end end
end end
@@ -238,7 +269,6 @@ function openMenu(Menu, data)
onSelect = data.onBack, onSelect = data.onBack,
}) })
end end
ESX.UI.Menu.Open("default", getScript(), "Example_Menu", { ESX.UI.Menu.Open("default", getScript(), "Example_Menu", {
title = data.header, title = data.header,
align = 'top-right', align = 'top-right',
@@ -259,15 +289,11 @@ function openMenu(Menu, data)
end end
end end
--- A line break constant used for formatting menu headers. --- A line break constant used for menu header formatting.
br = (Config.System.Menu == "ox" or Config.System.Menu == "gta") and "\n" or "<br>" br = (Config.System.Menu == "ox" or Config.System.Menu == "gta") and "\n" or "<br>"
--- Checks if the menu system is classified as 'ox' or 'gta'. --- Checks if the current menu system is 'ox' or 'gta' for formatting purposes.
--- --- @return boolean boolean True if using ox or gta menus, otherwise false.
--- This function is used to decide how to make line breaks in menu headers.
---
--- @return boolean Returns `true` if the menu system is 'ox' or 'gta'; otherwise, `false`.
---
--- @usage --- @usage
--- ```lua --- ```lua
--- if isOx() then --- if isOx() then
@@ -279,7 +305,7 @@ function isOx() return (Config.System.Menu == "ox" or Config.System.Menu == "gta
--- Checks if any WarMenu menu is currently open. --- Checks if any WarMenu menu is currently open.
--- ---
--- @return boolean Returns `true` if a WarMenu menu is open; otherwise, `false`. --- @return boolean boolean Returns `true` if a WarMenu menu is open; otherwise, `false`.
--- ---
--- @usage --- @usage
--- ```lua --- ```lua

View File

@@ -1,170 +1,103 @@
-- Create empty Variables -- Items, Vehicles, Jobs, Gangs, Core = {}, nil, nil, nil, nil
Items, Vehicles, Jobs, Gangs, Core, ESX = {}, nil, nil, nil, nil, nil
-- Correct QB inventory export (if needed) from 'qb-inventory' to 'ps-inventory' or 'lj-inventory' -- -- Shared Exports Initialization
Exports.QBInv = (isStarted("ps-inventory") and "ps-inventory") or (isStarted("lj-inventory") and "lj-inventory") or Exports.QBInv Exports.PSInv = isStarted("lj-inventory") and "lj-inventory" or Exports.PSInv
-- Create simple variables based on the corresponding framework exports -- OXLibExport, QBXExport, QBExport, ESXExport, OXCoreExport =
OXLibExport, QBXExport, QBExport, ESXExport, OXCoreExport = Exports.OXLibExport or "", Exports.QBXExport or "", Exports.QBExport or "", Exports.ESXExport or "", Exports.OXCoreExport or "" Exports.OXLibExport or "",
Exports.QBXExport or "",
Exports.QBExport or "",
Exports.ESXExport or "",
Exports.OXCoreExport or ""
-- Create simple variables based on the corresponding inventory names -- OXInv, QBInv, PSInv, QSInv, CoreInv, CodeMInv, OrigenInv, TgiannInv, JPRInv =
OXInv, QBInv, PSInv, QSInv, CoreInv, CodeMInv, OrigenInv = Exports.OXInv or "", Exports.QBInv or "", Exports.PSInv or "", Exports.QSInv or "", Exports.CoreInv or "", Exports.CodeMInv or "", Exports.OrigenInv or "" Exports.OXInv or "",
Exports.QBInv or "",
Exports.PSInv or "",
Exports.QSInv or "",
Exports.CoreInv or "",
Exports.CodeMInv or "",
Exports.OrigenInv or "",
Exports.TgiannInv or "",
Exports.JPRInv or ""
-- QB-Menu export name grabbed from exports.lua -- RSGExport, RSGInv = Exports.RSGExport or "", Exports.RSGInv or ""
QBMenuExport = Exports.QBMenuExport or "" QBMenuExport = Exports.QBMenuExport or ""
-- Target exports based on what is loaded --
QBTargetExport, OXTargetExport = Exports.QBTargetExport or "", Exports.OXTargetExport or "" QBTargetExport, OXTargetExport = Exports.QBTargetExport or "", Exports.OXTargetExport or ""
-- If Debug mode is on in the loading script, print the list of found exports --
-- Some may "lie", 'ox_target' attempts to use 'qb-target' exports and this print will say its loaded (which is technically true) --
for _, v in pairs(Exports) do
if isStarted(v) then debugPrint("^6Bridge^7: '^3"..v.."^7' ^2export found ^7") end
end
local itemResource, jobResource, vehResource = "", "", ""
-- Load item lists --
-- Complies the items from ox_inventory, qb-core or esx into 'Items' and loads them in a layout similar to qb-core's Shared items.lua --
-- For example this makes it so instead of QBCore.Shared.Items[item], you can load 'Item[item]' in the script --
if isStarted(OXInv) then itemResource = OXInv
Items = exports[OXInv]:Items()
for k, v in pairs(Items) do
if v.client and v.client.image then
Items[k].image = (v.client.image):gsub("nui://"..OXInv.."/web/images/", "")
else
Items[k].image = k..".png"
end
Items[k].hunger = v.client and v.client.hunger or nil
Items[k].thirst = v.client and v.client.thirst or nil
end
elseif isStarted(QBExport) then itemResource = QBExport
Core = Core or exports[QBExport]:GetCoreObject()
Items = Core and Core.Shared.Items or nil
if isStarted(QBExport) and not isStarted(QBXExport) then
RegisterNetEvent('QBCore:Client:UpdateObject', function()
Core = Core or exports[QBExport]:GetCoreObject()
Items = Core and Core.Shared.Items or nil
end)
end
elseif isStarted(ESXExport) then itemResource = ESXExport
ESX = exports[ESXExport]:getSharedObject()
Items = ESX and ESX.Items or nil
end
-- If it fails to load items, then it will print the error below --
-- If it loads them and debug is on, print how many items and where from --
if not Items then
print("^4ERROR^7: ^2No Core Items detected ^7- ^2Check ^3exports^1.^2lua^7")
else
debugPrint("^6Bridge^7: ^2Loading ^6"..countTable(Items).." ^3Items^2 from ^7" .. itemResource)
end
-- Load Vehicles --
-- Complies the vehicles from the detected frameworks into a table in the style of qb-cores shared vehicles.lua --
-- For example, instead of using QBCore.Shared.Vehicles[vehicle] you can load 'Vehicles[vehicle]' in the script --
if isStarted(QBXExport) or isStarted(QBExport) then if isStarted(QBXExport) or isStarted(QBExport) then
Core = Core or exports[QBExport]:GetCoreObject() Core = Core or exports[QBExport]:GetCoreObject()
Vehicles = Core and Core.Shared.Vehicles elseif isStarted(RSGExport) then
if isStarted(QBExport) and not isStarted(QBXExport) then Core = Core or exports[RSGExport]:GetCoreObject()
RegisterNetEvent('QBCore:Client:UpdateObject', function()
Core = Core or exports[QBExport]:GetCoreObject()
Vehicles = Core and Core.Shared.Vehicles
end)
end
vehResource = QBExport
elseif isStarted(OXCoreExport) then
Vehicles = {}
for k, v in pairs(Ox.GetVehicleData()) do
Vehicles[k] = { model = k, price = v.price, name = v.name, brand = v.make }
end
vehResource = OXCoreExport
elseif isStarted(ESXExport) then
-- print("^6Bridge^7: ^2Loading ^3Vehicles^2 from ^7"..ESXExport)
-- print("^6Bridge^7: ^2Loading ^6"..countTable(Vehicles).." ^3Vehicles^2 from ^7"..ESXExport)
CreateThread(function()
if isServer() then
createCallback(getScript()..":getVehiclesPrices", function(source)
Vehicles = MySQL.query.await('SELECT model, price, name FROM vehicles')
vehResource = ESXExport
return Vehicles
end)
end
if not isServer() then
local TempVehicles = triggerCallback(getScript()..":getVehiclesPrices")
for _, v in pairs(TempVehicles) do
Vehicles = Vehicles or {}
Vehicles[v.model] = { model = v.model, price = v.price, name = v.name, brand = GetMakeNameFromVehicleModel(v.model):lower():gsub("^%l", string.upper) }
end
end
end)
end
if vehResource == nil then
print("^4ERROR^7: ^2No Vehicle info detected ^7- ^2Check ^3exports^1.^2lua^7")
else
debugPrint("^6Bridge^7: ^2Loading ^6"..countTable(Vehicles).." ^3Vehicles^2 from ^7"..vehResource)
end end
-- Load Jobs --
-- Attempts to load the details of jobs and gangs and compile into tables --
-- For example, instead of using QBCore.Shared.Jobs[job] you can load 'Jobs[job]' in the script --
if isStarted(QBXExport) then jobResource = QBXExport
Core = Core or exports[QBExport]:GetCoreObject()
Jobs, Gangs = exports[QBXExport]:GetJobs(), exports[QBXExport]:GetGangs()
elseif isStarted(OXCoreExport) then jobResource = OXExport if IsDuplicityVersion() then
CreateThread(function() CreateThread(function()
if isServer() then local cache = nil
createCallback(getScript()..":getOxGroups", function(source) local timeout = GetGameTimer() + 5000 -- 5 seconds max wait
Jobs = MySQL.query.await('SELECT * FROM `ox_groups`') return Jobs
-- Wait until jim_bridge is started and export is available
while not cache and GetGameTimer() < timeout do
if GetResourceState("jim_bridge"):find("start") then
local success, result = pcall(function()
return exports["jim_bridge"]:GetSharedData()
end)
if success and result then
cache = result
--print(json.encode(cache, {indent = true}))
end
end
Wait(100)
end
if not cache then
print("^1ERROR^7: ^2jim_bridge export not available after timeout^7.")
return
end
Items = cache.Items
Vehicles = cache.Vehicles
Jobs = cache.Jobs
Gangs = cache.Gangs
debugPrint("^6Bridge^7: ^2Shared cache successfully loaded from export^7.")
end) end)
else else
local TempJobs = triggerCallback(getScript()..":getOxGroups") local hasCache = false
Jobs = TempJobs or {} -- 🔹 Client Side: Request from server
for k, v in pairs(TempJobs) do _G.__jimBridgeDataCache = {}
local grades = {}
for i = 1, #v.grades do grades[i] = { name = v.grades[i], isboss = (i == #v.grades)} end RegisterNetEvent("jim_bridge:receiveCache", function(data)
Jobs[v.name] = { label = v.label, grades = grades } if not hasCache then
end _G.__jimBridgeDataCache = data
Gangs = Jobs hasCache = true
else
return
end end
end) end)
elseif isStarted(QBExport) then jobResource = QBExport TriggerServerEvent("jim_bridge:requestCache")
Core = Core or exports[QBExport]:GetCoreObject()
Jobs, Gangs = Core.Shared.Jobs, Core.Shared.Gangs
if isStarted(QBExport) and not isStarted(QBXExport) then
RegisterNetEvent('QBCore:Client:UpdateObject', function()
Core = exports[QBExport]:GetCoreObject()
Jobs, Gangs = Core.Shared.Jobs, Core.Shared.Gangs
end)
end
elseif isStarted(ESXExport) then
--print("^6Bridge^7: ^2Loading ^3Jobs^7/^3Gangs^2 from ^7"..ESXExport)
ESX = exports[ESXExport]:getSharedObject()
if isServer() then
Jobs = ESX.GetJobs()
for k, v in pairs(Jobs) do
local count = countTable(Jobs[k].grades)-1
Jobs[k].grades[tostring(count)].isBoss = true
end
Gangs = Jobs
end
CreateThread(function() CreateThread(function()
while not ESX do Wait(0) end while not _G.__jimBridgeDataCache or not next(_G.__jimBridgeDataCache) do Wait(50) end
if isServer() then local cache = _G.__jimBridgeDataCache
createCallback(getScript()..":getJobs", function(source) Items = cache.Items or {}
return Jobs Vehicles = cache.Vehicles or {}
Jobs = cache.Jobs or {}
Gangs = cache.Gangs or {}
if isStarted(ESXExport) then
for _, v in pairs(Vehicles) do
Vehicles[v.model] = {
model = v.model,
hash = v.hash,
price = v.price,
name = v.name,
brand = GetMakeNameFromVehicleModel(v.model):lower():gsub("^%l", string.upper)
}
end
end
end) end)
end end
if not isServer() then
Jobs = triggerCallback(getScript()..":getJobs")
Gangs = Jobs
end
end)
end
if not isStarted(ESXExport) and Jobs then
debugPrint("^6Bridge^7: ^2Loading ^6"..countTable(Jobs).." ^3Jobs^2 from ^7"..jobResource, "^6Bridge^7: ^2Loading ^6"..countTable(Gangs).." ^3Gangs^2 from ^7"..jobResource)
end

View File

@@ -1,20 +1,38 @@
local CraftLock = false --[[
Crafting, Selling, and Shop Module
-----------------------------------
This module provides functions for opening crafting menus, handling multi-crafting,
performing the crafting process (with animations and progress bars), selling items,
and opening shop interfaces. It integrates with various inventory and menu systems,
and uses server callbacks to check item carry capacity.
]]
--- Opens a crafting menu based on the provided data. -------------------------------------------------------------
-- Global Variables
-------------------------------------------------------------
CraftLock = false
-- helper filter table for crafting menus
local excludeKeys = {
amount = true, metadata = true, description = true, info = true,
job = true, gang = true, oneUse = true, slot = true,
blueprintRef = true, craftingLevel = true, craftedItems = true,
hasCrafted = true, exp = true, anim = true, time = true,
}
-------------------------------------------------------------
-- Crafting Menu
-------------------------------------------------------------
--- Opens the crafting menu based on provided data.
--- Checks job restrictions, builds the recipe menu, and opens the menu.
--- ---
--- This function checks job requirements, prepares the menu options, and opens the crafting menu. --- @param data table Crafting menu configuration containing:
--- It handles item availability, crafting recipes, and displays appropriate icons and labels. --- - craftable (`table`) Table with Header, Recipes, Anims, and (optionally) craftedItems.
--- --- - coords (`vector3`) The coordinates where the crafting menu is being opened.
---@param data table A table containing crafting menu data. --- - stashTable|stashName (`string\table`) Name(s) of the stash for checking item availability.
--- - **craftable** (`table`): The crafting options and settings. --- - job|gang (`string`) Job or gang requirements.
--- - **Header** (`string`): The header/title of the crafting menu. --- - onBack (optional): Function to call when returning.
--- - **Recipes** (`table`): A list of crafting recipes.
--- - **coords** (`vector3`): The coordinates where the crafting menu is being opened.
--- - **stashTable** (`string` or `table`, optional): The stash name(s) to check for item availability.
--- - **stashName** (`string` or `table`, optional): Alias for `stashTable`.
--- - **job** (`string` or `table`, optional): Job(s) required to access the crafting menu.
--- - **gang** (`string` or `table`, optional): Gang(s) required to access the crafting menu.
--- - **onBack** (`function`, optional): Function to call when returning from the menu.
--- ---
--- @usage --- @usage
--- ```lua --- ```lua
@@ -35,22 +53,31 @@ local CraftLock = false
--- }, --- },
--- coords = vector3(100.0, 200.0, 300.0), --- coords = vector3(100.0, 200.0, 300.0),
--- stashTable = "crafting_stash", --- stashTable = "crafting_stash",
--- job = "mechanic", -- Optional --- job = "mechanic",
--- onBack = function() print("Returning to previous menu") end, --- onBack = function() print("Returning to previous menu") end,
--- }) --- })
--- ```
function craftingMenu(data) function craftingMenu(data)
if CraftLock then return end if CraftLock then return end
-- Job or gang check; exit if not authorized.
if (data.job or data.gang) and not jobCheck(data.job or data.gang) then return end if (data.job or data.gang) and not jobCheck(data.job or data.gang) then return end
-- Display a temporary "thinking" notification.
if Config.System.Menu == "jim" then if Config.System.Menu == "jim" then
triggerNotify(nil, "Thinking", "info") triggerNotify(nil, "Thinking", "info")
else else
openMenu({ { header = "Thinking...", icon = "fas fa-hourglass-end", isMenuHeader = true } }, { header = "Crafting Menu" } ) openMenu({ { header = "Thinking...", icon = "fas fa-hourglass-end", isMenuHeader = true } }, { header = "Crafting Menu" } )
end end
if data.stashTable then data.stashName = data.stashTable end
local Menu, hasjob = {}, false -- Normalize stash name.
data.stashName = data.stashTable or data.stashName
local Menu = {}
local Recipes = data.craftable.Recipes local Recipes = data.craftable.Recipes
local craftedItems = {}
local tempCarryTable = {} local tempCarryTable = {}
-- Build a table of all required ingredients (default quantity is 1).
for i = 1, #Recipes do for i = 1, #Recipes do
for k in pairs(Recipes[i]) do for k in pairs(Recipes[i]) do
if k ~= "amount" and k ~= "metadata" and k ~= "job" and k ~= "gang" then if k ~= "amount" and k ~= "metadata" and k ~= "job" and k ~= "gang" then
@@ -59,69 +86,102 @@ function craftingMenu(data)
end end
end end
-- Check if the player can carry the required items (server callback).
local canCarryTable = triggerCallback(getScript()..':server:canCarry', tempCarryTable) local canCarryTable = triggerCallback(getScript()..':server:canCarry', tempCarryTable)
-- Process each recipe to create menu entries.
for i = 1, #Recipes do for i = 1, #Recipes do
if not Recipes[i]["amount"] then Recipes[i]["amount"] = 1 end if not Recipes[i]["amount"] then Recipes[i]["amount"] = 1 end
for k, v in pairs(Recipes[i]) do for k, _ in pairs(Recipes[i]) do
if k ~= "amount" and k ~= "metadata" and k ~= "job" and k ~= "gang" then if not excludeKeys[k] then
local hasjob = true
if Recipes[i].job then if Recipes[i].job then
for l, b in pairs(Recipes[i].job) do for l, b in pairs(Recipes[i].job) do
hasjob = hasJob(l, nil, b) hasjob = hasJob(l, nil, b)
if hasjob == true then break end if hasjob then break end
end
end end
else hasjob = true end
local setheader, settext, disable, metadata = "", "", false, (Recipes[i]["metadata"] or nil)
if hasjob then if hasjob then
local setheader, settext, disable, metadata = "", "", false, (Recipes[i]["metadata"] or Recipes[i]["info"] or nil)
local itemTable = {} local itemTable = {}
local metaTable = {} local metaTable = {}
-- Build ingredient details.
for l, b in pairs(Recipes[i][tostring(k)]) do for l, b in pairs(Recipes[i][tostring(k)]) do
settext = settext..(settext ~= "" and br or "")..(Items[l] and Items[l].label or "error - "..l)..(b > 1 and " x"..b or "") local label = Items[l] and Items[l].label or "error - "..l
local hasItem = checkStashItem(data.stashName, { [l] = b })
local missingMark = not hasItem and "" or " "
settext = settext..(settext ~= "" and br or "").."[ x"..b.." ] - "..label..(b > 1 and " x"..b or "")..missingMark
metaTable[Items[l] and Items[l].label or "error - "..l] = b metaTable[Items[l] and Items[l].label or "error - "..l] = b
itemTable[l] = b itemTable[l] = b
Wait(0)
end end
while not canCarryTable do Wait(0) end while not canCarryTable do Wait(0) end
disable = not checkHasItem(data.stashName, itemTable) disable = not checkStashItem(data.stashName, itemTable)
setheader = ((metadata and metadata.label) or (Items[tostring(k)] and Items[tostring(k)].label) or "error - " .. tostring(k)) .. (Recipes[i]["amount"] > 1 and " x" .. Recipes[i]["amount"] or "") setheader = ((metadata and metadata.label) or (Items[tostring(k)] and Items[tostring(k)].label) or "error - "..tostring(k))
if not disable then ..(Recipes[i]["amount"] > 1 and " x"..Recipes[i]["amount"] or "")
if not canCarryTable[k] then setheader = setheader .. " 📦"
else setheader = setheader .. " ✔️" end local statusEmoji = disable and " " or not canCarryTable[k] and " 📦" or " ✔️"
elseif not canCarryTable[k] then setheader = setheader .. " 📦" end local isNew = (Recipes[i]["hasCrafted"] ~= nil and craftedItems[k] == nil) and " " or ""
setheader = isNew .. setheader .. statusEmoji
Menu[#Menu + 1] = { Menu[#Menu + 1] = {
arrow = not disable and canCarryTable[k], arrow = isOx() and (not disable and canCarryTable[k]),
disable = isStarted(QBMenuExport) and disable and not canCarryTable[k], isMenuHeader = disable or not canCarryTable[k],
icon = invImg((metadata and metadata.image) or tostring(k)), icon = invImg((metadata and metadata.image) or tostring(k)),
image = invImg((metadata and metadata.image) or tostring(k)), image = invImg((metadata and metadata.image) or tostring(k)),
header = setheader..((disable or not canCarryTable[k]) and "" or ""), header = setheader,
txt = isStarted(QBMenuExport) and settext or nil, txt = settext or nil,
--metadata = debugMode and Recipes[i]["metadata"] or nil,
metadata = metaTable, metadata = metaTable,
onSelect = ((not disable and canCarryTable[k]) and (function() onSelect = (not disable and canCarryTable[k]) and function()
local transdata = { item = k, craft = data.craftable.Recipes[i], craftable = data.craftable, coords = data.coords, stashName = data.stashName, onBack = data.onBack, metadata = Recipes[i]["metadata"] } local transdata = {
if Config.Crafting.MultiCraft then multiCraft(transdata) else makeItem(transdata) end item = k,
end) or nil), craft = data.craftable.Recipes[i],
craftable = data.craftable,
coords = data.coords,
stashName = data.stashName,
onBack = data.onBack,
metadata = metadata,
}
if Config.Crafting.MultiCraft then
multiCraft(transdata)
else
makeItem(transdata)
end
end or nil,
} }
end end
end end
Wait(0) --Wait(0)
end end
end end
openMenu(Menu, { header = data.craftable.Header, onBack = data.onBack or nil, canClose = true, onExit = function() end, })
openMenu(Menu, {
header = data.craftable.Header,
headertxt = data.craftable.Headertxt,
onBack = data.onBack or nil,
canClose = true,
onExit = data.onExit or (function() end),
})
lookEnt(data.coords) lookEnt(data.coords)
end end
-------------------------------------------------------------
-- Multi-Craft Menu
-------------------------------------------------------------
--- Opens a menu for selecting the quantity to craft. --- Opens a menu for selecting the quantity to craft.
--- ---
--- This function presents the player with options to craft multiple quantities of an item, based on `Config.Crafting.MultiCraftAmounts`. --- Presents the player with multiple crafting quantities based on Config.Crafting.MultiCraftAmounts.
--- ---
---@param data table A table containing crafting data. --- @param data table Crafting configuration containing:
--- - **item** (`string`): The item to craft. --- - item `string`) The item to craft.
--- - **craft** (`table`): The crafting recipe for the item. --- - craft (`table`) The crafting recipe.
--- - **craftable** (`table`): The crafting options and settings. --- - craftable (`table`) Crafting options.
--- - **coords** (`vector3`): The coordinates where the crafting is taking place. --- - coords (`vector3`) where crafting occurs.
--- - **stashName** (`string` or `table`, optional): The stash name(s) to check for item availability. --- - stashName (`string`) The stash name(s) for item availability.
--- - **onBack** (`function`, optional): Function to call when returning from the menu. --- - onBack (`function`) Callback when returning.
--- - **metadata** (`table`, optional): Metadata for the crafted item. --- - metadata (`table`) (optional): Metadata for the crafted item.
--- ---
--- @usage --- @usage
--- ```lua --- ```lua
@@ -129,57 +189,114 @@ end
--- item = "weapon_pistol", --- item = "weapon_pistol",
--- craft = { ["weapon_pistol"] = { ["steel"] = 5, ["plastic"] = 2 }, amount = 1 }, --- craft = { ["weapon_pistol"] = { ["steel"] = 5, ["plastic"] = 2 }, amount = 1 },
--- craftable = craftingOptions, --- craftable = craftingOptions,
--- coords = vector3(100.0, 200.0, 300.0), --- coords = vector3(100,200,300),
--- stashName = "crafting_stash", --- stashName = "crafting_stash",
--- onBack = function() craftingMenu(data) end, --- onBack = function() craftingMenu(data) end,
--- metadata = { label = "Custom Pistol", image = "custom_pistol.png" }, --- metadata = { label = "Custom Pistol", image = "custom_pistol.png" },
--- }) --- })
--- ``` --- ```
function multiCraft(data) function multiCraft(data)
local Menu = {} local max = 0
local success = Config.Crafting.MultiCraftAmounts local stashName = nil
local metadata = data.metadata or nil local maxCreation = 100
Menu[#Menu+1] = {
isMenuHeader = true, -- Generate item table to check against stash or inventory
icon = invImg(metadata and metadata.image or data.item), -- takes into account the ingredients needed for multiple items
header = metadata and metadata.label or Items[data.item].label, local multiItemTable = {}
}
for k in pairsByKeys(success) do for i = 1, maxCreation do
local settext = "" multiItemTable[i] = {}
local itemTable = {}
for l, b in pairs(data.craft[data.item]) do for l, b in pairs(data.craft[data.item]) do
itemTable[l] = (b * k) multiItemTable[i][l] = (b * i)
settext = settext..(settext ~= "" and br or "")..Items[l].label..(b*k > 1 and "- x"..b*k or "")
Wait(0)
end end
local disable, stashname = checkHasItem(data.stashName, itemTable)
Menu[#Menu + 1] = {
isMenuHeader = not disable,
arrow = disable,
header = "Craft - x"..k * data.craft.amount,
txt = settext,
onSelect = function ()
makeItem({item = data.item, craft = data.craft, craftable = data.craftable, amount = k, coords = data.coords, stashName = stashname, stashTable = data.stashName, onBack = data.onBack, metadata = data.metadata })
end,
}
end end
openMenu(Menu, { header = data.craftable.Header, onBack = function() craftingMenu(data) end, })
for i = 1, maxCreation do
-- if its received a stash name, check if the items are in the stash
if data.stashName then
local hasItems, stashname = checkStashItem(data.stashName, multiItemTable[i])
if hasItems == true then
max += 1
stashName = stashname
else
break
end end
else
-- if not check the players inventory for the items
local has, _ = hasItem(multiItemTable[i], nil, nil)
if has then
max += 1
else
break
end
end
end
local carryMax = triggerCallback(getScript()..":server:getMaxCarryCraft", {
item = data.item,
max = max
})
local dialog = createInput(data.craftable.Header..(Config.System.Menu == "qb" and ": "..br.."How many to craft? "..br.."Max: "..carryMax or ""), {
((Config.System.Menu == "ox") and {
type = "slider",
label = "How many to craft? "..br.."Max: "..carryMax,
required = true,
default = 1,
min = 1,
max = carryMax
}) or nil,
((Config.System.Menu == "qb") and {
type = "number",
name = "amount",
isRequired = true,
default = 1,
}) or nil,
})
if dialog then
if Config.System.Menu == "ox" then
end
if Config.System.Menu == "qb" then
dialog["amount"] = tonumber(dialog["amount"])
if dialog["amount"] > carryMax or dialog["amount"] < 1 or dialog["amount"] == nil or dialog["amount"] == "" then
triggerNotify(nil, "Invalid Amount", "error")
craftingMenu(data)
return
end
end
makeItem({
item = data.item,
craft = data.craft,
craftable = data.craftable,
amount = dialog["amount"] or dialog[1],
coords = data.coords,
stashName = stashName or nil,
onBack = data.onBack,
metadata = data.metadata,
})
end
end
-------------------------------------------------------------
-- Crafting Process
-------------------------------------------------------------
--- Initiates the crafting process for a specified item. --- Initiates the crafting process for a specified item.
--- ---
--- This function handles the crafting animation, progress bar, item removal, and item creation. --- Plays crafting animations, shows progress bars, removes ingredients, and triggers item creation.
--- ---
---@param data table A table containing crafting data. --- @param data table Crafting configuration containing:
--- - **item** (`string`): The item to craft. --- - item `string`) The item to craft.
--- - **craft** (`table`): The crafting recipe for the item. --- - craft (`table`) The crafting recipe.
--- - **craftable** (`table`): The crafting options and settings. --- - craftable (`table`) Crafting options.
--- - **amount** (`number`, optional): The quantity to craft. Default is `1`. --- - amount (`number`) (optional): Quantity to craft (default 1).
--- - **coords** (`vector3`): The coordinates where the crafting is taking place. --- - coords (`vector3`) where crafting occurs.
--- - **stashName** (`string` or `table`, optional): The stash name(s) to remove items from. --- - stashName (`string`) The stash name(s) for item availability.
--- - **stashTable** (`string` or `table`, optional): Alias for `stashName`. --- - onBack (`function`) Callback when returning.
--- - **onBack** (`function`, optional): Function to call when returning from the menu. --- - metadata (`table`) (optional): Metadata for the crafted item.
--- - **metadata** (`table`, optional): Metadata for the crafted item.
--- ---
--- @usage --- @usage
--- ```lua --- ```lua
@@ -188,7 +305,7 @@ end
--- craft = { ["weapon_pistol"] = { ["steel"] = 5, ["plastic"] = 2 }, amount = 1 }, --- craft = { ["weapon_pistol"] = { ["steel"] = 5, ["plastic"] = 2 }, amount = 1 },
--- craftable = craftingOptions, --- craftable = craftingOptions,
--- amount = 2, --- amount = 2,
--- coords = vector3(100.0, 200.0, 300.0), --- coords = vector3(100,200,300),
--- stashName = "crafting_stash", --- stashName = "crafting_stash",
--- onBack = function() craftingMenu(data) end, --- onBack = function() craftingMenu(data) end,
--- metadata = { label = "Custom Pistol", image = "custom_pistol.png" }, --- metadata = { label = "Custom Pistol", image = "custom_pistol.png" },
@@ -197,46 +314,77 @@ end
function makeItem(data) function makeItem(data)
if CraftLock then return end if CraftLock then return end
CraftLock = true CraftLock = true
if data.stashTable then data.stashName = data.stashTable end data.stashName = data.stashTable or data.stashName
local bartime = data.craftable.progressBar and data.craftable.progressBar.time or 5000
local bartext = (data.craftable.progressBar and data.craftable.progressBar.label) or (Loc[Config.Lan].progressbar and Loc[Config.Lan].progressbar["progress_make"]) or "Making a" local bartime = (data.craftable.progressBar and data.craftable.progressBar.time) or 5000
local animDict = data.craftable.Anims and data.craftable.Anims.animDict or "amb@prop_human_parking_meter@male@idle_a" local bartext = (data.craftable.progressBar and data.craftable.progressBar.label)
local anim = data.craftable.Anims and data.craftable.Anims.anim or "idle_a" or (Loc[Config.Lan].progressbar and Loc[Config.Lan].progressbar["progress_make"])
local amount = data.amount and (data.amount ~= 1) and data.amount or 1 or "Making "
local animDict = (data.craftable.Anims and data.craftable.Anims.animDict) or "amb@prop_human_parking_meter@male@idle_a"
local anim = (data.craftable.Anims and data.craftable.Anims.anim) or "idle_a"
local craftAmount = (data.amount and data.amount ~= 1) and data.amount or 1
local metadata = data.metadata or nil local metadata = data.metadata or nil
local prop = data.craftable.Anims and data.craftable.Anims.prop or nil local prop = data.craftable.Anims and data.craftable.Anims.prop or nil
local canReturn = true
local crafted, crafting = true, true local crafted, crafting = true, true
local cam = createTempCam(PlayerPedId(), data.coords) local cam = createTempCam(PlayerPedId(), data.coords)
startTempCam(cam) startTempCam(cam)
for i = 1, craftAmount do
for i = 1, amount do
for k, v in pairs(data.craft) do for k, v in pairs(data.craft) do
if k ~= "amount" and k ~= "metadata" and k ~= "job" and k ~= "gang" then if not excludeKeys[k] then
if type(v) == "table" then if type(v) == "table" then
for l, b in pairs(v) do for l, b in pairs(v) do
if isInventoryOpen() then
print("^1Error^7: ^2Inventory is open, you tried to break things")
crafted, crafting = false, false
stopTempCam()
ClearPedTasks(PlayerPedId())
if canReturn then craftingMenu(data) end
CraftLock = false
return
end
if crafting and progressBar({ if crafting and progressBar({
label = "Using "..b.." "..Items[l].label, label = "Using "..b.." "..Items[l].label,
time = 1000, time = 1000,
cancel = true, cancel = true,
dict = 'pickup_object', dict = 'pickup_object',
anim = "putdown_low", anim = "putdown_low",
flag = 48, flag = 49,
icon = l, icon = l,
}) then }) then
TriggerEvent((isStarted(QBInv) and QBInvNew and "qb-" or "").."inventory:client:ItemBox", Items[l], "use", b) -- Show item box for each item TriggerEvent((isStarted(QBInv) and QBInvNew and "qb-" or "")..'inventory:client:ItemBox', Items[l], "use", b)
else else
crafted, crafting = false, false crafted, crafting = false, false
break break
end end
Wait(200) Wait(200)
end end
if isInventoryOpen() then
print("^1Error^7: ^2Inventory is open, you tried to break things")
crafted, crafting = false, false
stopTempCam()
ClearPedTasks(PlayerPedId())
if canReturn then craftingMenu(data) end
CraftLock = false
return
end
if crafted then if crafted then
local craftProp = nil local craftProp = nil
if prop then if prop then
local model, pos, rot, bone = prop.model, prop.pos, prop.rot, prop.bone craftProp = makeProp({ prop = prop.model, coords = vec4(0, 0, 0, 0), true, true })
craftProp = makeProp({ prop = model, coords = vec4(0, 0, 0, 0), true, true }) AttachEntityToEntity(craftProp, PlayerPedId(), GetPedBoneIndex(PlayerPedId(), prop.bone), prop.pos.x, prop.pos.y, prop.pos.z, prop.rot.x, prop.rot.y, prop.rot.z, true, true, false, true, 1, true)
AttachEntityToEntity(craftProp, PlayerPedId(), GetPedBoneIndex(PlayerPedId(), bone), pos.x, pos.y, pos.z, rot.x, rot.y, rot.z, true, true, false, true, 1, true) end
if data.sound then
local s = data.sound
PlaySoundFromEntity(s.soundId, s.audioName, PlayerPedId(), s.audioRef, true, 0)
end
if isInventoryOpen() then
--print("^1Error^7: ^2Inventory is open, you tried to break things")
crafted, crafting = false, false
crafted, crafting, CraftLock = false, false, false
return
end end
if crafting and progressBar({ if crafting and progressBar({
label = bartext..((metadata and metadata.label) or Items[data.item].label), label = bartext..((metadata and metadata.label) or Items[data.item].label),
@@ -246,8 +394,36 @@ function makeItem(data)
anim = anim, anim = anim,
flag = 49, flag = 49,
icon = data.item, icon = data.item,
request = true,
}) then }) then
TriggerServerEvent(getScript()..":Crafting:GetItem", data.item, data.craft, data.stashName, metadata) TriggerServerEvent(getScript()..":Crafting:GetItem", data.item, data.craft, data.stashName, metadata, currentToken)
currentToken = nil -- clear client cached token
CreateThread(function()
if data.craft["hasCrafted"] ~= nil then
debugPrint("hasCrafted Found, marking '"..data.item.."' as crafted for player")
data.craftable.craftedItems[data.item] = true
triggerCallback(getScript()..":server:SetMetadata", "craftedItems", data.craftable.craftedItems)
end
Wait(100)
if data.craft["exp"] ~= nil then
craftingLevel += data.craft["exp"].give
jsonPrint(data.craft["exp"])
debugPrint("exp found, giving exp for '"..data.item.."'")
triggerCallback(getScript()..":server:SetMetadata", "craftingLevel", craftingLevel)
end
end)
if data.craftable.Recipes[1].oneUse == true then
removeItem("craftrecipe", 1, nil, data.craftable.Recipes[1].slot)
local breakId = GetSoundId()
PlaySoundFromEntity(breakId, "Drill_Pin_Break", PlayerPedId(), "DLC_HEIST_FLEECA_SOUNDSET", 1, 0)
canReturn = false
end
if data.sound then
StopSound(data.sound.soundId)
end
if data.requiredItemfunc then
data.requiredItemfunc()
end
else else
crafting = false crafting = false
break break
@@ -261,21 +437,38 @@ function makeItem(data)
end end
stopTempCam() stopTempCam()
CraftLock = false CraftLock = false
lockInv(false) if canReturn then craftingMenu(data) end
craftingMenu(data)
ClearPedTasks(PlayerPedId()) ClearPedTasks(PlayerPedId())
end end
-------------------------------------------------------------
-- Server Event Handler: Crafted Item
-------------------------------------------------------------
--- Server event handler for giving the crafted item to the player. --- Server event handler for giving the crafted item to the player.
--- ---
--- This event is triggered when the crafting process is completed successfully. --- Removes required ingredients from the player's inventory or stash,
--- then adds the crafted item to their inventory.
--- ---
--- @param ItemMake string The item being crafted. --- @param ItemMake string The item being crafted.
--- @param craftable table The crafting recipe and details. --- @param craftable table The crafting recipe and details.
--- @param stashName string|table The stash name(s) to remove items from. --- @param stashName string|table The stash name(s) to remove ingredients from.
--- @param metadata table (optional) Metadata for the crafted item. --- @param metadata table (optional) Metadata for the crafted item.
RegisterNetEvent(getScript()..":Crafting:GetItem", function(ItemMake, craftable, stashName, metadata) --- @usage
local src, amount, stashItems = source, craftable and craftable.amount or 1, nil RegisterNetEvent(getScript()..":Crafting:GetItem", function(ItemMake, craftable, stashName, metadata, token)
local src = source
debugPrint(GetInvokingResource())
if GetInvokingResource() and GetInvokingResource() ~= getScript() and GetInvokingResource() ~= "qb-core" then
debugPrint("^1Error^7: ^1Possible exploit^7, ^1vital function was called from an external resource^7")
return
end
if not checkToken(src, token, "item", ItemMake) then
return
end
local hasItems, hasTable = hasItem(ItemMake, 1, src)
if stashName then if stashName then
local itemRemove = {} local itemRemove = {}
if type(stashName) == "table" then if type(stashName) == "table" then
@@ -283,7 +476,9 @@ RegisterNetEvent(getScript()..":Crafting:GetItem", function(ItemMake, craftable,
stashItems = getStash(name) stashItems = getStash(name)
for k, v in pairs(craftable[ItemMake] or {}) do for k, v in pairs(craftable[ItemMake] or {}) do
for _, b in pairs(stashItems or {}) do for _, b in pairs(stashItems or {}) do
if k == b.name then itemRemove[k] = v end if k == b.name then
itemRemove[k] = v
end
end end
end end
end end
@@ -291,7 +486,9 @@ RegisterNetEvent(getScript()..":Crafting:GetItem", function(ItemMake, craftable,
stashItems = getStash(stashName) stashItems = getStash(stashName)
for k, v in pairs(craftable[ItemMake] or {}) do for k, v in pairs(craftable[ItemMake] or {}) do
for _, b in pairs(stashItems or {}) do for _, b in pairs(stashItems or {}) do
if k == b.name then itemRemove[k] = v end if k == b.name then
itemRemove[k] = v
end
end end
end end
end end
@@ -299,183 +496,12 @@ RegisterNetEvent(getScript()..":Crafting:GetItem", function(ItemMake, craftable,
else else
if craftable then if craftable then
for k, v in pairs(craftable[ItemMake] or {}) do for k, v in pairs(craftable[ItemMake] or {}) do
TriggerEvent(getScript()..":server:toggleItem", false, tostring(k), v, src) removeItem(tostring(k), v, src)
end end
end end
end end
TriggerEvent(getScript()..":server:toggleItem", true, ItemMake, amount, src, metadata) addItem(ItemMake, craftable.amount or 1, metadata, src)
-- Optionally, add experience here:
-- for example:
-- if isStarted("core_skills") then exports["core_skills"]:AddExperience(src, 2) end -- if isStarted("core_skills") then exports["core_skills"]:AddExperience(src, 2) end
end) end)
--- Opens a selling menu based on the provided data.
---
--- This function checks available items to sell, prepares the menu options, and opens the selling menu.
---
---@param data table A table containing selling menu data.
--- - **sellTable** (`table`): The selling options and settings.
--- - **Items** (`table`): A list of items that can be sold with their prices.
--- - **Header** (`string`, optional): The header/title of the selling menu.
--- - **ped** (`number`, optional): The ped entity involved in the selling interaction.
--- - **onBack** (`function`, optional): Function to call when returning from the menu.
---
---@usage
--- ```lua
--- sellMenu({
--- sellTable = {
--- Header = "Sell Items",
--- Items = {
--- ["gold_ring"] = 100,
--- ["diamond"] = 500,
--- },
--- },
--- ped = pedEntity,
--- onBack = function() print("Returning to previous menu") end,
--- })
--- ```
function sellMenu(data)
local origData = data
local Menu = {}
if data.sellTable.Items then
local itemList = {}
for k, v in pairs(data.sellTable.Items) do itemList[k] = 1 end
local _, hasTable = hasItem(itemList)
for k, v in pairsByKeys(data.sellTable.Items) do
Menu[#Menu +1] = {
isMenuHeader = not hasTable[k].hasItem,
icon = invImg(k),
header = Items[k].label.. (hasTable[k].hasItem and "💰 (x"..hasTable[k].count..")" or ""),
txt = Loc[Config.Lan].info["sell_all"]..v.." "..Loc[Config.Lan].info["sell_each"],
onSelect = function()
sellAnim({ item = k, price = v, ped = data.ped, onBack = function() sellMenu(data) end })
end,
}
end
else
for k, v in pairsByKeys(data.sellTable) do
if type(v) == "table" then
Menu[#Menu +1] = {
arrow = true,
header = k,
txt = "Amount of items: "..countTable(v.Items),
onSelect = function()
v.onBack = function() sellMenu(origData) end
v.sellTable = data.sellTable[k]
sellMenu(v)
end,
}
end
end
end
openMenu(Menu, { header = data.sellTable.Header or "Amount of items: "..countTable(data.sellTable.Items), headertxt = data.sellTable.Header and "Amount of items: "..countTable(data.sellTable.Items) or "", canClose = true, onBack = data.onBack })
end
--- Handles the selling animation and item transaction.
---
--- This function plays the selling animation, removes the item from the player's inventory, and gives the player money.
---
---@param data table A table containing selling data.
--- - **item** (`string`): The item to sell.
--- - **price** (`number`): The price per item.
--- - **ped** (`number`, optional): The ped entity involved in the selling interaction.
--- - **onBack** (`function`, optional): Function to call when returning from the menu.
---
---@usage
--- ```lua
--- sellAnim({
--- item = "gold_ring",
--- price = 100,
--- ped = pedEntity,
--- onBack = function() sellMenu(data) end,
--- })
--- ```
function sellAnim(data)
if not hasItem(data.item, 1) then
triggerNotify(nil, Loc[Config.Lan].error["dont_have"].." "..Items[data.item].label, "error")
return
end
for k, v in pairs(GetGamePool('CObject')) do
for _, model in pairs({`p_cs_clipboard`}) do
if GetEntityModel(v) == model then
if IsEntityAttachedToEntity(data.ped, v) then
DeleteObject(v) DetachEntity(v, 0, 0) SetEntityAsMissionEntity(v, true, true)
Wait(100) DeleteEntity(v)
end
end
end
end
TriggerServerEvent(getScript().."Sellitems", data)
lookEnt(data.ped)
local dict = "mp_common"
playAnim(dict, "givetake2_a", 0.3, 2)
playAnim(dict, "givetake2_b", 0.3, 2, data.ped)
Wait(2000)
StopAnimTask(PlayerPedId(), dict, "givetake2_a", 0.5)
StopAnimTask(data.ped, dict, "givetake2_b", 0.5)
if data.onBack then data.onBack() end
end
--- Server event handler for processing the item sale.
---
--- This event removes the sold item from the player's inventory and adds money to their account.
---
---@param data table The data containing item and price information.
RegisterNetEvent(getScript().."Sellitems", function(data)
local src = source
local hasItems, hasTable = hasItem(data.item, 1, src)
if hasItems then
TriggerEvent(getScript()..":server:toggleItem", false, data.item, hasTable[data.item].count, src)
TriggerEvent(getScript()..":server:FundPlayer", (hasTable[data.item].count * data.price), "cash", src)
else
triggerNotify(nil, Loc[Config.Lan].error["dont_have"].." "..Items[data.item].label, "error", src)
end
end)
--- Opens a shop interface for the player.
---
--- This function checks job requirements and opens the shop using the appropriate inventory system.
---
---@param data table A table containing shop data.
--- - **shop** (`string`): The shop identifier.
--- - **items** (`table`): The items available in the shop.
--- - **coords** (`vector3`): The coordinates where the shop interaction is happening.
--- - **job** (`string` or `table`, optional): Job(s) required to access the shop.
--- - **gang** (`string` or `table`, optional): Gang(s) required to access the shop.
---
---@usage
--- ```lua
--- openShop({
--- shop = "weapon_shop",
--- items = weaponShopItems,
--- coords = vector3(100.0, 200.0, 300.0),
--- job = "police",
--- })
--- ```
function openShop(data)
if (data.job or data.gang) and not jobCheck(data.job or data.gang) then return end
if isStarted(OXInv) then
exports[OXInv]:openInventory('shop', { type = data.shop })
elseif isStarted(QBInv) then
if QBInvNew then
TriggerServerEvent(getScript()..':server:OpenShopNewQB', data.shop) -- i hate qb-inv
else
TriggerServerEvent(Config.General.JimShops and "jim-shops:ShopOpen" or "inventory:server:OpenInventory", "shop", data.items.label, data.items)
end
else
TriggerServerEvent(Config.General.JimShops and "jim-shops:ShopOpen" or "inventory:server:OpenInventory", "shop", data.items.label, data.items)
end
lookEnt(data.coords)
end
--- Server event handler for opening a new QB inventory shop.
---
--- This event is triggered when using the new QB inventory system.
---
---@param data table The shop data to open.
RegisterNetEvent(getScript()..':server:OpenShopNewQB', function(data)
exports[QBInv]:OpenShop(source, data)
end)
--- Server-side callback registration for checking if the player can carry items.
if isServer() then
createCallback(getScript()..':server:canCarry', function(source, itemTable) local result = canCarry(itemTable, source) return result end)
end

View File

@@ -1,53 +1,88 @@
local radarTable = {} --[[
Text Drawing Module
---------------------
This module provides functions to display and hide text on screen using
various frameworks: QB, OX, GTA, and ESX.
]]
--- Displays text on the screen using the configured draw text system. --- Displays text on the screen using the configured draw text system.
--- ---
--- This function handles displaying text with optional images or icons using different frameworks like 'qb', 'ox', 'gta', and 'esx'. --- Depending on Config.System.drawText, this function will use different methods to
--- display text along with optional images/icons.
--- ---
---@param image string|nil An optional image or icon to display with the text. Can be a URL, path, or a reference to an icon. --- @param image string|nil Optional image/icon identifier to display with the text.
---@param input table A table of strings, each representing a line of text to display. --- @param input table An array of strings; each string is a line of text to display.
---@param style string|nil An optional style code for default GTA popups (e.g., '~g~' for green text). --- @param style string|nil Optional style code for default GTA popups (e.g., "~g~" for green).
---@param oxStyleTable table|nil An optional table specifying style parameters for the 'ox' draw text system. --- @param oxStyleTable table|nil Optional table specifying style parameters for the OX text UI.
--- ---
---@usage ---@usage
--- ```lua --- ```lua
--- drawText("img_link", { "Test line 1", "Test Line 2" }, "~g~") --- drawText("img_link", { "Test line 1", "Test Line 2" }, "~g~")
--- ``` --- ```
function drawText(image, input, style, oxStyleTable) local text = "" function drawText(image, input, style, oxStyleTable)
local text = ""
if not radarTable then radarTable = {} end
if Config.System.drawText == "qb" then if Config.System.drawText == "qb" then
-- Concatenate lines for QB system with HTML line breaks.
for i = 1, #input do for i = 1, #input do
text = text..input[i].."</span>"..(input[i+1] ~= nil and "<br>" or "") end text = text..input[i].."</span>"..(input[i + 1] and "<br>" or "")
local text = text:gsub("%:", ":<span style='color:yellow'>") end
text = text:gsub("%:", ":<span style='color:yellow'>")
if image then if image then
text = '<img src="'..(radarTable[image] or nil)..'" style="width:12px;height:12px">'..text text = '<img src="'..(radarTable[image] or "")..'" style="width:12px;height:12px">'..text
end end
exports[QBExport]:DrawText(text, 'left') exports[QBExport]:DrawText(text, 'left')
elseif Config.System.drawText == "ox" then elseif Config.System.drawText == "ox" then
-- Append newline spacing to each input line.
for k, v in pairs(input) do for k, v in pairs(input) do
input[k] = v.." \n" input[k] = v.." \n"
end end
lib.showTextUI(table.concat(input), { icon = (image and radarTable[image] or image) or nil, position = 'left-center', style = oxStyleTable }) lib.showTextUI(table.concat(input), { icon = (image and radarTable[image] or image) or nil, position = 'left-center', style = oxStyleTable })
elseif Config.System.drawText == "gta" then elseif Config.System.drawText == "gta" then
for i = 1, #input do if input[i] ~= "" then text = text..input[i].."\n~s~" end end -- Concatenate input lines and apply GTA style formatting.
if image then text = "~BLIP_"..image.."~ "..text end
DisplayHelpMsg(text:gsub("%:", ":~"..(style or "g").."~"))
elseif Config.System.drawText == "esx" then
for i = 1, #input do for i = 1, #input do
text = text..input[i].."</span>"..(input[i+1] ~= nil and "<br>" or "") end if input[i] ~= "" then
local text = text:gsub("%:", ":<span style='color:yellow'>") text = text..input[i].."\n~s~"
end
end
if image then if image then
text = '<img src="'..radarTable[image]..'" style="width:12px;height:12px">'..text text = "~BLIP_"..image.."~ "..text
end
DisplayHelpMsg(text:gsub("%:", ":~"..(style or "g").."~"))
elseif Config.System.drawText == "esx" then
-- ESX-based text UI uses similar HTML formatting as QB.
for i = 1, #input do
text = text..input[i].."</span>"..(input[i + 1] and "<br>" or "")
end
text = text:gsub("%:", ":<span style='color:yellow'>")
if image then
text = '<img src="'..(radarTable[image] or "")..'" style="width:12px;height:12px">'..text
end end
ESX.TextUI(text, nil) ESX.TextUI(text, nil)
elseif Config.System.drawText == "red" then
-- Concatenate input lines and apply GTA style formatting.
for i = 1, #input do
if input[i] ~= "" then
text = text..input[i].."\n~q~"
end
end
TriggerEvent("jim-redui:DrawText", text)
end end
end end
--- Hides any text currently being displayed on the screen. --- Hides any text currently displayed on the screen.
--- ---
--- This function clears the text displayed by the `drawText` function, using the appropriate method based on the configured draw text system. --- Clears the text using the appropriate method for the configured draw text system.
---
--- @usage
--- ```lua
--- hideText()
--- ```
function hideText() function hideText()
if Config.System.drawText == "qb" then if Config.System.drawText == "qb" then
exports[QBExport]:HideText() exports[QBExport]:HideText()
@@ -57,5 +92,7 @@ function hideText()
ClearAllHelpMessages() ClearAllHelpMessages()
elseif Config.System.drawText == "esx" then elseif Config.System.drawText == "esx" then
ESX.HideUI() ESX.HideUI()
elseif Config.System.drawText == "red" then
TriggerEvent("jim-redui:HideText")
end end
end end

View File

@@ -1,53 +1,81 @@
-- DUI STUFF -- * Experimental * -- if gameName ~= "rdr3" then
--[[
DUI Module (Experimental)
--------------------------
This module handles the creation, modification, and removal of custom DUI (Display UI)
elements using runtime textures. It supports both client and server functionality to update DUI
images dynamically.
]]
-- Create a runtime texture dictionary on the client if not running on the server.
scriptTxd = not isServer() and CreateRuntimeTxd(getScript()..'scriptTxd') or nil scriptTxd = not isServer() and CreateRuntimeTxd(getScript()..'scriptTxd') or nil
customDUIList = {} customDUIList = {}
-- DUI CLIENT -------------------------------------------------------------
-- DUI Client Functions
-------------------------------------------------------------
--- Creates or updates a DUI element.
---
--- @param name string The unique name for the DUI element.
--- @param http string The URL to load into the DUI.
--- @param size table A table with .x and .y fields specifying the DUI dimensions.
--- @param txd table The runtime texture dictionary where the DUI texture will be created.
--- @usage
--- ```lua
--- createDui("logo", "https://example.com/logo.png", { x = 512, y = 256 }, scriptTxd)
--- ```
function createDui(name, http, size, txd) function createDui(name, http, size, txd)
--print(name, http, size, txd)
if not customDUIList[name] then if not customDUIList[name] then
local newTxt = CreateDui(http, math.floor(size.x), math.floor(size.y)) local newDui = CreateDui(http, math.floor(size.x), math.floor(size.y))
while not GetDuiHandle(newTxt) do Wait(0) end while not GetDuiHandle(newDui) do Wait(0) end
CreateRuntimeTextureFromDuiHandle(txd, name, GetDuiHandle(newTxt)) CreateRuntimeTextureFromDuiHandle(txd, name, GetDuiHandle(newDui))
customDUIList[name] = newTxt customDUIList[name] = newDui
SetDuiUrl(customDUIList[name], http) SetDuiUrl(customDUIList[name], http)
else else
SetDuiUrl(customDUIList[name], http) SetDuiUrl(customDUIList[name], http)
end end
end end
--- Opens a DUI selection input allowing the user to change the DUI image URL.
---
--- @param data table A table containing DUI data:
--- - name: The key name in the DUI list.
--- - texn: The texture name.
--- - texd: The texture dictionary.
--- - size: A table with .x and .y dimensions.
---
--- @usage
--- ```lua
--- DuiSelect({ name = "logo", texn = "logoTex", texd = "someTxd", size = { x = 512, y = 256 } })
--- ```
function DuiSelect(data) function DuiSelect(data)
local image = "" local imagePreview = "![test]("..data.url..")"
for k, v in pairs(duiList[data.name]) do --local imagePreview = "<center>- Current Image -<br>" ..
if v.tex.texn == data.texn then -- "<img src="..data.url.." width=150px><br>" ..
if duiList[data.name][k] then -- "Size: ["..math.floor(data.size.x)..", "..math.floor(data.size.y).."]<br><br>"
image = "<center>- Current Image -<br>"..
"<img src="..duiList[data.name][k].url.." width=150px><br>".. local dialog = createInput(imagePreview, {
"Size: ["..math.floor(data.size.x)..", "..math.floor(data.size.y).."]<br><br>" { type = "text", text = "dui_url", name = "url", isRequired = true },
end })
end
end
local dialog = exports['qb-input']:ShowInput({
header = image..Loc[Config.Lan].menu["dui_new"],
submitText = Loc[Config.Lan].menu["dui_change"],
inputs = { { type = 'text', isRequired = true, name = 'url', text = Loc[Config.Lan].menu["dui_url"] } } })
if dialog then if dialog then
if not dialog.url then return end data.url = dialog.url or dialog[1]
data.url = dialog.url -- Scan URL for valid image extension and banned words.
--Scan the link to see if it has an image extention otherwise, stop here.
local searchList = { "png", "jpg", "jpeg", "gif", "webp", "bmp" } local searchList = { "png", "jpg", "jpeg", "gif", "webp", "bmp" }
--Scan the link for certain terms that will flag it and refuse to show it local banList = { "porn" }
local banList = { "porn" } -- I dunno, let me know what links people manage to find
local searchFound = false local searchFound = false
for k, v in pairs(searchList) do for _, ext in pairs(searchList) do
if string.find(tostring(data.url), tostring(v))then if string.find(tostring(data.url), ext) then
searchFound = true searchFound = true
break
end end
end end
for k, v in pairs(banList) do for _, banned in pairs(banList) do
if string.find(tostring(data.url), tostring(v)) then if string.find(tostring(data.url), banned) then
searchFound = false print("BANNED WORD: "..v) searchFound = false
print("BANNED WORD: "..banned)
break
end end
end end
if searchFound then if searchFound then
@@ -56,14 +84,16 @@ function DuiSelect(data)
end end
end end
--- Client event handler to update DUI elements.
RegisterNetEvent(getScript()..":Client:ChangeDUI", function(data) RegisterNetEvent(getScript()..":Client:ChangeDUI", function(data)
debugPrint("^6Bridge^7: ^2Recieving new DUI ^7- ^6"..data.url.."^7") debugPrint("^6Bridge^7: ^2Receiving new DUI ^7- ^6"..data.url.."^7")
if tostring(data.url) ~= "-" then if tostring(data.url) ~= "-" then
createDui(data.texn, tostring(data.url), data.size, scriptTxd) createDui(data.texn, tostring(data.url), data.size, scriptTxd)
AddReplaceTexture(tostring(data.texd), tostring(data.texn), getScript()..'scriptTxd', tostring(data.texn)) AddReplaceTexture(tostring(data.texd), tostring(data.texn), getScript().."scriptTxd", tostring(data.texn))
end end
end) end)
--- Client event handler to clear DUI elements.
RegisterNetEvent(getScript()..":Client:ClearDUI", function(data) RegisterNetEvent(getScript()..":Client:ClearDUI", function(data)
if customDUIList[tostring(data.texn)] then if customDUIList[tostring(data.texn)] then
RemoveReplaceTexture(tostring(data.texd), tostring(data.texn)) RemoveReplaceTexture(tostring(data.texd), tostring(data.texn))
@@ -73,50 +103,59 @@ RegisterNetEvent(getScript()..":Client:ClearDUI", function(data)
end end
end) end)
-- DUI SERVER -------------------------------------------------------------
-- DUI Server Functions
-------------------------------------------------------------
--- Server event handler to change DUI settings.
--- If no URL is provided, resets to the preset value.
RegisterNetEvent(getScript()..":Server:ChangeDUI", function(data) RegisterNetEvent(getScript()..":Server:ChangeDUI", function(data)
-- if no url given, "reset" it back to preset
if not data.url then if not data.url then
for k, v in pairs(duiList[data.name]) do debugPrint("^6Bridge^7: ^2Preset: ^6"..tostring(data.preset).."^7")
data.url = data.preset
else
for k, v in pairs(Locations[data.name].duiList) do
if v.tex.texn == data.texn then if v.tex.texn == data.texn then
debugPrint("^6Bridge^7: ^2Preset^7: ^6"..tostring(duiList[data.name][k].preset).."^7") Locations[data.name].duiList[k].url = data.url
data.url = duiList[data.name][k].preset
end end
end end
end end
-- if it has a url, update server DUI list and send to players
for k, v in pairs(duiList[data.name]) do
if v.tex.texn == data.texn then
duiList[data.name][k].url = data.url
end
end
debugPrint("^6Bridge^7: ^3DUI^2 Sending new DUI to all players^7 - ^6"..data.url.."^7") debugPrint("^6Bridge^7: ^3DUI^2 Sending new DUI to all players^7 - ^6"..data.url.."^7")
TriggerClientEvent(getScript()..":Client:ChangeDUI", -1, data) TriggerClientEvent(getScript()..":Client:ChangeDUI", -1, data)
end) end)
--- Server event handler to clear DUI settings.
RegisterNetEvent(getScript()..":Server:ClearDUI", function(data) RegisterNetEvent(getScript()..":Server:ClearDUI", function(data)
if data.url == "-" then if data.url == "-" then
for k, v in pairs(duiList[data.name]) do for k, v in pairs(Locations[data.name].duiList) do
if v.tex.texn == data.texn then if v.tex.texn == data.texn then
duiList[data.name][k].url = "-" Locations[data.name].duiList[k].url = "-"
end end
end end
end end
-- Clear the DUI from loading
TriggerClientEvent(getScript()..":Client:ClearDUI", -1, data) TriggerClientEvent(getScript()..":Client:ClearDUI", -1, data)
--duiList[tostring(data.tex)].url = ""
end) end)
AddEventHandler('onResourceStop', function(r) if r ~= getScript() then return end -------------------------------------------------------------
-- Resource Cleanup
-------------------------------------------------------------
onResourceStop(function()
for k, v in pairs(duiList or {}) do for k, v in pairs(duiList or {}) do
for i = 1, #v do for i = 1, #v do
RemoveReplaceTexture(tostring(v[i].tex.texd), tostring(v[i].tex.texn)) RemoveReplaceTexture(tostring(v[i].tex.texd), tostring(v[i].tex.texn))
end end
end end
end) end, true)
-------------------------------------------------------------
-- DUI List Callback (Server)
-------------------------------------------------------------
if isServer() then if isServer() then
createCallback(getScript()..":Server:duiList", function(source) createCallback(getScript()..":Server:duiList", function(source)
return duiList return duiList
end) end)
end end
end

View File

@@ -1,15 +1,19 @@
--- Utility Functions for Resource Management and Debugging --[[
--- Utility Functions for Resource Management and Debugging
--- This script provides a set of utility functions for managing resources, debugging, and handling various common tasks within the game environment. ----------------------------------------------------------
--- It includes functions for checking resource states, generating unique keys, formatting numbers and coordinates, handling JSON data, and more. This script provides a set of utility functions for managing resources,
debugging, and handling common tasks in the game environment.
It includes functions to check resource states, generate unique keys,
format numbers and coordinates, handle JSON data, perform raycasts, and more.
]]
--[[ Resource and Environment Checks ]]-- -------------------------------------------------------------
-- Resource and Environment Checks
-------------------------------------------------------------
--- Checks if a specific resource is started. --- Checks if a specific resource is started.
--- --- @param script string The name of the resource.
---@param script string The name of the resource to check. --- @return boolean boolean True if the resource state contains "start", false otherwise.
---@return boolean `true` if the resource state contains "start", otherwise `false`.
---
---@usage ---@usage
--- ```lua --- ```lua
--- if isStarted("myResource") then --- if isStarted("myResource") then
@@ -17,17 +21,17 @@
--- end --- end
--- ``` --- ```
function isStarted(script) function isStarted(script)
return GetResourceState(script):find("start") if not script then
print("^1Error^7: ^1Tried to check if ^3nil^2 was started^7, ^1returning ^4false^7")
return false
end
return GetResourceState(script):find("start") ~= nil
end end
local scriptName = nil local scriptName = nil
--- Retrieves the current resource name. --- Retrieves the current resource name, caching it for efficiency.
--- --- @return string string The current resource name.
--- Caches the resource name after the first call for efficiency.
---
--- @return string scriptName The name of the current resource.
---
--- @usage --- @usage
--- ```lua --- ```lua
--- local currentScript = getScript() --- local currentScript = getScript()
@@ -38,12 +42,8 @@ function getScript()
return scriptName return scriptName
end end
--- Determines if the current execution context is the server. --- Determines if the current context is the server.
--- --- @return boolean boolean True if running on the server, false otherwise.
--- Very helpful for shared files complaining about client functions running on server or vice versa
---
--- @return boolean Returns `true` if running on the server, otherwise `false`.
---
---@usage ---@usage
--- ```lua --- ```lua
--- if isServer() then --- if isServer() then
@@ -56,14 +56,32 @@ function isServer()
return IsDuplicityVersion() return IsDuplicityVersion()
end end
--[[ Debugging Functions ]]-- function checkExportExists(resource, export)
if not resource or not export then return false end
--- Prints debug messages if debugging mode is enabled. local exists = false
--- local ok, result = pcall(function()
--- Concatenates all arguments and prints them along with debug information. exists = type(exports[resource][export]) == "function"
--- end)
--- @param ... any Multiple arguments to be concatenated and printed.
--- if ok and exists then
debugPrint(("^3Export Check^7: ^5exports^7['^5%s^7']:^5%s^7() ^2Exists^7"):format(resource, export))
return true
else
debugPrint(("^3Export Check^7: ^5exports^7['^5%s^7']:^5%s^7() ^1Doesn^7'^1t Exist^7"):format(resource, export))
return false
end
end
-------------------------------------------------------------
-- Debugging and JSON Utilities
-------------------------------------------------------------
--- Prints debug messages if debugMode is enabled.
--- Concatenates all arguments and prints them with debug info.
--- @param ... any One or more values to print.
--- @usage --- @usage
--- ```lua --- ```lua
--- debugPrint("Player has joined:", playerName) --- debugPrint("Player has joined:", playerName)
@@ -71,15 +89,13 @@ end
function debugPrint(...) function debugPrint(...)
if debugMode then if debugMode then
local args = {...} local args = {...}
local output = table.concat(args, " ") -- Concatenate all arguments with a space local output = table.concat(args, " ")
print(output, getDebugInfo(debug.getinfo(2, "nSl"))) print(output, getDebugInfo(debug.getinfo(2, "nSl")))
end end
end end
--- Prints event-related debug messages if event debugging is enabled. --- Prints event-related debug messages if event debugging is enabled.
--- --- @param ... any One or more values to print.
--- @param ... any Multiple arguments to be printed.
---
--- @usage --- @usage
--- ```lua --- ```lua
--- eventPrint("Event triggered:", eventName) --- eventPrint("Event triggered:", eventName)
@@ -90,24 +106,22 @@ function eventPrint(...)
end end
end end
-- Function to recursively colorize the JSON data --- Returns the keys of a table in sorted order.
--- @param tbl table The table to sort keys for.
--- @return table table A sorted array of keys.
function getSortedKeys(tbl) function getSortedKeys(tbl)
local keys = {} local keys = {}
for k in pairs(tbl) do keys[#keys + 1] = k end for k in pairs(tbl) do keys[#keys + 1] = k end
table.sort(keys, function(a, b) table.sort(keys, function(a, b)
local numA, numB = tonumber(a), tonumber(b) local numA, numB = tonumber(a), tonumber(b)
if numA and numB then return numA < numB if numA and numB then return numA < numB else return tostring(a) < tostring(b) end
else return tostring(a) < tostring(b) end
end) end)
return keys return keys
end end
--- Recursively colorizes a table for debug printing. --- Recursively colorizes a table for debug printing.
---
--- @param tbl table The table to colorize. --- @param tbl table The table to colorize.
--- @return table colourizedTable The colorized table. --- @return table table A new table with colorized keys and values.
---
--- @usage
--- ```lua --- ```lua
--- local colorizedData = colorizeTable(myTable) --- local colorizedData = colorizeTable(myTable)
--- jsonPrint(colorizedData) --- jsonPrint(colorizedData)
@@ -116,18 +130,19 @@ function colorizeTable(tbl)
local newData, sortedKeys = {}, getSortedKeys(tbl) local newData, sortedKeys = {}, getSortedKeys(tbl)
for _, k in ipairs(sortedKeys) do for _, k in ipairs(sortedKeys) do
local v = tbl[k] local v = tbl[k]
newData["^6"..tostring(k).."^7"] = ((type(v) == "table") and colorizeTable(v)) or (type(v):find("vector") and formatCoord(v)) or "^2"..tostring(v).."^7" newData["^6"..tostring(k).."^7"] =
(type(v) == "table" and colorizeTable(v))
or (tostring(type(v)):find("vector") and formatCoord(v))
or "^2"..tostring(v).."^7"
end end
return newData return newData
end end
--- Encodes a table into an ordered JSON string with indentation. --- Encodes a table into an ordered JSON string with indentation.
---
--- @param data table The table to encode. --- @param data table The table to encode.
--- @param indent string The string used for indentation (e.g., " "). --- @param indent string The indentation string (e.g., " ").
--- @param level number The current indentation level. --- @param level number The current level of indentation.
--- @return string The formatted JSON string. --- @return string The formatted JSON string.
---
--- @usage --- @usage
--- ```lua --- ```lua
--- local jsonString = encodeOrderedJSON(myTable, " ", 0) --- local jsonString = encodeOrderedJSON(myTable, " ", 0)
@@ -143,10 +158,8 @@ function encodeOrderedJSON(data, indent, level)
return table.concat(jsonParts) return table.concat(jsonParts)
end end
--- Prints a table as a colorized and ordered JSON string if debugging mode is enabled. --- Prints a table as a colorized and ordered JSON string if debugMode is enabled.
---
--- @param data table The table to print. --- @param data table The table to print.
---
--- @usage --- @usage
--- ```lua --- ```lua
--- jsonPrint(myTable) --- jsonPrint(myTable)
@@ -158,9 +171,7 @@ function jsonPrint(data)
end end
--- Retrieves the current time formatted for debug prints. --- Retrieves the current time formatted for debug prints.
---
--- @return string string The formatted time string, e.g., "^7(14:23:45)". --- @return string string The formatted time string, e.g., "^7(14:23:45)".
---
--- @usage --- @usage
--- ```lua --- ```lua
--- local currentTime = GetPrintTime() --- local currentTime = GetPrintTime()
@@ -177,9 +188,7 @@ function GetPrintTime()
end end
--- Generates a unique 3-character alphanumeric key. --- Generates a unique 3-character alphanumeric key.
--- --- @return string string The generated key.
--- @return string GeneratedString A randomly generated 3-character string.
---
--- @usage --- @usage
--- ```lua --- ```lua
--- local uniqueKey = keyGen() --- local uniqueKey = keyGen()
@@ -187,20 +196,28 @@ end
--- ``` --- ```
function keyGen() function keyGen()
local charset = { local charset = {
"q","w","e","r","t","y","u","i","o","p","a","s","d","f","g","h","j","k","l","z","x","c","v","b","n","m", "q","w","e","r","t","y","u","i","o","p",
"Q","W","E","R","T","Y","U","I","O","P","A","S","D","F","G","H","J","K","L","Z","X","C","V","B","N","M", "a","s","d","f","g","h","j","k","l",
"z","x","c","v","b","n","m",
"Q","W","E","R","T","Y","U","I","O","P",
"A","S","D","F","G","H","J","K","L",
"Z","X","C","V","B","N","M",
"1","2","3","4","5","6","7","8","9","0" "1","2","3","4","5","6","7","8","9","0"
} }
local GeneratedID = "" local GeneratedID = ""
for i = 1, 3 do GeneratedID = GeneratedID..charset[math.random(1, #charset)] end for i = 1, 3 do
GeneratedID = GeneratedID..charset[math.random(1, #charset)]
end
return GeneratedID return GeneratedID
end end
-------------------------------------------------------------
-- Formatting and Vector Math Functions
-------------------------------------------------------------
--- Formats a number with commas as thousand separators. --- Formats a number with commas as thousand separators.
---
--- @param amount number The number to format. --- @param amount number The number to format.
--- @return string commaValue The formatted number string with commas. --- @return string string The formatted number.
---
--- @usage --- @usage
--- ```lua --- ```lua
--- local formattedNumber = cv(1000000) -- "1,000,000" --- local formattedNumber = cv(1000000) -- "1,000,000"
@@ -208,15 +225,17 @@ end
--- `` --- ``
function cv(amount) function cv(amount)
local formatted = tostring(amount or "0") local formatted = tostring(amount or "0")
while true do formatted, k = string.gsub(formatted, "^(-?%d+)(%d%d%d)", '%1,%2') if (k==0) then break end Wait(0) end while true do
formatted, k = string.gsub(formatted, "^(-?%d+)(%d%d%d)", '%1,%2')
if k == 0 then break end
Wait(0)
end
return formatted return formatted
end end
--- Formats a coordinate vector for debug printing. --- Formats a coordinate vector for debug printing.
--- --- @param coord table A vector3 or vector4 with x, y, z (and optional w).
--- @param coord table A vector3 or vector4 table with `x`, `y`, `z`, and optional `w` components. --- @return string string The formatted coordinate string.
--- @return string The formatted coordinate string with color codes.
---
--- @usage --- @usage
--- ```lua --- ```lua
--- local formattedCoord = formatCoord(vector3(100.0, 200.0, 300.0)) --- local formattedCoord = formatCoord(vector3(100.0, 200.0, 300.0))
@@ -233,47 +252,42 @@ function formatCoord(coord)
return "^5"..vecType.."^7("..components[1]..components[2]..components[3]..components[4].."^7)" return "^5"..vecType.."^7("..components[1]..components[2]..components[3]..components[4].."^7)"
end end
--- Calculates the center point of a list of zones (coordinates). --- Calculates the center point of a list of coordinates.
--- --- @param tbl table An array of vector3 coordinates.
--- @param table table A table of vector3 coordinates.
--- @return vector3 vector3 The center coordinate. --- @return vector3 vector3 The center coordinate.
---
--- @usage --- @usage
--- ```lua --- ```lua
--- local center = getCenterOfZones({vector3(100, 200, 300), vector3(110, 210, 310)}) --- local center = getCenterOfZones({vector3(100, 200, 300), vector3(110, 210, 310)})
--- print("Center of Zones:", center) --- print("Center of Zones:", center)
--- ``` --- ```
function getCenterOfZones(table) function getCenterOfZones(tbl)
local totalX, totalY, totalZ = 0, 0, 0 local totalX, totalY, totalZ = 0, 0, 0
for _, coord in ipairs(tbl) do
for _, coord in ipairs(table) do
totalX = totalX + coord.x totalX = totalX + coord.x
totalY = totalY + coord.y totalY = totalY + coord.y
totalZ = totalZ + coord.z totalZ = totalZ + coord.z
end end
local count = #tbl
local count = #table
return vector3(totalX / count, totalY / count, totalZ / count) return vector3(totalX / count, totalY / count, totalZ / count)
end end
--- Counts the number of keys in a table. --- Counts the number of keys in a table.
--- --- @param tbl table The table to count.
--- @param table table The table to count keys in. --- @return number number The key count.
--- @return number number The number of keys in the table.
---
--- @usage --- @usage
--- ```lua --- ```lua
--- local count = countTable(myTable) --- local count = countTable(myTable)
--- print("Number of keys:", count) --- print("Number of keys:", count)
--- ``` --- ```
function countTable(table) local i = 0 for keys in pairs(table) do i += 1 end return i end function countTable(tbl)
local i = 0
for _ in pairs(tbl) do i += 1 end
return i
end
--- Returns an iterator over a table's keys in sorted order.
--- Returns an iterator that iterates over a table's keys in sorted order.
---
--- @param t table The table to iterate over. --- @param t table The table to iterate over.
--- @return function function An iterator function. --- @return function An iterator function for sorted keys.
---
--- @usage --- @usage
--- ```lua --- ```lua
--- for k, v in pairsByKeys(myTable) do --- for k, v in pairsByKeys(myTable) do
@@ -281,7 +295,6 @@ function countTable(table) local i = 0 for keys in pairs(table) do i += 1 end re
--- end --- end
--- ``` --- ```
function pairsByKeys(t) function pairsByKeys(t)
local t = t
if not t then if not t then
print("^1Error^7: ^3Nil ^2table recieved for ^3pairsByKeys^7(), ^2setting to ^7{} ^2to prevent break^7") print("^1Error^7: ^3Nil ^2table recieved for ^3pairsByKeys^7(), ^2setting to ^7{} ^2to prevent break^7")
t = {} t = {}
@@ -289,24 +302,20 @@ function pairsByKeys(t)
local a = {} for n in pairs(t) do a[#a+1] = n end table.sort(a) local i = 0 local iter = function() i += 1 if a[i] == nil then return nil else return a[i], t[a[i]] end end return iter local a = {} for n in pairs(t) do a[#a+1] = n end table.sort(a) local i = 0 local iter = function() i += 1 if a[i] == nil then return nil else return a[i], t[a[i]] end end return iter
end end
--- Creates a new table with consecutive numerical indices sorted by the `id` field. --- Creates a new table with consecutive numerical indices sorted by the 'id' field.
--- --- @param originalTable table The table containing entries with an 'id' field.
--- @param originalTable table The original table with entries containing an `id` field. --- @return table table A sorted table with consecutive indices.
--- @return table The new table with sorted entries and consecutive `id` values.
---
--- @usage --- @usage
--- ```lua
--- local sortedTable = createConsecutiveTable(originalTable) --- local sortedTable = createConsecutiveTable(originalTable)
--- for i, entry in ipairs(sortedTable) do --- for i, entry in ipairs(sortedTable) do
--- print(i, entry) --- print(i, entry)
--- end --- end
--- ```
function createConsecutiveTable(originalTable) function createConsecutiveTable(originalTable)
local sortedEntries = {} local sortedEntries = {}
for _, entry in pairs(originalTable) do for _, entry in pairs(originalTable) do table.insert(sortedEntries, entry) end
table.insert(sortedEntries, entry) table.sort(sortedEntries, function(a, b) return a.id < b.id end)
end
table.sort(sortedEntries, function(a, b)
return a.id < b.id
end)
local newTable = {} local newTable = {}
for newIndex, entry in ipairs(sortedEntries) do for newIndex, entry in ipairs(sortedEntries) do
entry.id = newIndex entry.id = newIndex
@@ -315,94 +324,9 @@ function createConsecutiveTable(originalTable)
return newTable return newTable
end end
--[[ Drawing Functions ]]--
--- Draws 3D text at specified coordinates.
---
--- @param coord table A vector3 table with `x`, `y`, and `z` coordinates.
--- @param text string The text to display.
--- @param highlight boolean (optional) Whether to highlight certain parts of the text.
---
--- @usage
--- ```lua
--- CreateThread(function()
--- while true do
--- DrawText3D(vector3(100, 200, 300), "Hello World", true)
--- Wait(0)
--- end
--- end)
--- ```
function DrawText3D(coord, text, highlight)
SetTextScale(0.30, 0.30)
SetTextFont(0)
SetTextProportional(1)
SetTextColour(255, 255, 255, 215)
SetTextEntry("STRING")
SetTextCentre(true)
local totalLength = string.len(text)
local textMaxLength = textMaxLength or 99 -- max 99
local text = totalLength > textMaxLength and text:sub(1, totalLength - (totalLength - textMaxLength)) or text
AddTextComponentString(highlight and text:gsub("%~w~", "~y~") or text)
SetDrawOrigin(coord.x, coord.y, coord.z, 0)
DrawText(0.0, 0.0)
local count, length = GetLineCountAndMaxLength(text)
local padding = 0.005
local heightFactor = (count / 43) + padding
local weightFactor = (length / 150) + padding
local height = (heightFactor / 2) - padding / 1
local width = (weightFactor / 2) - padding / 1
DrawRect(0.0, height, width, heightFactor, 0, 0, 0, 150)
ClearDrawOrigin()
end
--- Displays a help message on the screen.
---
--- @param text string The text to display as a help message.
---
--- @usage
--- DisplayHelpMsg("Press E to interact")
function DisplayHelpMsg(text)
BeginTextCommandDisplayHelp("STRING")
AddTextComponentScaleform(text)
EndTextCommandDisplayHelp(0, true, false, -1)
end
--- Displays a "Saving/Loading" spinner with a custom message.
---
--- @param text string The message to display alongside the spinner.
---
--- @usage
--- ```lua
--- displaySpinner("Saving data...")
--- ```
function displaySpinner(text)
BeginTextCommandBusyspinnerOn('STRING')
AddTextComponentSubstringPlayerName(text)
EndTextCommandBusyspinnerOn(4)
end
--- Stops the "Saving/Loading" spinner.
---
--- This function is client-side only.
---
--- @usage
--- ```lua
--- stopSpinner()
--- ```
function stopSpinner()
if not isServer() then
BusyspinnerOff()
end
end
--- Concatenates a table of strings into a single string separated by newlines. --- Concatenates a table of strings into a single string separated by newlines.
--- --- @param tbl table The table containing strings.
--- @param tbl table A table containing string elements. --- @return string string The concatenated string.
--- @return string string The concatenated string with newline separators.
---
--- @usage --- @usage
--- ```lua --- ```lua
--- local combinedText = concatenateText({"Line 1", "Line 2", "Line 3"}) --- local combinedText = concatenateText({"Line 1", "Line 2", "Line 3"})
@@ -411,74 +335,69 @@ end
function concatenateText(tbl) function concatenateText(tbl)
local result = "" local result = ""
for i = 1, #tbl do for i = 1, #tbl do
result = result..tbl[i] result = result..tbl[i]..(i < #tbl and "\n" or "")
if i < #tbl then
result = result.."\n" -- Add newline only if it's not the last element
end
end end
return result return result
end end
--- Converts rotation to a direction vector. --- Converts a rotation (degrees) to a direction vector.
--- --- @param rot vector3 A vector3 with rotation values.
--- @param rot vector3 A vector3 containing rotation values --- @return vector3 vector3 The forward direction vector.
--- @return vector3 vector3 A vector3 representing the direction.
---
--- @usage --- @usage
--- ```lua --- ```lua
--- local direction = RotationToDirection({ z = 90 }) --- local direction = RotationToDirection({ z = 90 })
--- print(direction) --- print(direction)
--- ``` --- ```
function RotationToDirection(rot) function RotationToDirection(rot)
local adjust = (math.pi / 180) local adjust = math.pi / 180
return vec3(-math.sin(adjust * rot.z) * math.abs(math.cos(adjust * rot.x)), math.cos(adjust * rot.z) * math.abs(math.cos(adjust * rot.x)), math.sin(adjust * rot.x)) return vec3(
-math.sin(adjust * rot.z) * math.abs(math.cos(adjust * rot.x)),
math.cos(adjust * rot.z) * math.abs(math.cos(adjust * rot.x)),
math.sin(adjust * rot.x)
)
end end
--- Creates a simple text-based progress bar. --- Creates a basic progress bar string.
--- --- @param percentage number Completion percentage (0-100).
--- @param percentage number The completion percentage (0-100). --- @return string string The progress bar (e.g., "█████░░░░░").
--- @return string string A string representing the progress bar, e.g., "█████░░░░░".
---
--- @usage --- @usage
--- ```lua --- ```lua
--- local bar = basicBar(50) -- "█████░░░░░" --- local bar = basicBar(50) -- "█████░░░░░"
--- print(bar) --- print(bar)
--- ``` --- ```
function basicBar(percentage) function basicBar(percentage)
local percentage = math.ceil(percentage) local perc = math.ceil(percentage)
local totalBlocks = 10 local total = 10
local filledBlocks = math.floor((percentage / 100) * totalBlocks) local filled = math.floor((perc / 100) * total)
local emptyBlocks = totalBlocks - filledBlocks local empty = total - filled
return string.rep("", filled)..string.rep("", empty)
local bar = string.rep("", filledBlocks)..string.rep("", emptyBlocks)
return bar
end end
--- Normalizes a 3D vector. --- Normalizes a 3D vector.
--- --- @param vec vector3 A vector3 table.
--- @param vec vector3 A vector3 table with `x`, `y`, and `z` components. --- @return vector3 vector3 A normalized vector.
--- @return vector3 vector3 The normalized vector3.
---
--- @usage --- @usage
--- ```lua --- ```lua
--- local normalizedVec = normalizeVector(vector3(1, 2, 3)) --- local normalizedVec = normalizeVector(vector3(1, 2, 3))
--- print(normalizedVec) --- print(normalizedVec)
--- ``` --- ```
function normalizeVector(vec) function normalizeVector(vec)
local length = math.sqrt(vec.x * vec.x + vec.y * vec.y + vec.z * vec.z) local len = math.sqrt(vec.x^2 + vec.y^2 + vec.z^2)
if length ~= 0 then if len ~= 0 then
return vec3(vec.x / length, vec.y / length, vec.z / length) return vec3(vec.x / len, vec.y / len, vec.z / len)
else else
return vec3(0, 0, 0) return vec3(0, 0, 0)
end end
end end
--- Draws a line between two coordinates for debugging purposes. -------------------------------------------------------------
--- -- Drawing and Raycasting Functions
--- @param startCoords vector3 A vector3 table representing the start point. -------------------------------------------------------------
--- @param endCoords vector3 A vector3 table representing the end point.
--- @param col vector4 A table with `x`, `y`, `z`, `w` representing the color and opacity. --- Draws a line between two coordinates (for debugging).
--- --- @param startCoords vector3 The starting coordinate.
--- @param endCoords vector3 The ending coordinate.
--- @param col vector4 A vector4 specifying color and opacity.
--- @usage --- @usage
--- ```lua --- ```lua
--- drawLine(vector3(100, 200, 300), vector3(150, 250, 350), vector4(255, 0, 0, 255)) --- drawLine(vector3(100, 200, 300), vector3(150, 250, 350), vector4(255, 0, 0, 255))
@@ -486,21 +405,19 @@ end
function drawLine(startCoords, endCoords, col) function drawLine(startCoords, endCoords, col)
if debugMode then if debugMode then
CreateThread(function() CreateThread(function()
local showCount = 1000 local count = 1000
while showCount >= 0 do while count >= 0 do
DrawLine(startCoords.x, startCoords.y, startCoords.z, endCoords.x, endCoords.y, endCoords.z, col.x, col.y, col.z, col.w) DrawLine(startCoords.x, startCoords.y, startCoords.z, endCoords.x, endCoords.y, endCoords.z, col.x, col.y, col.z, col.w)
showCount -= 10 count -= 10
Wait(0) Wait(0)
end end
end) end)
end end
end end
--- Draws a sphere at specified coordinates for debugging purposes. --- Draws a sphere at the specified coordinates (for debugging).
--- --- @param coords vector3 The center of the sphere.
--- @param coords vector3 A vector3 table representing the center of the sphere. --- @param col vector4 A vector4 specifying color and opacity.
--- @param col vector4 A table with `x`, `y`, `z`, `w` representing the color and opacity.
---
--- @usage --- @usage
--- ```lua --- ```lua
--- drawSphere(vector3(100, 200, 300), vector4(0, 255, 0, 255)) --- drawSphere(vector3(100, 200, 300), vector4(0, 255, 0, 255))
@@ -508,24 +425,22 @@ end
function drawSphere(coords, col) function drawSphere(coords, col)
if debugMode then if debugMode then
CreateThread(function() CreateThread(function()
local showCount = 1000 local count = 1000
while showCount >= 0 do while count >= 0 do
DrawSphere(coords.x, coords.y, coords.z, 0.5, col.x, col.y, col.z, col.w) DrawSphere(coords.x, coords.y, coords.z, 0.5, col.x, col.y, col.z, col.w)
showCount -= 1 count -= 1
Wait(10) Wait(10)
end end
end) end)
end end
end end
--- Performs a raycast between two coordinates and returns the result. --- Performs a raycast between two coordinates and returns the results.
--- --- @param startCoords vector3 The starting coordinate.
--- @param startCoords table A vector3 table representing the start point. --- @param endCoords vector3 The ending coordinate.
--- @param endCoords table A vector3 table representing the end point. --- @param entity number|nil An entity to ignore.
--- @param entity number|nil The entity to ignore during the raycast. --- @param flags number|nil Optional raycast flags (default: 4294967295).
--- @param flags number|nil Raycast flags to customize the raycast behavior. Defaults to `4294967295`. --- @return multiple Multiple values returned by GetShapeTestResultIncludingMaterial.
--- @return multiple multiple Returns multiple values from `GetShapeTestResultIncludingMaterial`.
---
--- @usage --- @usage
--- ```lua --- ```lua
--- local hit, hitPos, material = PerformRaycast(startVec, endVec, playerPed, 1) --- local hit, hitPos, material = PerformRaycast(startVec, endVec, playerPed, 1)
@@ -536,46 +451,40 @@ end
--- ``` --- ```
function PerformRaycast(startCoords, endCoords, entity, flags) function PerformRaycast(startCoords, endCoords, entity, flags)
drawLine(startCoords, endCoords, vec4(0,0,255,255)) drawLine(startCoords, endCoords, vec4(0,0,255,255))
local val1, val2, val3, val4, val5, val6 = GetShapeTestResult(StartExpensiveSynchronousShapeTestLosProbe(startCoords.x, startCoords.y, startCoords.z, endCoords.x, endCoords.y, endCoords.z, flags or 4294967295, entity, 0)) local val1, val2, val3, val4, val5, val6 = GetShapeTestResult(
if val2 then StartExpensiveSynchronousShapeTestLosProbe(
--drawSphere(val3, vec4(255, 0, 255, 0.5)) startCoords.x, startCoords.y, startCoords.z,
end endCoords.x, endCoords.y, endCoords.z,
flags or 4294967295, entity, 0
)
)
return val1, val2, val3, val4, val5, val6 return val1, val2, val3, val4, val5, val6
end end
--- Adjusts the Z-coordinate of a position to align with the ground. --- Adjusts the Z-coordinate of a position to the ground level.
--- --- @param coords vector4 A vector3 or vector4 with x, y, z (and optional w).
--- @param coords vector4 A vector3 or vector4 table with `x`, `y`, `z`, and optional `w` components. --- @return vector3|vector4 vector The coordinates adjusted for ground level.
--- @return vector3|vector4 vector adjusted coordinate with the Z value set to the ground level.
---
--- @usage --- @usage
--- ```lua --- ```lua
--- local groundCoords = adjustForGround(playerCoords) --- local groundCoords = adjustForGround(playerCoords)
--- print("Ground Position:", groundCoords) --- print("Ground Position:", groundCoords)
--- ``` --- ```
function adjustForGround(coords) function adjustForGround(coords)
local coords = coords
local foundGround, zPos = GetGroundZFor_3dCoord(coords.x, coords.y, coords.z + 1.0) local foundGround, zPos = GetGroundZFor_3dCoord(coords.x, coords.y, coords.z + 1.0)
if foundGround then if foundGround then
if coords.w then if coords.w then
coords = vec4(coords.x, coords.y, zPos, coords.w) return vec4(coords.x, coords.y, zPos, coords.w)
else else
coords = vec3(coords.x, coords.y, zPos) return vec3(coords.x, coords.y, zPos)
end end
--debugPrint("^6Bridge^7: Adjusting for ground pos ", coords.z, zPos)
return coords
else else
return coords return coords
end end
end end
--- Ensures that a network vehicle exists by verifying its network ID. --- Ensures a network vehicle exists from its network ID.
--- --- @param vehNetID number The network ID.
--- @param vehNetID number The network ID of the vehicle. --- @return number number The vehicle entity, or 0 if not found.
--- @return number number The vehicle entity if it exists, otherwise `0`.
---
--- @usage --- @usage
--- ```lua --- ```lua
--- local vehicle = ensureNetToVeh(netID) --- local vehicle = ensureNetToVeh(netID)
@@ -584,7 +493,7 @@ end
--- end --- end
--- ``` --- ```
function ensureNetToVeh(vehNetID) function ensureNetToVeh(vehNetID)
debugPrint("^6Bridge^7: ^3ensureNetToVeh^7: ^2Requesting NetworkDoesNetworkIdExist^7(^6"..vehNetID.."^7)") --debugPrint("^6Bridge^7: ^3ensureNetToVeh^7: ^2Requesting NetworkDoesNetworkIdExist^7(^6"..vehNetID.."^7)")
local timeout = 100 local timeout = 100
while not NetworkDoesNetworkIdExist(vehNetID) and timeout > 0 do while not NetworkDoesNetworkIdExist(vehNetID) and timeout > 0 do
timeout -= 1 timeout -= 1
@@ -601,18 +510,18 @@ function ensureNetToVeh(vehNetID)
return vehicle return vehicle
end end
--- Ensures that a network entity exists by verifying its network ID. --- Ensures a network entity exists from its network ID.
--- --- @param entNetID number The network ID.
--- @param entNetID number The network ID of the entity. --- @return number number The entity, or 0 if not found.
--- @return number The entity if it exists, otherwise `0`.
---
--- @usage --- @usage
--- ```lua
--- local entity = ensureNetToEnt(netID) --- local entity = ensureNetToEnt(netID)
--- if entity ~= 0 then --- if entity ~= 0 then
--- print("Entity exists:", entity) --- print("Entity exists:", entity)
--- end --- end
--- ```
function ensureNetToEnt(entNetID) function ensureNetToEnt(entNetID)
debugPrint("^6Bridge^7: ^3ensureNetToEnt^7: ^2Requesting NetworkDoesNetworkIdExist^7(^6"..entNetID.."^7)") --debugPrint("^6Bridge^7: ^3ensureNetToEnt^7: ^2Requesting NetworkDoesNetworkIdExist^7(^6"..entNetID.."^7)")
local timeout = 100 local timeout = 100
while not NetworkDoesNetworkIdExist(entNetID) and timeout > 0 do while not NetworkDoesNetworkIdExist(entNetID) and timeout > 0 do
timeout -= 1 timeout -= 1
@@ -629,7 +538,58 @@ function ensureNetToEnt(entNetID)
return entity return entity
end end
--[[ Material Definitions ]]-- function sendLog(text)
local Player = getPlayer()
local coords = GetEntityCoords(PlayerPedId())
local _, _, _, hour, min, sec = GetLocalTime()
local data = {
script = debug.getinfo(2, "nSl"),
coords = coords,
localTime = { hour = hour, min = min, sec = sec },
firstname = Player.firstname,
lastname = Player.lastname,
source = Player.source,
id = Player.citizenId,
text = text,
}
debugPrint("^5Log Message^7: "..getScript().." - "..Player.firstname.." "..Player.lastname.."("..Player.source..") ["..Player.citizenId.."]", text)
TriggerServerEvent(getScript()..":server:sendlog", data)
end
function sendServerLog(data)
local hour, min, sec = os.date('%H'), os.date('%M'), os.date('%S')
data.serverTime = { house = hour, min = min, sec = sec }
--jsonPrint(data)
debugPrint("^5Log Message^7: "..getScript().." - "..data.firstname.." "..data.lastname.."("..data.source..") ["..data.id.."]", data.text)
-- Add your logger here
end
RegisterNetEvent(getScript()..":server:sendlog", sendServerLog)
-- This function was created to help create random numbers
-- When you create a table of items with a random hunger value for example
-- `hunger = math.random(10, 20)` this will be set at script start and never change
-- using `hunger = {10, 20}` and then calling this function will make it generate a random number every time
-- It also fallsback if it simply recieved a number instead of a table
-- For example:
-- local hunger = {10, 20}
-- local hungerAmount = GetRandomTiming(hunger)
-- print(hungerAmount) -- number between 10, 20
function GetRandomTiming(tbl)
if type(tbl) == "table" then
return math.random(tbl[1], tbl[2])
else
return tbl
end
end
-------------------------------------------------------------
-- Material and Prop Functions
-------------------------------------------------------------
--- A table mapping material names to their corresponding hash values. --- A table mapping material names to their corresponding hash values.
--- ---
@@ -851,22 +811,17 @@ local materials = {
temp_30 = 13626292 temp_30 = 13626292
} }
--- Retrieves the ground material at a specified position. --- Retrieves the ground material at a given position.
--- --- @param coords vector3 The coordinate to test.
--- This function performs a raycast downwards from the given coordinates to determine the material type of the ground. --- @return number|nil number The material hash if hit, nil otherwise.
--- --- @return string string The material name.
--- @param coords vector3 The coordinates from which to perform the raycast.
--- @return number|nil number The material hash if found; otherwise, `nil`.
--- @return string string The name of the material.
---
--- @usage --- @usage
--- ```lua --- ```lua
--- local materialHash, materialName = GetGroundMaterialAtPosition(vector3(100, 200, 300)) --- local matHash, matName = GetGroundMaterialAtPosition(vector3(100,200,300))
--- print("Ground material:", materialName) --- print("Material:", matName)
--- ``` --- ```
function GetGroundMaterialAtPosition(coords) function GetGroundMaterialAtPosition(coords)
local endX, endY, endZ = coords.x, coords.y, coords.z - 1.0 local endX, endY, endZ = coords.x, coords.y, coords.z - 1.0
local rayHandle = StartShapeTestCapsule(coords.x, coords.y, coords.z, endX, endY, endZ, 1.0, 1, playerPed, 7) local rayHandle = StartShapeTestCapsule(coords.x, coords.y, coords.z, endX, endY, endZ, 1.0, 1, playerPed, 7)
local _, hit, _, _, materialHash, _ = GetShapeTestResultIncludingMaterial(rayHandle) local _, hit, _, _, materialHash, _ = GetShapeTestResultIncludingMaterial(rayHandle)
local materialName = "Unknown" local materialName = "Unknown"
@@ -876,14 +831,10 @@ function GetGroundMaterialAtPosition(coords)
break break
end end
end end
if hit then return materialHash, materialName if hit then return materialHash, materialName else return nil, materialName end
else return nil, materialName end
end end
--- Retrieves the dimensions of a prop/model. --- Retrieves the dimensions (width, depth, height) of a prop/model.
---
--- This function loads the specified model and returns its width, depth, and height based on its bounding box.
---
--- @param model string The name or hash of the model. --- @param model string The name or hash of the model.
--- @return number number The width of the prop. --- @return number number The width of the prop.
--- @return number number The depth of the prop. --- @return number number The depth of the prop.

View File

@@ -1,25 +1,28 @@
-- INPUT -- --[[
-- Multiscript input script function to create simple input text boxes -- Input Dialog Module
---------------------
This module provides a function to create a simple input dialog compatible with
multiple menu systems (OX, QB, GTA/WarMenu, and ESX). It supports various input
types such as radio buttons, numbers, text, and select dropdowns.
--- Creates a simple input dialog compatible with multiple menu systems. ]]
--- Creates a simple input dialog using the configured menu system.
--- ---
--- This function generates input dialogs for different frameworks (OX, QB, GTA) based on the configuration. --- @param title string The title or header of the input dialog.
--- It supports various input types such as radio buttons, numbers, text, and select dropdowns. --- @param opts table A table of input option definitions. Each option should include:
--- - type (string): The input type ("radio", "number", "text", "select").
--- - label (string, optional): A label for the input (used in radio/select for OX).
--- - text (string, optional): The text prompt for the input.
--- - name (string): The identifier for the input.
--- - isRequired (boolean, optional): Whether input is mandatory.
--- - default (any, optional): The default value.
--- - options (table, optional): A table of choices for "radio" and "select" types.
--- - min (number, optional): Minimum value (for "number" and "select").
--- - max (number, optional): Maximum value.
--- - txt (string, optional): Additional description.
--- ---
---@param title string The title/header of the input dialog. --- @return table|nil table Returns the user's input as a table if submitted, otherwise nil.
---@param opts table A table containing input options. Each option should have a `type` and other relevant fields based on the type.
--- - **type** (`string`): The type of input. Supported types: "radio", "number", "text", "select".
--- - **label** (`string`, optional): The label for the input (used for "radio" and "select" types in OX).
--- - **text** (`string`, optional): The text prompt for the input.
--- - **name** (`string`): The identifier name for the input.
--- - **isRequired** (`boolean`, optional): Whether the input is required.
--- - **default** (`any`, optional): The default value for the input.
--- - **options** (`table`, optional): A table of options for "radio" and "select" types.
--- - **min** (`number`, optional): The minimum value (used for "select" type).
--- - **max** (`number`, optional): The maximum value (used for "number" and "select" types).
--- - **txt** (`string`, optional): Additional text or description for the input.
---
---@return table|nil table Returns the user's input as a table if the dialog is submitted, otherwise returns `nil`.
--- ---
---@usage ---@usage
--- ```lua --- ```lua
@@ -36,15 +39,17 @@
function createInput(title, opts) function createInput(title, opts)
local dialog = nil local dialog = nil
local options = {} local options = {}
local currentNum = 0
if Config.System.Menu == "ox" then if Config.System.Menu == "ox" then
for i = 1, #opts do for i = 1, #opts do
currentNum += 1
if opts[i] == nil then currentNum -= 1 goto skip end
if opts[i].type == "radio" then if opts[i].type == "radio" then
-- Convert radio options to select type for OX -- Convert radio options to select type for OX
for k in pairs(opts[i].options) do for k in pairs(opts[i].options) do
opts[i].options[k].label = opts[i].options[k].text opts[i].options[k].label = opts[i].options[k].text
end end
options[i] = { options[currentNum] = {
type = "select", type = "select",
isRequired = opts[i].isRequired, isRequired = opts[i].isRequired,
label = opts[i].label or opts[i].text, label = opts[i].label or opts[i].text,
@@ -54,16 +59,16 @@ function createInput(title, opts)
} }
end end
if opts[i].type == "number" then if opts[i].type == "number" then
options[i] = { options[currentNum] = {
type = "number", type = opts[i].type,
label = opts[i].text..(opts[i].txt and " - "..opts[i].txt or ""), label = (opts[i].label or opts[i].text)..(opts[i].txt and " - "..opts[i].txt or ""),
isRequired = opts[i].isRequired, isRequired = opts[i].isRequired,
name = opts[i].name, name = opts[i].name,
options = opts[i].options, options = opts[i].options,
} }
end end
if opts[i].type == "text" then if opts[i].type == "text" then
options[i] = { options[currentNum] = {
type = "input", type = "input",
label = opts[i].text..(opts[i].txt and " - "..opts[i].txt or ""), label = opts[i].text..(opts[i].txt and " - "..opts[i].txt or ""),
default = opts[i].default, default = opts[i].default,
@@ -71,8 +76,8 @@ function createInput(title, opts)
} }
end end
if opts[i].type == "select" then if opts[i].type == "select" then
options[i] = { options[currentNum] = {
type = "select", type = opts[i].type,
label = opts[i].text..(opts[i].txt and " - "..opts[i].txt or ""), label = opts[i].text..(opts[i].txt and " - "..opts[i].txt or ""),
isRequired = opts[i].isRequired, isRequired = opts[i].isRequired,
name = opts[i].name, name = opts[i].name,
@@ -82,17 +87,58 @@ function createInput(title, opts)
default = opts[i].default, default = opts[i].default,
} }
end end
if opts[i].type == "checkbox" then
jsonPrint(opts[i])
for k in pairs(opts[i].options) do
if options[currentNum] then currentNum += 1 end
options[currentNum] = {
type = opts[i].type,
label = opts[i].options[k].text..(opts[i].txt and " - "..opts[i].txt or ""),
name = opts[i].options[k].value,
}
end
end
if opts[i].type == "color" then
options[currentNum] = {
type = opts[i].type,
label = opts[i].label,
isRequired = opts[i].isRequired,
format = opts[i].format,
default = opts[i].default,
}
end
if opts[i].type == "slider" then
options[currentNum] = {
type = opts[i].type,
label = opts[i].label,
isRequired = opts[i].required,
min = opts[i].min,
max = opts[i].max,
default = opts[i].default,
}
end
::skip::
end end
dialog = exports[OXLibExport]:inputDialog(title, options) dialog = exports[OXLibExport]:inputDialog(title, options)
return dialog return dialog
elseif Config.System.Menu == "qb" then
for k, v in pairs(opts) do
currentNum += 1
if opts[k] == nil then
currentNum -= 1
else
options[currentNum] = opts[k]
end end
end
if Config.System.Menu == "qb" then dialog = exports['qb-input']:ShowInput(
dialog = exports['qb-input']:ShowInput({ header = title, submitText = "Accept", inputs = opts }) { header = title, submitText = "Accept", inputs = options }
)
return dialog return dialog
end
if Config.System.Menu == "gta" then elseif Config.System.Menu == "gta" then
WarMenu.CreateMenu(tostring(opts), WarMenu.CreateMenu(tostring(opts),
title, title,
" ", " ",
@@ -152,5 +198,44 @@ function createInput(title, opts)
end end
Wait(0) Wait(0)
end end
elseif Config.System.Menu == "esx" then -- horrible input dialog, not even worth using, get OX
local results = {}
for i, opt in ipairs(opts) do
local prompt = opt.text or opt.label or "Enter value"
-- For radio/select types, append available options in the prompt.
if (opt.type == "radio" or opt.type == "select") and opt.options then
local choices = ""
for j, choice in ipairs(opt.options) do
choices = choices .. choice.text .. " (" .. tostring(choice.value) .. ")"
if j < #opt.options then choices = choices .. ", " end
end
prompt = prompt .. " [" .. choices .. "]"
elseif opt.type == "number" then
prompt = prompt .. " (number between " .. (opt.min or 0) .. " and " .. (opt.max or 100) .. ")"
end
local value = nil
ESX.UI.Menu.Open('dialog', getScript(), 'input_' .. i, {
title = prompt
}, function(data, menu)
value = data.value
menu.close()
end, function(data, menu)
menu.close()
end)
-- Wait until the player submits a value.
while value == nil do
Wait(0)
end
-- Convert to a number if needed.
if opt.type == "number" then
value = tonumber(value)
end
results[opt.name or i] = value
end
return results
end end
end end

246
shared/inventories.lua Normal file
View File

@@ -0,0 +1,246 @@
-------------------------------------------------------------
-- Item Availability & Inventory Retrieval
-------------------------------------------------------------
---
--- Locks or unlocks the player's inventory.
--- Freezes/unfreezes the player's position, sets inventory busy state, and toggles hotbar usage.
---
--- @param toggle boolean True to lock inventory; false to unlock.
---
--- @usage
--- ```lua
--- lockInv(true) -- Lock inventory.
--- lockInv(false) -- Unlock inventory.
--- ```
function lockInv(toggle)
FreezeEntityPosition(PlayerPedId(), toggle)
LocalPlayer.state:set("inv_busy", toggle, true)
LocalPlayer.state:set("invBusy", toggle, true)
TriggerEvent('inventory:client:busy:status', toggle)
TriggerEvent('canUseInventoryAndHotbar:toggle', not toggle)
end
--- Checks if a player has the specified items in their inventory.
---
--- Verifies whether the required quantities are present. Returns a boolean and a table of details.
---
--- @param items string|table A single item name or table with required amounts.
--- @param amount number The required quantity (default 1).
--- @param src number|nil Player source ID (defaults to caller).
--- @return boolean boolean True if all items are available; otherwise, false.
--- @return table|nil table Table detailing counts for each item.
---
---@usage
--- ```lua
--- local hasAll, details = hasItem({"health_potion", "mana_potion"}, 2, playerId)
--- if hasAll then
--- -- Proceed with action
--- else
--- -- Inform the player about missing items
--- end
--- ```
function hasItem(items, amount, src)
local amount = amount and amount or 1
local grabInv, foundInv = getPlayerInv(src)
if type(items) ~= "table" then items = { [items] = amount and amount or 1, } end
if grabInv then
local hasTable = {}
for item, amt in pairs(items) do
if not Items[item] then print("^4ERROR^7: ^2Script can't find ingredient item in Shared Items - ^1"..item.."^7") end
local count = 0
for _, itemData in pairs(grabInv) do
--jsonPrint(itemData)
if itemData and itemData.name == item then
count += (itemData.amount or itemData.count or 1)
end
end
foundInv = foundInv:gsub("%-", "^7-^6"):gsub("%_", "^7_^6")
local foundMessage = "^6Bridge^7: ^3hasItem^7[^6"..foundInv.."^7]: "..tostring(item).." ^3"..count.."^7/^3"..amt
if count >= amt then foundMessage = foundMessage.." ^5FOUND^7" else foundMessage = foundMessage .." ^1NOT FOUND^7" end
debugPrint(foundMessage)
hasTable[item] = { hasItem = count >= amt, count = count }
end
for k, v in pairs(hasTable) do
if not v.hasItem then
return false, hasTable
end
end
return true, hasTable
end
-- if can't find inventory, return false
print("^1Error^7: ^1Can't find players inventory for some reason")
return false, {}
end
--- Retrieves a player's inventory based on the active inventory system.
---
--- @param src number|nil The player source ID (if nil, retrieves current player's inventory).
--- @return table|nil table The inventory items.
--- @return string|nil string The name of the inventory system.
---
---@usage
--- ```lua
--- local inventory, system = getPlayerInv(playerId)
--- if inventory then
--- -- Process inventory
--- end
--- ```
function getPlayerInv(src)
local grabInv = nil
local foundInv = ""
if isStarted(OXInv) then
foundInv = OXInv
if src then
grabInv = exports[OXInv]:GetInventoryItems(src)
else
grabInv = exports[OXInv]:GetPlayerItems()
end
elseif isStarted(QSInv) then
foundInv = QSInv
if src then
grabInv = exports[QSInv]:GetInventory(src)
else
grabInv = exports[QSInv]:getUserInventory()
end
elseif isStarted(OrigenInv) then
foundInv = OrigenInv
if src then
grabInv = exports[OrigenInv]:getInventory(src)
else
grabInv = exports[OrigenInv]:getInventory()
end
elseif isStarted(CoreInv) then
foundInv = CoreInv
if src then
grabInv = exports[CoreInv]:getInventory(src)
else
grabInv = exports[CoreInv]:getInventory()
end
elseif isStarted(CodeMInv) then
foundInv = CodeMInv
if src then
grabInv = exports[CodeMInv]:GetInventory(getPlayer(src).citizenId, src)
else
grabInv = exports[CodeMInv]:getUserInventory()
end
elseif isStarted(TgiannInv) then
foundInv = TgiannInv
if src then
grabInv = exports[TgiannInv]:GetPlayerItems(src)
else
grabInv = exports[TgiannInv]:GetPlayerItems()
end
elseif isStarted(JPRInv) then
foundInv = JPRInv
if src then
grabInv = Core.Functions.GetPlayer(src).PlayerData.items
else
grabInv = Core.Functions.GetPlayerData().items
end
elseif isStarted(QBInv) then
foundInv = QBInv
if src then
grabInv = Core.Functions.GetPlayer(src).PlayerData.items
else
grabInv = Core.Functions.GetPlayerData().items
end
elseif isStarted(PSInv) then
foundInv = PSInv
if src then
grabInv = Core.Functions.GetPlayer(src).PlayerData.items
else
grabInv = Core.Functions.GetPlayerData().items
end
elseif ESX and isStarted(ESXExport) then
foundInv = ESX
if src then
local xPlayer = ESX.GetPlayerFromId(src)
grabInv = xPlayer.inventory
else
local xPlayer = ESX.GetPlayerData() -- Client side, if available
grabInv = xPlayer.inventory
end
elseif isStarted(RSGInv) then
foundInv = RSGInv
if src then
grabInv = Core.Functions.GetPlayer(src).PlayerData.items
else
grabInv = Core.Functions.GetPlayerData().items
end
else
print("^4ERROR^7: ^2No Inventory detected ^7- ^2Check ^3starter^1.^2lua^7")
end
return grabInv, foundInv
end
function isInventoryOpen()
return IsNuiFocused()
end
-------------------------------------------------------------
-- Item Image Retrieval
-------------------------------------------------------------
--- Retrieves the NUI link for an item's image from the active inventory system.
---
--- @param item string The item name.
--- @return string string A `nui://` link to the item's image, or an empty string if not found.
---
--- @usage
--- ```lua
--- local imageLink = invImg("health_potion")
--- if imageLink ~= "" then print(imageLink) end
--- ```
function invImg(item)
local imgLink = ""
if item ~= "" and Items[item] then
if isStarted(OXInv) then
imgLink = "nui://"..OXInv.."/web/images/"..(Items[item].image or "")
elseif isStarted(QSInv) then
imgLink = "nui://"..QSInv.."/html/images/"..(Items[item].image or "")
elseif isStarted(CoreInv) then
imgLink = "nui://"..CoreInv.."/html/img/"..(Items[item].image or "")
elseif isStarted(CodeMInv) then
imgLink = "nui://"..CodeMInv.."/html/itemimages/"..(Items[item].image or "")
elseif isStarted(OrigenInv) then
imgLink = "nui://"..OrigenInv.."/html/img/"..(Items[item].image or "")
elseif isStarted(JPRInv) then
imgLink = "nui://"..JPRInv.."/html/images/"..(Items[item].image or "")
elseif isStarted(QBInv) then
imgLink = "nui://"..QBInv.."/html/images/"..(Items[item].image or "")
elseif isStarted(PSInv) then
imgLink = "nui://"..PSInv.."/html/images/"..(Items[item].image or "")
elseif isStarted(TgiannInv) then
imgLink = "nui://inventory_images/images/"..(Items[item].image or "")
elseif isStarted(RSGInv) then
imgLink = "nui://"..RSGInv.."/html/images/"..(Items[item].image or "")
else
print("^4ERROR^7: ^2No Inventory detected for invImg - Check starter.lua")
end
end
return imgLink
end

View File

@@ -1,36 +1,72 @@
--[[
Animal Detection Module
-------------------------
This module determines whether a Ped is an animal and categorizes it as a cat, dog,
or other type (e.g., coyote). It uses predefined model hashes stored in the AnimalPeds table.
Global Flags:
- isCat, isDog, isBigDog, isSmallDog, isCoyote, isAnimal: Booleans to track the player's
current animal classification.
When running client-side (not on the server), the module checks the player's Ped after they load.
Usage Examples:
-- Check if the player's Ped is an animal:
local animalStatus = isPedAnimal()
-- Check if a given Ped is a cat:
if isCat(somePed) then print("This is a cat!") end
-- Determine if a Ped is a dog and whether it's big or small:
local isDogFlag, isBig = isDog(somePed)
-- Retrieve a flat list of all animal model hashes:
local allAnimalModels = getAnimalModels()
]]
-- Global animal classification flags.
isCat, isDog, isBigDog, isSmallDog, isCoyote, isAnimal = false, false, false, false, false, false isCat, isDog, isBigDog, isSmallDog, isCoyote, isAnimal = false, false, false, false, false, false
if not isServer() then if not isServer() then
onPlayerLoaded(function() onPlayerLoaded(function()
Wait(2000) Wait(2000)
-- Reset classification flags
isCat, isDog, isBigDog, isSmallDog, isCoyote = false, false, false, false, false isCat, isDog, isBigDog, isSmallDog, isCoyote = false, false, false, false, false
-- Check if the player's Ped is an animal.
isPedAnimal() isPedAnimal()
if isAnimal then if isAnimal then
local ped = PlayerPedId() local ped = PlayerPedId()
local pedModel = GetEntityModel(ped) local pedModel = GetEntityModel(ped)
-- Determine if the Ped is a cat:
-- Also treat 'ft-raccoon' as a cat unless it is 'ft-sphynx'
isCat = (isCat(ped) or pedModel == `ft-raccoon`) and (pedModel ~= `ft-sphynx`) isCat = (isCat(ped) or pedModel == `ft-raccoon`) and (pedModel ~= `ft-sphynx`)
-- Determine if the Ped is a dog and whether it's big:
isDog, isBigDog = isDog(ped) isDog, isBigDog = isDog(ped)
isSmallDog = not isBigDog isSmallDog = not isBigDog
if isDog and pedModel == `a_c_coyote` then isDog = false end if isDog and pedModel == `a_c_coyote` then isDog = false end
-- Determine if the Ped is a coyote (special case):
isCoyote = (pedModel == `ft-sphynx` or pedModel == `a_c_coyote`) isCoyote = (pedModel == `ft-sphynx` or pedModel == `a_c_coyote`)
-- Special override: if model is 'ft-capmonkey2', treat as a dog.
if pedModel == `ft-capmonkey2` then isDog = true end if pedModel == `ft-capmonkey2` then isDog = true end
end end
end, true) end, true)
--- Determines if a given Ped is classified as an animal. -------------------------------------------------------------
-- Animal Classification Functions
-------------------------------------------------------------
--- Determines whether a given Ped is classified as an animal.
--- ---
--- This function checks whether the specified Ped (or the player's Ped if none is provided) --- Checks if the Ped's model hash appears in any of the animal categories defined in AnimalPeds.
--- is listed within the predefined `AnimalPeds` tables. It iterates through all animal types
--- to verify if the Ped's model hash matches any known animal models.
--- ---
---@param ped number|nil Optional. The Ped entity to check. Defaults to the player's Ped (`PlayerPedId()`). --- @param ped number|nil Optional. The Ped entity to check. Defaults to the player's Ped.
--- --- @return boolean boolean True if the Ped is an animal, otherwise false.
---@return boolean `true` if the Ped is an animal, otherwise `false`.
--- ---
--- @usage --- @usage
--- ```lua --- ```lua
@@ -39,31 +75,24 @@ if not isServer() then
--- ``` --- ```
function isPedAnimal(ped) function isPedAnimal(ped)
local PedModel = GetEntityModel(ped or PlayerPedId()) local PedModel = GetEntityModel(ped or PlayerPedId())
for _, animalCategory in pairs(AnimalPeds) do
for _, animalTypeTable in pairs(AnimalPeds) do for animalModelHash, _ in pairs(animalCategory) do
for animalModelHash, _ in pairs(animalTypeTable) do
if PedModel == animalModelHash then if PedModel == animalModelHash then
isAnimal = true isAnimal = true
break debugPrint("^6Bridge^7: ^2Ped is Animal")
return true
end end
end end
if isAnimal then
debugPrint("^6Debug^7: ^2Ped is Animal^1")
break
end end
return false
end end
return isAnimal --- Checks if a given Ped is classified as a cat.
end
--- Checks if a given Ped is classified specifically as a cat.
--- ---
--- This function verifies whether the specified Ped (or the player's Ped if none is provided) --- Iterates through the CatPeds table and returns true if the Ped's model matches.
--- matches any of the model hashes listed under `AnimalPeds.CatPeds`. It returns `true` if a match is found.
--- ---
---@param ped number|nil Optional. The Ped entity to check. Defaults to the player's Ped (`PlayerPedId()`). --- @param ped number|nil Optional. The Ped entity to check. Defaults to the player's Ped.
--- --- @return boolean True if the Ped is a cat, otherwise false.
---@return boolean `true` if the Ped is a cat, otherwise `false`.
--- ---
---@usage ---@usage
--- ```lua --- ```lua
@@ -78,24 +107,20 @@ if not isServer() then
--- ``` --- ```
function isCat(ped) function isCat(ped)
local PedModel = GetEntityModel(ped or PlayerPedId()) local PedModel = GetEntityModel(ped or PlayerPedId())
for k, v in pairs(AnimalPeds.CatPeds) do for modelHash, _ in pairs(AnimalPeds.CatPeds) do
if PedModel == k then if PedModel == modelHash then
return true return true
end end
end end
return false return false
end end
--- Determines if a given Ped is classified as a dog and identifies its size category. --- Determines if a given Ped is a dog and identifies its size category.
--- ---
--- This function checks whether the specified Ped (or the player's Ped if none is provided) --- Checks the BigDogs and SmallDogs tables to see if the Ped's model matches any dog model.
--- matches any model hashes listed under `AnimalPeds.BigDogs` or `AnimalPeds.SmallDogs`. It returns
--- two values: the first indicates if the Ped is a dog, and the second specifies whether it's a
--- large dog (`true`) or a small dog (`false`). If the Ped is not a dog, the second return value is `nil`.
--- ---
---@param ped number|nil Optional. The Ped entity to check. Defaults to the player's Ped (`PlayerPedId()`). --- @param ped number|nil Optional. The Ped entity to check. Defaults to the player's Ped.
--- ---@return boolean, boolean|nil boolean Returns `true` and `true` if the Ped is a big dog,
---@return boolean, boolean|nil Returns `true` and `true` if the Ped is a big dog,
--- `true` and `false` if it's a small dog, --- `true` and `false` if it's a small dog,
--- or `false` and `nil` if it's not a dog. --- or `false` and `nil` if it's not a dog.
--- ---
@@ -124,25 +149,22 @@ if not isServer() then
--- ``` --- ```
function isDog(ped) function isDog(ped)
local PedModel = GetEntityModel(ped or PlayerPedId()) local PedModel = GetEntityModel(ped or PlayerPedId())
for k, v in pairs(AnimalPeds.BigDogs) do for modelHash, _ in pairs(AnimalPeds.BigDogs) do
if PedModel == k then if PedModel == modelHash then
return true, true return true, true
end end
end end
for modelHash, _ in pairs(AnimalPeds.SmallDogs) do
for k, v in pairs(AnimalPeds.SmallDogs) do if PedModel == modelHash then
if PedModel == k then
return true, false return true, false
end end
end end
return false, nil return false, nil
end end
--- Retrieves a list of all animal model hashes. --- Compiles and returns a flat table of all animal model hashes.
--- ---
--- This function compiles and returns a flat table containing all model hashes --- Iterates through every category in AnimalPeds and collects all model hashes.
--- from the various animal categories defined within the `AnimalPeds` table.
--- It's useful for iterating over or performing bulk operations on all animal models.
--- ---
--- @return table table A table containing all animal model hashes. --- @return table table A table containing all animal model hashes.
--- ---
@@ -154,289 +176,109 @@ if not isServer() then
--- end --- end
--- ``` --- ```
function getAnimalModels() function getAnimalModels()
local animalModels = {}
for _, animalCategory in pairs(AnimalPeds) do
for modelHash, _ in pairs(animalCategory) do
table.insert(animalModels, modelHash)
end
end
return animalModels
end
--- Compiles and returns a table of animal animations for the ped model.
---
--- Iterates through every category in AnimalPeds and collects all anims.
---
--- @return table table A table containing all current model anims.
---
---@usage
--- ```lua
--- local getAnim = getAnimalAnims(ped)
--- playAnim(getAnim.sitDict, getAnim.sitAnim, -1, 1)
--- ```
function getAnimalAnims(ped)
local model = GetEntityModel(ped)
local animalTable = {} local animalTable = {}
for k in pairs(AnimalPeds) do for _, animalCategory in pairs(AnimalPeds) do
for v in pairs(AnimalPeds[k]) do for k, v in pairs(animalCategory) do
animalTable[#animalTable+1] = v if k == model then
animalTable = v
break
end
end end
end end
return animalTable return animalTable
end end
end end
-------------------------------------------------------------
-- Animal Models Data
-------------------------------------------------------------
-- Define the animal models and their associated animations.
AnimalPeds = { AnimalPeds = {
BigDogs = { BigDogs = {
-- Big Dogs [`a_c_chop`] = { deathAnim = "dead_right", deathDict = "creatures@chop@move", exitAnim = "getup_r", exitDict = "creatures@chop@getup", sitAnim = "sit", sitDict = "creatures@rottweiler@in_vehicle@std_car" },
[`a_c_chop`] = { [`a_c_k9`] = { deathAnim = "dead_right", deathDict = "creatures@chop@move", exitAnim = "getup_r", exitDict = "creatures@chop@getup", sitAnim = "sit", sitDict = "creatures@rottweiler@in_vehicle@std_car" },
deathAnim = "dead_right", deathDict = "creatures@chop@move", [`a_c_husky`] = { deathAnim = "dead_right", deathDict = "creatures@rottweiler@move", exitAnim = "getup_r", exitDict = "creatures@rottweiler@getup", sitAnim = "sit", sitDict = "creatures@rottweiler@in_vehicle@std_car" },
exitAnim = "getup_r", exitDict = "creatures@chop@getup", [`a_c_retriever`] = { deathAnim = "dead_right", deathDict = "creatures@rottweiler@move", exitAnim = "getup_r", exitDict = "creatures@rottweiler@getup", sitAnim = "sit", sitDict = "creatures@rottweiler@in_vehicle@std_car" },
sitAnim = "sit", sitDict = "creatures@rottweiler@in_vehicle@std_car" [`a_c_shepherd`] = { deathAnim = "dead_right", deathDict = "creatures@rottweiler@move", exitAnim = "getup_r", exitDict = "creatures@rottweiler@getup", sitAnim = "sit", sitDict = "creatures@rottweiler@in_vehicle@std_car" },
}, [`a_c_rottweiler`] = { deathAnim = "dead_right", deathDict = "creatures@rottweiler@move", exitAnim = "getup_r", exitDict = "creatures@rottweiler@getup", sitAnim = "sit", sitDict = "creatures@rottweiler@in_vehicle@std_car" },
[`a_c_k9`] = { [`ft-aushep`] = { deathAnim = "dead_right", deathDict = "creatures@rottweiler@move", exitAnim = "getup_r", exitDict = "creatures@rottweiler@getup", sitAnim = "sit", sitDict = "creatures@rottweiler@in_vehicle@std_car" },
deathAnim = "dead_right", deathDict = "creatures@chop@move", [`golden_r`] = { deathAnim = "dead_right", deathDict = "creatures@rottweiler@move", exitAnim = "getup_r", exitDict = "creatures@rottweiler@getup", sitAnim = "sit", sitDict = "creatures@rottweiler@in_vehicle@std_car" },
exitAnim = "getup_r", exitDict = "creatures@chop@getup", [`ft-dobermanv2`] = { deathAnim = "dead_right", deathDict = "creatures@rottweiler@move", exitAnim = "getup_r", exitDict = "creatures@rottweiler@getup", sitAnim = "sit", sitDict = "creatures@rottweiler@in_vehicle@std_car" },
sitAnim = "sit", sitDict = "creatures@rottweiler@in_vehicle@std_car" [`doberman`] = { deathAnim = "dead_right", deathDict = "creatures@rottweiler@move", exitAnim = "getup_r", exitDict = "creatures@rottweiler@getup", sitAnim = "sit", sitDict = "creatures@rottweiler@in_vehicle@std_car" },
}, [`ft-gs`] = { deathAnim = "dead_right", deathDict = "creatures@rottweiler@move", exitAnim = "getup_r", exitDict = "creatures@rottweiler@getup", sitAnim = "sit", sitDict = "creatures@rottweiler@in_vehicle@std_car" },
[`a_c_husky`] = { [`k9_husky`] = { deathAnim = "dead_right", deathDict = "creatures@rottweiler@move", exitAnim = "getup_r", exitDict = "creatures@rottweiler@getup", sitAnim = "sit", sitDict = "creatures@rottweiler@in_vehicle@std_car" },
deathAnim = "dead_right", deathDict = "creatures@rottweiler@move", [`ft-bloodhound`] = { deathAnim = "dead_right", deathDict = "creatures@rottweiler@move", exitAnim = "getup_r", exitDict = "creatures@rottweiler@getup", sitAnim = "sit", sitDict = "creatures@rottweiler@in_vehicle@std_car" },
exitAnim = "getup_r", exitDict = "creatures@rottweiler@getup", [`bernard`] = { deathAnim = "dead_right", deathDict = "creatures@rottweiler@move", exitAnim = "getup_r", exitDict = "creatures@rottweiler@getup", sitAnim = "sit", sitDict = "creatures@rottweiler@in_vehicle@std_car" },
sitAnim = "sit", sitDict = "creatures@rottweiler@in_vehicle@std_car" [`ft-pterrier`] = { deathAnim = "dead_right", deathDict = "creatures@rottweiler@move", exitAnim = "getup_r", exitDict = "creatures@rottweiler@getup", sitAnim = "sit", sitDict = "creatures@rottweiler@in_vehicle@std_car" },
}, [`ft-labrador`] = { deathAnim = "dead_right", deathDict = "creatures@rottweiler@move", exitAnim = "getup_r", exitDict = "creatures@rottweiler@getup", sitAnim = "sit", sitDict = "creatures@rottweiler@in_vehicle@std_car" },
[`a_c_retriever`] = { [`dane`] = { deathAnim = "dead_right", deathDict = "creatures@rottweiler@move", exitAnim = "getup_r", exitDict = "creatures@rottweiler@getup", sitAnim = "sit", sitDict = "creatures@rottweiler@in_vehicle@std_car" },
deathAnim = "dead_right", deathDict = "creatures@rottweiler@move", [`ft_malinois`] = { deathAnim = "dead_right", deathDict = "creatures@rottweiler@move", exitAnim = "getup_r", exitDict = "creatures@rottweiler@getup", sitAnim = "sit", sitDict = "creatures@rottweiler@in_vehicle@std_car" },
exitAnim = "getup_r", exitDict = "creatures@rottweiler@getup", [`abdog`] = { deathAnim = "dead_right", deathDict = "creatures@rottweiler@move", exitAnim = "getup_r", exitDict = "creatures@rottweiler@getup", sitAnim = "sit", sitDict = "creatures@rottweiler@in_vehicle@std_car" },
sitAnim = "sit", sitDict = "creatures@rottweiler@in_vehicle@std_car" [`dalmatian`] = { deathAnim = "dead_right", deathDict = "creatures@rottweiler@move", exitAnim = "getup_r", exitDict = "creatures@rottweiler@getup", sitAnim = "sit", sitDict = "creatures@rottweiler@in_vehicle@std_car" },
}, [`a_c_dalmatian`] = { deathAnim = "dead_right", deathDict = "creatures@rottweiler@move", exitAnim = "getup_r", exitDict = "creatures@rottweiler@getup", sitAnim = "sit", sitDict = "creatures@rottweiler@in_vehicle@std_car" },
[`a_c_shepherd`] = { [`ft-boxer`] = { deathAnim = "dead_right", deathDict = "creatures@rottweiler@move", exitAnim = "getup_r", exitDict = "creatures@rottweiler@getup", sitAnim = "sit", sitDict = "creatures@rottweiler@in_vehicle@std_car" },
deathAnim = "dead_right", deathDict = "creatures@rottweiler@move", [`ft-bs`] = { deathAnim = "dead_right", deathDict = "creatures@rottweiler@move", exitAnim = "getup_r", exitDict = "creatures@rottweiler@getup", sitAnim = "sit", sitDict = "creatures@rottweiler@in_vehicle@std_car" },
exitAnim = "getup_r", exitDict = "creatures@rottweiler@getup", [`chowchow`] = { deathAnim = "dead_right", deathDict = "creatures@rottweiler@move", exitAnim = "getup_r", exitDict = "creatures@rottweiler@getup", sitAnim = "sit", sitDict = "creatures@rottweiler@in_vehicle@std_car" },
sitAnim = "sit", sitDict = "creatures@rottweiler@in_vehicle@std_car" [`a_c_coyote`] = { deathAnim = "dead_right", deathDict = "creatures@coyote@move", exitAnim = "getup_r", exitDict = "creatures@coyote@getup", sitAnim = "base", sitDict = "creatures@coyote@amb@world_coyote_howl@base" },
}, [`a_c_coyote_02`] = { deathAnim = "dead_right", deathDict = "creatures@coyote@move", exitAnim = "getup_r", exitDict = "creatures@coyote@getup", sitAnim = "base", sitDict = "creatures@coyote@amb@world_coyote_howl@base" },
[`a_c_rottweiler`] = {
deathAnim = "dead_right", deathDict = "creatures@rottweiler@move",
exitAnim = "getup_r", exitDict = "creatures@rottweiler@getup",
sitAnim = "sit", sitDict = "creatures@rottweiler@in_vehicle@std_car"
},
[`ft-aushep`] = {
deathAnim = "dead_right", deathDict = "creatures@rottweiler@move",
exitAnim = "getup_r", exitDict = "creatures@rottweiler@getup",
sitAnim = "sit", sitDict = "creatures@rottweiler@in_vehicle@std_car"
},
[`golden_r`] = {
deathAnim = "dead_right", deathDict = "creatures@rottweiler@move",
exitAnim = "getup_r", exitDict = "creatures@rottweiler@getup",
sitAnim = "sit", sitDict = "creatures@rottweiler@in_vehicle@std_car"
},
[`ft-dobermanv2`] = {
deathAnim = "dead_right", deathDict = "creatures@rottweiler@move",
exitAnim = "getup_r", exitDict = "creatures@rottweiler@getup",
sitAnim = "sit", sitDict = "creatures@rottweiler@in_vehicle@std_car"
},
[`doberman`] = {
deathAnim = "dead_right", deathDict = "creatures@rottweiler@move",
exitAnim = "getup_r", exitDict = "creatures@rottweiler@getup",
sitAnim = "sit", sitDict = "creatures@rottweiler@in_vehicle@std_car"
},
[`ft-gs`] = {
deathAnim = "dead_right", deathDict = "creatures@rottweiler@move",
exitAnim = "getup_r", exitDict = "creatures@rottweiler@getup",
sitAnim = "sit", sitDict = "creatures@rottweiler@in_vehicle@std_car"
},
[`k9_husky`] = {
deathAnim = "dead_right", deathDict = "creatures@rottweiler@move",
exitAnim = "getup_r", exitDict = "creatures@rottweiler@getup",
sitAnim = "sit", sitDict = "creatures@rottweiler@in_vehicle@std_car"
},
[`ft-bloodhound`] = {
deathAnim = "dead_right", deathDict = "creatures@rottweiler@move",
exitAnim = "getup_r", exitDict = "creatures@rottweiler@getup",
sitAnim = "sit", sitDict = "creatures@rottweiler@in_vehicle@std_car"
},
[`bernard`] = {
deathAnim = "dead_right", deathDict = "creatures@rottweiler@move",
exitAnim = "getup_r", exitDict = "creatures@rottweiler@getup",
sitAnim = "sit", sitDict = "creatures@rottweiler@in_vehicle@std_car"
},
[`ft-pterrier`] = {
deathAnim = "dead_right", deathDict = "creatures@rottweiler@move",
exitAnim = "getup_r", exitDict = "creatures@rottweiler@getup",
sitAnim = "sit", sitDict = "creatures@rottweiler@in_vehicle@std_car"
},
[`ft-labrador`] = {
deathAnim = "dead_right", deathDict = "creatures@rottweiler@move",
exitAnim = "getup_r", exitDict = "creatures@rottweiler@getup",
sitAnim = "sit", sitDict = "creatures@rottweiler@in_vehicle@std_car"
},
[`dane`] = {
deathAnim = "dead_right", deathDict = "creatures@rottweiler@move",
exitAnim = "getup_r", exitDict = "creatures@rottweiler@getup",
sitAnim = "sit", sitDict = "creatures@rottweiler@in_vehicle@std_car"
},
[`ft_malinois`] = {
deathAnim = "dead_right", deathDict = "creatures@rottweiler@move",
exitAnim = "getup_r", exitDict = "creatures@rottweiler@getup",
sitAnim = "sit", sitDict = "creatures@rottweiler@in_vehicle@std_car"
},
[`abdog`] = {
deathAnim = "dead_right", deathDict = "creatures@rottweiler@move",
exitAnim = "getup_r", exitDict = "creatures@rottweiler@getup",
sitAnim = "sit", sitDict = "creatures@rottweiler@in_vehicle@std_car"
},
[`dalmatian`] = {
deathAnim = "dead_right", deathDict = "creatures@rottweiler@move",
exitAnim = "getup_r", exitDict = "creatures@rottweiler@getup",
sitAnim = "sit", sitDict = "creatures@rottweiler@in_vehicle@std_car"
},
[`a_c_dalmatian`] = {
deathAnim = "dead_right", deathDict = "creatures@rottweiler@move",
exitAnim = "getup_r", exitDict = "creatures@rottweiler@getup",
sitAnim = "sit", sitDict = "creatures@rottweiler@in_vehicle@std_car"
},
[`ft-boxer`] = {
deathAnim = "dead_right", deathDict = "creatures@rottweiler@move",
exitAnim = "getup_r", exitDict = "creatures@rottweiler@getup",
sitAnim = "sit", sitDict = "creatures@rottweiler@in_vehicle@std_car"
},
[`ft-bs`] = {
deathAnim = "dead_right", deathDict = "creatures@rottweiler@move",
exitAnim = "getup_r", exitDict = "creatures@rottweiler@getup",
sitAnim = "sit", sitDict = "creatures@rottweiler@in_vehicle@std_car"
},
[`chowchow`] = {
deathAnim = "dead_right", deathDict = "creatures@rottweiler@move",
exitAnim = "getup_r", exitDict = "creatures@rottweiler@getup",
sitAnim = "sit", sitDict = "creatures@rottweiler@in_vehicle@std_car"
},
[`a_c_coyote`] = {
deathAnim = "dead_right", deathDict = "creatures@coyote@move",
exitAnim = "getup_r", exitDict = "creatures@coyote@getup",
sitAnim = "base", sitDict = "creatures@coyote@amb@world_coyote_howl@base"
},
[`a_c_coyote_02`] = {
deathAnim = "dead_right", deathDict = "creatures@coyote@move",
exitAnim = "getup_r", exitDict = "creatures@coyote@getup",
sitAnim = "base", sitDict = "creatures@coyote@amb@world_coyote_howl@base"
},
}, },
SmallDogs = { SmallDogs = {
-- Small Dogs [`a_c_poodle`] = { deathAnim = "dead_right", deathDict = "creatures@pug@move", exitAnim = "getup_r", exitDict = "creatures@pug@getup", sitAnim = "base", sitDict = "creatures@pug@amb@world_dog_sitting@base" },
[`a_c_poodle`] = { [`ft-chihuahua`] = { deathAnim = "dead_right", deathDict = "creatures@pug@move", exitAnim = "getup_r", exitDict = "creatures@pug@getup", sitAnim = "base", sitDict = "creatures@pug@amb@world_dog_sitting@base" },
deathAnim = "dead_right", deathDict = "creatures@pug@move", [`a_c_pug`] = { deathAnim = "dead_right", deathDict = "creatures@pug@move", exitAnim = "getup_r", exitDict = "creatures@pug@getup", sitAnim = "base", sitDict = "creatures@pug@amb@world_dog_sitting@base" },
exitAnim = "getup_r", exitDict = "creatures@pug@getup", [`a_c_pug_02`] = { deathAnim = "dead_right", deathDict = "creatures@pug@move", exitAnim = "getup_r", exitDict = "creatures@pug@getup", sitAnim = "base", sitDict = "creatures@pug@amb@world_dog_sitting@base" },
sitAnim = "base", sitDict = "creatures@pug@amb@world_dog_sitting@base" [`a_c_westy`] = { deathAnim = "dead_right", deathDict = "creatures@pug@move", exitAnim = "getup_r", exitDict = "creatures@pug@getup", sitAnim = "base", sitDict = "creatures@pug@amb@world_dog_sitting@base" },
}, [`ft-pretriever`] = { deathAnim = "dead_right", deathDict = "creatures@pug@move", exitAnim = "getup_r", exitDict = "creatures@pug@getup", sitAnim = "base", sitDict = "creatures@pug@amb@world_dog_sitting@base" },
[`ft-chihuahua`] = { [`ft-shepk9`] = { deathAnim = "dead_right", deathDict = "creatures@pug@move", exitAnim = "getup_r", exitDict = "creatures@pug@getup", sitAnim = "base", sitDict = "creatures@pug@amb@world_dog_sitting@base" },
deathAnim = "dead_right", deathDict = "creatures@pug@move",
exitAnim = "getup_r", exitDict = "creatures@pug@getup",
sitAnim = "base", sitDict = "creatures@pug@amb@world_dog_sitting@base"
},
[`a_c_pug`] = {
deathAnim = "dead_right", deathDict = "creatures@pug@move",
exitAnim = "getup_r", exitDict = "creatures@pug@getup",
sitAnim = "base", sitDict = "creatures@pug@amb@world_dog_sitting@base"
},
[`a_c_pug_02`] = {
deathAnim = "dead_right", deathDict = "creatures@pug@move",
exitAnim = "getup_r", exitDict = "creatures@pug@getup",
sitAnim = "base", sitDict = "creatures@pug@amb@world_dog_sitting@base"
},
[`a_c_westy`] = {
deathAnim = "dead_right", deathDict = "creatures@pug@move",
exitAnim = "getup_r", exitDict = "creatures@pug@getup",
sitAnim = "base", sitDict = "creatures@pug@amb@world_dog_sitting@base"
},
[`ft-pretriever`] = {
deathAnim = "dead_right", deathDict = "creatures@pug@move",
exitAnim = "getup_r", exitDict = "creatures@pug@getup",
sitAnim = "base", sitDict = "creatures@pug@amb@world_dog_sitting@base"
},
[`ft-shepk9`] = {
deathAnim = "dead_right", deathDict = "creatures@pug@move",
exitAnim = "getup_r", exitDict = "creatures@pug@getup",
sitAnim = "base", sitDict = "creatures@pug@amb@world_dog_sitting@base"
},
}, },
CatPeds = { CatPeds = {
-- Cat [`bshorthair`] = { deathAnim = "dead_right", deathDict = "creatures@cat@move", exitAnim = "getup_r", exitDict = "creatures@cat@getup", sitAnim = "base", sitDict = "creatures@cat@amb@world_cat_sleeping_ledge@base" },
[`bshorthair`] = { [`a_c_cat_01`] = { deathAnim = "dead_right", deathDict = "creatures@cat@move", exitAnim = "getup_r", exitDict = "creatures@cat@getup", sitAnim = "base", sitDict = "creatures@cat@amb@world_cat_sleeping_ledge@base" },
deathAnim = "dead_right", deathDict = "creatures@cat@move", [`ft-sphynx`] = { deathAnim = "dead_right", deathDict = "creatures@coyote@move", exitAnim = "getup_r", exitDict = "creatures@coyote@getup", sitAnim = "base", sitDict = "creatures@coyote@amb@world_coyote_howl@base" },
exitAnim = "getup_r", exitDict = "creatures@cat@getup",
sitAnim = "base", sitDict = "creatures@cat@amb@world_cat_sleeping_ledge@base"
},
[`a_c_cat_01`] = {
deathAnim = "dead_right", deathDict = "creatures@cat@move",
exitAnim = "getup_r", exitDict = "creatures@cat@getup",
sitAnim = "base", sitDict = "creatures@cat@amb@world_cat_sleeping_ledge@base"
},
[`ft-sphynx`] = {
deathAnim = "dead_right", deathDict = "creatures@coyote@move",
exitAnim = "getup_r", exitDict = "creatures@coyote@getup",
sitAnim = "base", sitDict = "creatures@coyote@amb@world_coyote_howl@base"
},
}, },
OtherPeds = { OtherPeds = {
-- Other Animals [`ft-raccoon`] = { deathAnim = "dead_right", deathDict = "creatures@cat@move", exitAnim = "getup_r", exitDict = "creatures@cat@getup", sitAnim = "base", sitDict = "creatures@cat@amb@world_cat_sleeping_ledge@base" },
[`ft-raccoon`] = { [`a_c_hen`] = { deathAnim = "dead_right", deathDict = "creatures@hen@move", exitAnim = "getup_r", exitDict = "creatures@hen@getup" },
deathAnim = "dead_right", deathDict = "creatures@cat@move", [`a_c_rabbit_01`] = { deathAnim = "dead_right", deathDict = "creatures@rabbit@move", exitAnim = "getup_r", exitDict = "creatures@rabbit@getup", sitAnim = "idle_c", sitDict = "creatures@coyote@amb@world_coyote_howl@base" },
exitAnim = "getup_r", exitDict = "creatures@cat@getup", [`a_c_rabbit_02`] = { deathAnim = "dead_right", deathDict = "creatures@rabbit@move", exitAnim = "getup_r", exitDict = "creatures@rabbit@getup", sitAnim = "idle_c", sitDict = "creatures@coyote@amb@world_coyote_howl@base" },
sitAnim = "base", sitDict = "creatures@cat@amb@world_cat_sleeping_ledge@base" [`a_c_rat`] = { deathAnim = "dead_right", deathDict = "creatures@rat@move", exitAnim = "getup_r", exitDict = "creatures@rat@getup" },
}, [`a_c_deer`] = { deathAnim = "dead_right", deathDict = "creatures@deer@move", exitAnim = "getup_r", exitDict = "creatures@deer@getup" },
[`a_c_hen`] = { [`a_c_boar`] = { deathAnim = "dead_right", deathDict = "creatures@boar@move", exitAnim = "getup_r", exitDict = "creatures@boar@getup" },
deathAnim = "dead_right", deathDict = "creatures@hen@move", [`a_c_boar_02`] = { deathAnim = "dead_right", deathDict = "creatures@boar@move", exitAnim = "getup_r", exitDict = "creatures@boar@getup" },
exitAnim = "getup_r", exitDict = "creatures@hen@getup" [`a_c_chicken`] = { deathAnim = "dead_right", deathDict = "creatures@chicken@move", exitAnim = "getup_r", exitDict = "creatures@chicken@getup" },
}, [`a_c_pig`] = { deathAnim = "dead_right", deathDict = "creatures@pig@move", exitAnim = "getup_r", exitDict = "creatures@pig@getup" },
[`a_c_rabbit_01`] = { [`a_c_sharkhammer`] = { deathAnim = "dead_right", deathDict = "creatures@sharkhammer@move", exitAnim = "getup_r", exitDict = "creatures@sharkhammer@getup" },
deathAnim = "dead_right", deathDict = "creatures@rabbit@move", [`a_c_sharktiger`] = { deathAnim = "dead_right", deathDict = "creatures@sharktiger@move", exitAnim = "getup_r", exitDict = "creatures@sharktiger@getup" },
exitAnim = "getup_r", exitDict = "creatures@rabbit@getup", [`a_c_crow`] = { deathAnim = "dead_down", deathDict = "creatures@crow@move", exitAnim = "nill", exitDict = "creatures@pug@move" },
sitAnim = "idle_c", sitDict = "creatures@coyote@amb@world_coyote_howl@base" [`a_c_pigeon`] = { deathAnim = "dead_down", deathDict = "creatures@pigeon@move", exitAnim = "nill", exitDict = "creatures@pug@move" },
},
[`a_c_rabbit_02`] = {
deathAnim = "dead_right", deathDict = "creatures@rabbit@move",
exitAnim = "getup_r", exitDict = "creatures@rabbit@getup",
sitAnim = "idle_c", sitDict = "creatures@coyote@amb@world_coyote_howl@base"
},
[`a_c_rat`] = {
deathAnim = "dead_right", deathDict = "creatures@rat@move",
exitAnim = "getup_r", exitDict = "creatures@rat@getup"
},
[`a_c_deer`] = {
deathAnim = "dead_right", deathDict = "creatures@deer@move",
exitAnim = "getup_r", exitDict = "creatures@deer@getup"
},
[`a_c_boar`] = {
deathAnim = "dead_right", deathDict = "creatures@boar@move",
exitAnim = "getup_r", exitDict = "creatures@boar@getup"
},
[`a_c_boar_02`] = {
deathAnim = "dead_right", deathDict = "creatures@boar@move",
exitAnim = "getup_r", exitDict = "creatures@boar@getup"
},
[`a_c_chicken`] = {
deathAnim = "dead_right", deathDict = "creatures@chicken@move",
exitAnim = "getup_r", exitDict = "creatures@chicken@getup"
},
[`a_c_pig`] = {
deathAnim = "dead_right", deathDict = "creatures@pig@move",
exitAnim = "getup_r", exitDict = "creatures@pig@getup"
},
[`a_c_sharkhammer`] = {
deathAnim = "dead_right", deathDict = "creatures@sharkhammer@move",
exitAnim = "getup_r", exitDict = "creatures@sharkhammer@getup"
},
[`a_c_sharktiger`] = {
deathAnim = "dead_right", deathDict = "creatures@sharktiger@move",
exitAnim = "getup_r", exitDict = "creatures@sharktiger@getup"
},
[`a_c_crow`] = {
deathAnim = "dead_down", deathDict = "creatures@crow@move",
exitAnim = "nill", exitDict = "creatures@pug@move", -- no get up anim
},
[`a_c_pigeon`] = {
deathAnim = "dead_down", deathDict = "creatures@pigeon@move",
exitAnim = "nill", exitDict = "creatures@pug@move", -- no get up anim
},
}, },
Monekys = { Monekys = {
[`ft-chimpanzee`] = { [`ft-chimpanzee`] = { deathAnim = "dead", deathDict = "dead_a", exitAnim = "get_up@sat_on_floor@to_stand", exitDict = "getup_0" },
deathAnim = "dead", deathDict = "dead_a", [`a_c_chimp`] = { deathAnim = "dead", deathDict = "dead_a", exitAnim = "get_up@sat_on_floor@to_stand", exitDict = "getup_0" },
exitAnim = "get_up@sat_on_floor@to_stand", exitDict = "getup_0" [`a_c_chimp_02`] = { deathAnim = "dead", deathDict = "dead_a", exitAnim = "get_up@sat_on_floor@to_stand", exitDict = "getup_0" },
}, [`a_c_rhesus`] = { deathAnim = "dead", deathDict = "dead_a", exitAnim = "get_up@sat_on_floor@to_stand", exitDict = "getup_0" },
[`a_c_chimp`] = { [`ft-capmonkey2`] = { deathAnim = "dead_right", deathDict = "creatures@pug@move", exitAnim = "getup_r", exitDict = "creatures@pug@getup", sitAnim = "base", sitDict = "creatures@pug@amb@world_dog_sitting@base" },
deathAnim = "dead", deathDict = "dead_a",
exitAnim = "get_up@sat_on_floor@to_stand", exitDict = "getup_0"
},
[`a_c_chimp_02`] = {
deathAnim = "dead", deathDict = "dead_a",
exitAnim = "get_up@sat_on_floor@to_stand", exitDict = "getup_0"
},
[`a_c_rhesus`] = {
deathAnim = "dead", deathDict = "dead_a",
exitAnim = "get_up@sat_on_floor@to_stand", exitDict = "getup_0"
},
[`ft-capmonkey2`] = {
deathAnim = "dead_right", deathDict = "creatures@pug@move",
exitAnim = "getup_r", exitDict = "creatures@pug@getup",
sitAnim = "base", sitDict = "creatures@pug@amb@world_dog_sitting@base"
},
} }
} }

File diff suppressed because it is too large Load Diff

View File

@@ -1,15 +1,38 @@
-- Global variable to track duty status --[[
Duty & Interaction Utilities Module
--------------------------------------
This module provides functions related to:
• Determining boss roles from Jobs and Gangs tables.
• Checking a player's job and duty status.
• Toggling duty state.
• Simulating player interactions such as hand washing, using toilets/urinals,
and teleporting via doors.
]]
-------------------------------------------------------------
-- Global Duty Status
-------------------------------------------------------------
-- This attempts to sync up with the players framework onDuty variable
-- This stops the script getting confused when one is false and one is true
onDuty = false onDuty = false
--- Scans the 'Jobs' and 'Gangs' tables to identify roles classified as Bosses. if not isServer() then
onPlayerLoaded(function()
onDuty = getPlayer().onDuty
end, true)
end
-------------------------------------------------------------
-- Boss Role Detection
-------------------------------------------------------------
--- Scans the 'Jobs' and 'Gangs' tables to identify roles classified as bosses.
--- ---
--- This function iterates through the specified role's grades within the `Jobs` or `Gangs` tables. --- Iterates through the specified role's grades in the Jobs or Gangs table and returns
--- It identifies which grades are marked as bosses (`isboss`) or have bank authorization (`bankAuth`). --- a table mapping the role to the lowest grade number that qualifies as a boss (isboss or bankAuth).
--- The function returns a table where each role maps to the lowest grade number that qualifies as a boss.
--- ---
---@param role string The name of the job or gang role to check for boss grades. --- @param role string The job or gang role to check.
--- --- @return table table A table with the role mapped to its boss grade number.
---@return table table A table containing roles mapped to their respective boss grade numbers.
--- ---
--- @usage --- @usage
--- ```lua --- ```lua
@@ -23,7 +46,7 @@ function makeBossRoles(role)
local data = (Jobs and Jobs[role]) or (Gangs and Gangs[role]) local data = (Jobs and Jobs[role]) or (Gangs and Gangs[role])
if data then if data then
for grade, info in pairs(data.grades) do for grade, info in pairs(data.grades) do
if info.isboss or info.bankAuth then if info.isboss or info.bankAuth or info.isBoss then
boss[role] = boss[role] and math.min(boss[role], tonumber(grade)) or tonumber(grade) boss[role] = boss[role] and math.min(boss[role], tonumber(grade)) or tonumber(grade)
end end
end end
@@ -31,27 +54,30 @@ function makeBossRoles(role)
return boss return boss
end end
--- Checks if the player has a specific job and is on duty. -------------------------------------------------------------
-- Job & Duty Checks
-------------------------------------------------------------
--- Checks if the player has a specific job (or gang) and is on duty.
--- ---
--- This function verifies whether the player possesses the specified job and, if applicable, --- Verifies whether the player possesses the specified role. If the role is defined in the Jobs table,
--- whether they are currently on duty. It provides a notification if the player fails these checks. --- it also checks that the player is clocked in (onDuty). If the check fails, a notification is sent.
--- ---
---@param job string The name of the job or gang to check. --- @param job string The job or gang to check.
--- --- @return boolean Returns true if the player meets the criteria; false otherwise.
---@return boolean Returns `true` if the player has the job (and is on duty if required), otherwise `false`.
--- ---
--- @usage --- @usage
--- ```lua --- ```lua
--- if jobCheck("mechanic") then --- if jobCheck("mechanic") then
--- -- Allow access to mechanic-related features --- -- Allow mechanic features.
--- else --- else
--- -- Deny access or notify the player --- -- Deny access.
--- end --- end
--- ``` --- ```
function jobCheck(job) function jobCheck(job)
canDo = true local canDo = true
if Jobs[job] then if Jobs[job] then
if not hasJob(job) or not onDuty then if not hasJob(job) or not getPlayer().onDuty then
triggerNotify(nil, Loc[Config.Lan].error["not_clockedin"]) triggerNotify(nil, Loc[Config.Lan].error["not_clockedin"])
canDo = false canDo = false
end end
@@ -66,20 +92,23 @@ end
--- Toggles the player's duty status. --- Toggles the player's duty status.
--- ---
--- This function switches the player's duty state between on-duty and off-duty. --- Switches the player's duty state between on-duty and off-duty. If using QBcore,
--- It integrates with QBcore's duty system if available; otherwise, it manually toggles the `onDuty` variable --- it triggers the appropriate server event. Otherwise, it manually toggles the onDuty variable and notifies the player.
--- and sends a notification to the player about their new duty status.
--- ---
--- @usage --- @usage
--- ```lua --- ```lua
--- toggleDuty() --- toggleDuty() -- Player receives a notification of their new duty status.
--- -- Player will receive a notification indicating their new duty status
--- ``` --- ```
function toggleDuty() function toggleDuty()
if isStarted(QBExport) or isStarted(QBXExport) then if isStarted(QBExport) or isStarted(QBXExport) then
TriggerServerEvent("QBCore:ToggleDuty") TriggerServerEvent("QBCore:ToggleDuty")
Wait(100)
onDuty = getPlayer().onDuty
elseif isStarted(RSGExport) then
TriggerServerEvent("RSGCore:ToggleDuty")
Wait(100)
onDuty = getPlayer().onDuty
else else
onDuty = not onDuty
if onDuty then if onDuty then
triggerNotify(nil, "Now on duty", "success") triggerNotify(nil, "Now on duty", "success")
else else
@@ -88,22 +117,33 @@ function toggleDuty()
end end
end end
-- Framework specific functions to keep duty status synced
RegisterNetEvent("QBCore:Client:OnJobUpdate", function(JobInfo) onDuty = JobInfo.onduty end)
RegisterNetEvent("QBCore:Client:SetDuty", function(duty) onDuty = duty end)
RegisterNetEvent("qbx_core:client:onJobUpdate", function(JobInfo) onDuty = JobInfo.onduty end)
RegisterNetEvent("RSGCore:Client:OnJobUpdate", function(JobInfo) onDuty = JobInfo.onduty end)
RegisterNetEvent("RSGCore:Client:SetDuty", function(duty) onDuty = duty end)
-------------------------------------------------------------
-- Interaction Functions
-------------------------------------------------------------
--- Initiates the hand-washing action for the player. --- Initiates the hand-washing action for the player.
--- ---
--- This function triggers an animation and a progress bar to simulate the player washing their hands. --- Triggers an animation and a progress bar to simulate hand washing at the specified coordinates.
--- Upon completion, it sends a success notification. If the action is canceled, it notifies the player of the cancellation. --- On success, it notifies the player; if cancelled, it sends an error notification.
--- ---
---@param data table A table containing the coordinates where the hand-washing action takes place. --- @param data table A table containing:
--- - **coords** (`vector3`): The position where the hand-washing animation and camera are focused. --- - coords (vector3): The location where the hand-washing action occurs.
---
---@return void
--- ---
--- @usage --- @usage
--- ```lua --- ```lua
--- washHands({ coords = vector3(200.0, 300.0, 40.0) }) --- washHands({ coords = vector3(200.0, 300.0, 40.0) })
--- -- Player will perform the hand-washing animation at the specified location
--- ``` --- ```
function washHands(data) local ped = PlayerPedId() function washHands(data)
local ped = PlayerPedId()
lookEnt(data.coords) lookEnt(data.coords)
local cam = createTempCam(ped, data.coords) local cam = createTempCam(ped, data.coords)
if progressBar({ if progressBar({
@@ -118,20 +158,19 @@ function washHands(data) local ped = PlayerPedId()
}) then }) then
triggerNotify(nil, Loc[Config.Lan].success["washed_hands"], "success") triggerNotify(nil, Loc[Config.Lan].success["washed_hands"], "success")
else else
triggerNotify(nil, Loc[Config.Lan].error["cancel"], 'error') triggerNotify(nil, Loc[Config.Lan].error["cancel"], "error")
end end
ClearPedTasks(ped) ClearPedTasks(ped)
end end
--- Handles the player's interaction with a toilet or urinal. --- Handles the player's interaction with a toilet or urinal.
--- ---
--- This function manages the animations and progress bars associated with using a toilet or urinal. --- Manages animations and progress bars for using a urinal or a toilet. If the action is successful,
--- Depending on whether the interaction is with a urinal (`data.urinal`), it plays the appropriate animation --- it triggers the appropriate server event (urinal usage) or notifies the player if cancelled.
--- and triggers server events upon successful completion. If the action is canceled, it notifies the player.
--- ---
---@param data table A table containing data about the toilet interaction. --- @param data table A table containing:
--- - **urinal** (`boolean`): Indicates whether the interaction is with a urinal (`true`) or a toilet (`false`). --- - urinal (boolean): `true if using a urinal; false for a toilet.`
--- - **sitcoords** (`vector4`): The coordinates and heading for the seating animation when using a toilet. --- - sitcoords (vector4): `Coordinates and heading for seating when using a toilet.`
--- ---
--- @usage --- @usage
--- ```lua --- ```lua
@@ -154,7 +193,7 @@ function useToilet(data)
TriggerServerEvent(getScript().."server:Urinal") TriggerServerEvent(getScript().."server:Urinal")
else else
lockInv(false) lockInv(false)
triggerNotify(nil, Loc[Config.Lan].error["cancelled"], 'error') triggerNotify(nil, Loc[Config.Lan].error["cancelled"], "error")
end end
else else
TaskStartScenarioAtPosition(PlayerPedId(), "PROP_HUMAN_SEAT_CHAIR_MP_PLAYER", data.sitcoords.x, data.sitcoords.y, data.sitcoords.z, data.sitcoords[4], 0, 1, true) TaskStartScenarioAtPosition(PlayerPedId(), "PROP_HUMAN_SEAT_CHAIR_MP_PLAYER", data.sitcoords.x, data.sitcoords.y, data.sitcoords.z, data.sitcoords[4], 0, 1, true)
@@ -167,24 +206,22 @@ function useToilet(data)
ClearPedTasks(PlayerPedId()) ClearPedTasks(PlayerPedId())
else else
lockInv(false) lockInv(false)
triggerNotify(nil, Loc[Config.Lan].error["cancelled"], 'error') triggerNotify(nil, Loc[Config.Lan].error["cancelled"], "error")
end end
end end
end end
--- Teleports the player to specified coordinates with a fade effect. --- Teleports the player to specified coordinates with a fade effect.
--- ---
--- This function fades the screen out, moves the player to the target coordinates (`data.telecoords`), --- Fades the screen out, moves the player to the target coordinates, sets the player's heading,
--- sets the player's heading, and then fades the screen back in. It's commonly used for door interactions --- then fades the screen back in. Commonly used for door interactions or teleportation points.
--- or teleportation points within the game.
--- ---
---@param data table A table containing teleportation data. --- @param data table A table containing:
--- - **telecoords** (`vector4`): The target coordinates and heading for the teleportation. --- - telecoords (vector4): The target coordinates and heading.
--- ---
--- @usage --- @usage
--- ```lua --- ```lua
--- useDoor({ telecoords = vector4(215.76, -810.12, 29.73, 90.0) }) --- useDoor({ telecoords = vector4(215.76, -810.12, 29.73, 90.0) })
--- -- Player is teleported to the specified coordinates with a fade effect
--- ``` --- ```
function useDoor(data) function useDoor(data)
DoScreenFadeOut(500) DoScreenFadeOut(500)
@@ -194,3 +231,16 @@ function useDoor(data)
DoScreenFadeIn(1000) DoScreenFadeIn(1000)
Wait(100) Wait(100)
end end
function openBossMenu(isGang, group)
if isStarted("qb-management") then
if isGang then
TriggerEvent("qb-gangmenu:client:OpenMenu")
else
TriggerEvent("qb-bossmenu:client:OpenMenu")
end
elseif isStarted("qbx_management") then
exports["qbx_management"]:OpenBossMenu(isGang and "gang" or "job")
end
end

View File

@@ -22,16 +22,22 @@ function createTempCam(ent, coords)
triggerNotify(nil, "ModCam Created", "success") triggerNotify(nil, "ModCam Created", "success")
end end
local camCoords = nil local camCoords = nil
local pointCoords = nil
if type(ent) ~= "vector3" then if type(ent) ~= "vector3" then
camCoords = GetOffsetFromEntityInWorldCoords(ent, 1.0, -0.3, 0.8) camCoords = GetOffsetFromEntityInWorldCoords(ent, 1.0, -0.3, 0.8)
else else
camCoords = ent camCoords = ent
end end
-- Create the camera with specified parameters
cam = CreateCamWithParams("DEFAULT_SCRIPTED_CAMERA", camCoords.x, camCoords.y, camCoords.z + 0.5, 1.0, 0.0, 0.0, 60.00, false, 0) cam = CreateCamWithParams("DEFAULT_SCRIPTED_CAMERA", camCoords.x, camCoords.y, camCoords.z + 0.5, 1.0, 0.0, 0.0, 60.00, false, 0)
-- Point the camera at the target coordinates
if type(coords) == "number" then
SetCamCoord(cam, GetCamCoord(cam) + vec3(0, 0, 1.0))
PointCamAtEntity(cam, coords)
else
PointCamAtCoord(cam, coords) PointCamAtCoord(cam, coords)
end end
end
return cam return cam
end end

View File

@@ -137,11 +137,11 @@ end
--- ``` --- ```
function loadScriptBank(bank) function loadScriptBank(bank)
local timeout = 2000 local timeout = 2000
debugPrint("^6Debug^7: ^2Loading ^3Script ^2AudioBank^7...") debugPrint("^6Bridge^7: ^2Loading ^3Script ^2AudioBank^7...")
while not RequestScriptAudioBank(bank, 0) do Wait(10) timeout -= 10 if timeout <= 0 then break end end while not RequestScriptAudioBank(bank, false) do Wait(10) timeout -= 10 if timeout <= 0 then break end end
local success = RequestScriptAudioBank(bank, 0) local success = RequestScriptAudioBank(bank, false)
debugPrint("^6Debug^7: "..(success and "^3Successfully ^2loaded^7: '^4" or "^1Failed to ^2load^7: '^4")..bank.."^7'") debugPrint("^6Bridge^7: "..(success and "^3Successfully ^2loaded^7: '^4" or "^1Failed to ^2load^7: '^4")..bank.."^7'")
return success return success
end end
@@ -159,14 +159,14 @@ end
--- ``` --- ```
function loadAmbientBank(bank) function loadAmbientBank(bank)
local timeout = 2000 local timeout = 2000
debugPrint("^6Debug^7: ^2Loading ^3Ambient ^2AudioBank^7...") debugPrint("^6Bridge^7: ^2Loading ^3Ambient ^2AudioBank^7...")
while not RequestAmbientAudioBank(bank, 0) do while not RequestAmbientAudioBank(bank, 0) do
Wait(10) Wait(10)
timeout -= 10 timeout -= 10
if timeout <= 0 then break end if timeout <= 0 then break end
end end
local success = RequestAmbientAudioBank(bank, 0) local success = RequestAmbientAudioBank(bank, 0)
debugPrint("^6Debug^7: "..(success and "^3Successfully ^2loaded^7: '^4" or "^1Failed to ^2load^7: '^4")..bank.."^7'") debugPrint("^6Bridge^7: "..(success and "^3Successfully ^2loaded^7: '^4" or "^1Failed to ^2load^7: '^4")..bank.."^7'")
return success return success
end end
@@ -224,16 +224,18 @@ end
--- ```lua --- ```lua
--- playGameSound('DLC_HEIST_HACKING_SNAKE_SOUNDS', 'Beep', vector3(0, 0, 0), false, 15.0) --- playGameSound('DLC_HEIST_HACKING_SNAKE_SOUNDS', 'Beep', vector3(0, 0, 0), false, 15.0)
--- ``` --- ```
function playGameSound(bank, sound, coords, synced, range) function playGameSound(audioBank, soundSet, soundRef, coords, synced, range)
debugPrint("^6Debug^7: ^2Attempting to play: ^3"..sound.." ^7(^4"..bank.."^7')") debugPrint("^6Bridge^7: ^2Attempting to play: ^3"..soundRef.." ^7('^4"..audioBank.."^7')")
loadScriptBank(audioBank)
local range = range or 10.0 local range = range or 10.0
local soundId = GetSoundId() local soundId = GetSoundId()
while not soundId do Wait(10) end while not soundId do Wait(10) end
if type(coords) == "vector3" or type(coords) == "vector4" then if type(coords) == "vector3" or type(coords) == "vector4" then
debugPrint("^6Debug^7: ^2Playing sound from Coord^7: "..formatCoord(coords.xyz)) debugPrint("^6Bridge^7: ^2Playing sound from Coord^7: "..formatCoord(coords.xyz))
PlaySoundFromCoord(soundId, sound, coords.x, coords.y, coords.z, bank, synced, range, 0) PlaySoundFromCoord(soundId, soundRef, coords.x, coords.y, coords.z, soundSet, synced, range, 0)
else else
debugPrint("^6Debug^7: ^2Playing sound from Entity^7: ^4"..coords.."^7") debugPrint("^6Bridge^7: ^2Playing sound from Entity^7: ^4"..coords.."^7")
PlaySoundFromEntity(soundId, sound, coords, bank, synced, 0) PlaySoundFromEntity(soundId, soundRef, coords, soundSet, synced, 1.0)
end end
ReleaseScriptAudioBank(audioBank)
end end

View File

@@ -1,3 +1,5 @@
local blipTable = {}
--- Creates a blip at specified coordinates with given properties. --- Creates a blip at specified coordinates with given properties.
-- --
-- This function adds a map blip at the provided coordinates and sets various display properties such as sprite, color, scale, and more. -- This function adds a map blip at the provided coordinates and sets various display properties such as sprite, color, scale, and more.
@@ -30,19 +32,29 @@
-- local blip = makeBlip(blipData) -- local blip = makeBlip(blipData)
-- ``` -- ```
function makeBlip(data) function makeBlip(data)
local blip = AddBlipForCoord(vec3(data.coords.x, data.coords.y, data.coords.z)) local blip = nil
if gameName == "rdr3" then
blip = BlipAddForCoords(1664425300, data.coords.x, data.coords.y, data.coords.z)
SetBlipSprite(blip, data.sprite or `blip_shop_market_stall`)
SetBlipScale(blip, data.scale or 0.2)
SetBlipName(blip, data.name)
--BlipSetStyle(blip, data.col or `BLIP_STYLE_CREATOR_DEFAULT`)
else
blip = AddBlipForCoord(vec3(data.coords.x, data.coords.y, data.coords.z))
SetBlipCoords(blip, data.coords.x, data.coords.y, data.coords.z) -- Manually set blip coordinates again as sometimes it just refuses SetBlipCoords(blip, data.coords.x, data.coords.y, data.coords.z) -- Manually set blip coordinates again as sometimes it just refuses
SetBlipAsShortRange(blip, true) SetBlipAsShortRange(blip, true)
SetBlipSprite(blip, data.sprite or 106) SetBlipSprite(blip, data.sprite or 106)
SetBlipColour(blip, data.col or 5) SetBlipColour(blip, data.col or 5)
SetBlipScale(blip, data.scale or 0.7) SetBlipScale(blip, data.scale or 0.7)
SetBlipDisplay(blip, data.disp or 6) SetBlipDisplay(blip, data.disp or 6)
if data.category then SetBlipCategory(blip, data.category) end if data.category then
SetBlipCategory(blip, data.category)
end
BeginTextCommandSetBlipName('STRING') BeginTextCommandSetBlipName('STRING')
AddTextComponentString(tostring(data.name)) AddTextComponentString(tostring(data.name))
EndTextCommandSetBlipName(blip) EndTextCommandSetBlipName(blip)
-- Handle preview image if certain resources are running -- Handle preview image if certain resources are running
if isStarted("fs_smallresources") or isStarted("blip_info") or isStarted("blipinfo") then if isStarted("jim-blipcontroller") then
if data.preview then if data.preview then
local txname = string.gsub(tostring(data.name..'preview'..string.gsub(data.coords.z, "%.", "")), "[ ()~]", "") local txname = string.gsub(tostring(data.name..'preview'..string.gsub(data.coords.z, "%.", "")), "[ ()~]", "")
if data.preview:find("http") or data.preview:find("nui") then if data.preview:find("http") or data.preview:find("nui") then
@@ -50,11 +62,21 @@ function makeBlip(data)
else else
CreateRuntimeTextureFromImage(scriptTxd, txname, data.preview) CreateRuntimeTextureFromImage(scriptTxd, txname, data.preview)
end end
exports["fs_smallresources"]:SetBlipInfoImage(blip, getScript()..'scriptTxd', txname) exports["jim-blipcontroller"]:ShowBlipInfo(blip, {
exports["fs_smallresources"]:SetBlipInfoTitle(blip, data.name, false) title = data.name,
dict = getScript()..'scriptTxd',
tex = txname,
})
end end
end end
end
blipTable[blip] = blip
if DoesBlipExist(blip) then
debugPrint("^6Bridge^7: ^6Blip ^2created^7: '^6"..data.name.."^7' - '"..formatCoord(data.coords).."'") debugPrint("^6Bridge^7: ^6Blip ^2created^7: '^6"..data.name.."^7' - '"..formatCoord(data.coords).."'")
else
print("Error making blip")
end
return blip return blip
end end
@@ -90,8 +112,17 @@ end
-- local blip = makeEntityBlip(blipData) -- local blip = makeEntityBlip(blipData)
-- ``` -- ```
function makeEntityBlip(data) function makeEntityBlip(data)
local blip = nil
if gameName == "rdr3" then
blip = BlipAddForEntity(1664425300, data.entity)
SetBlipSprite(blip, data.sprite or `blip_ambient_coach`)
SetBlipScale(blip, data.scale or 0.2)
SetBlipName(blip, data.name)
else
AddBlipForEntity(data.entity) AddBlipForEntity(data.entity)
local blip = GetBlipFromEntity(data.entity) blip = GetBlipFromEntity(data.entity)
blipTable[blip] = blip
SetBlipAsShortRange(blip, true) SetBlipAsShortRange(blip, true)
SetBlipSprite(blip, data.sprite or 106) SetBlipSprite(blip, data.sprite or 106)
SetBlipColour(blip, data.col or 5) SetBlipColour(blip, data.col or 5)
@@ -114,6 +145,21 @@ function makeEntityBlip(data)
exports["fs_smallresources"]:SetBlipInfoTitle(blip, data.name, false) exports["fs_smallresources"]:SetBlipInfoTitle(blip, data.name, false)
end end
end end
end
blipTable[blip] = blip
if DoesBlipExist(blip) then
debugPrint("^6Bridge^7: ^6Blip ^2created for Entity^7: '^6"..data.name.."^7'") debugPrint("^6Bridge^7: ^6Blip ^2created for Entity^7: '^6"..data.name.."^7'")
else
print("Error making blip")
end
return blip return blip
end end
if gameName == "rdr3" then
onResourceStop(function()
for k in pairs(blipTable) do
RemoveBlip(k)
end
end, true)
end

View File

@@ -19,15 +19,17 @@ local Peds = {}
-- makeDistPed(pedData, pedCoords, true, false, 'WORLD_HUMAN_STAND_IMPATIENT', nil, true) -- makeDistPed(pedData, pedCoords, true, false, 'WORLD_HUMAN_STAND_IMPATIENT', nil, true)
-- ``` -- ```
function makeDistPed(data, coords, freeze, collision, scenario, anim, synced) function makeDistPed(data, coords, freeze, collision, scenario, anim, synced)
local zoneCoords = type(data) == "table" and data.coords or coords
local randName = keyGen()..keyGen()
createCirclePoly({ createCirclePoly({
name = keyGen()..keyGen(), name = randName,
coords = vec3(data.coords.x, data.coords.y, data.coords.z - 1.03), coords = vec3(zoneCoords.x, zoneCoords.y, zoneCoords.z - 1.03),
radius = 50.0, radius = 50.0,
onEnter = function() onEnter = function()
Peds[#Peds + 1] = makePed(data, coords, freeze, collision, scenario, anim, synced) Peds[randName] = makePed(data, coords, freeze, collision, scenario, anim, synced)
end, end,
onExit = function() onExit = function()
DeletePed(Peds[#Peds]) DeletePed(Peds[randName])
end, end,
debug = debugMode, debug = debugMode,
}) })
@@ -112,8 +114,15 @@ function makePed(data, coords, freeze, collision, scenario, anim, synced)
else else
model = data model = data
loadModel(model) loadModel(model)
if gameName == "rdr3" then
ped = CreatePed(model, coords.x, coords.y, coords.z - 1.03, coords.w, synced or false, false)
SetEntityVisible(ped, 1) -- SetEntityVisible
SetEntityAlpha(ped, 255, false) -- SetEntityAlpha
SetRandomOutfitVariation(ped, true) -- Invisible without
else
ped = CreatePed(0, model, coords.x, coords.y, coords.z - 1.03, coords.w, synced or false, false) ped = CreatePed(0, model, coords.x, coords.y, coords.z - 1.03, coords.w, synced or false, false)
end end
end
SetEntityInvincible(ped, true) SetEntityInvincible(ped, true)
SetBlockingOfNonTemporaryEvents(ped, true) SetBlockingOfNonTemporaryEvents(ped, true)
@@ -125,10 +134,13 @@ function makePed(data, coords, freeze, collision, scenario, anim, synced)
loadAnimDict(anim[1]) loadAnimDict(anim[1])
TaskPlayAnim(ped, anim[1], anim[2], 0.5, 1.0, -1, 1, 0.2, 0, 0, 0) TaskPlayAnim(ped, anim[1], anim[2], 0.5, 1.0, -1, 1, 0.2, 0, 0, 0)
end end
if DoesEntityExist(ped) then
debugPrint("^6Bridge^7: ^1Ped ^2Created^7: '^6"..ped.."^7' | ^2Hash^7: ^7'^5"..(model).."^7' | ^2Coord^7: "..formatCoord(coords)) debugPrint("^6Bridge^7: ^1Ped ^2Created^7: '^6"..ped.."^7' | ^2Hash^7: ^7'^5"..(model).."^7' | ^2Coord^7: "..formatCoord(coords))
else
print("error ped")
end
unloadModel(model) unloadModel(model)
Peds[#Peds + 1] = ped Peds[keyGen()..keyGen()] = ped
return ped return ped
end end
@@ -227,4 +239,8 @@ function GenerateRandomPedData(data)
end end
--- Cleans up all created Peds when the resource stops. --- Cleans up all created Peds when the resource stops.
onResourceStop(function() for i = 1, #Peds do DeletePed(Peds[i]) end end, true) onResourceStop(function()
for k in pairs(Peds) do
DeletePed(Peds[k])
end
end, true)

View File

@@ -23,12 +23,12 @@ local Props = {}
function makeProp(data, freeze, synced) function makeProp(data, freeze, synced)
loadModel(data.prop) loadModel(data.prop)
local prop = CreateObject(data.prop, data.coords.x, data.coords.y, data.coords.z-1.03, synced and synced or false, synced and synced or false, false) local prop = CreateObject(data.prop, data.coords.x, data.coords.y, data.coords.z-1.03, synced and synced or false, synced and synced or false, false)
SetEntityHeading(prop, data.coords.w + 180.0) SetEntityHeading(prop, (data.coords.w or 0) + 180.0)
FreezeEntityPosition(prop, freeze or false) FreezeEntityPosition(prop, freeze or false)
debugPrint("^6Bridge^7: ^1Prop ^2Created^7: '^6"..prop.."^7' | ^2Hash^7: ^7'^6"..data.prop.."^7' | ^2Coord^7: "..formatCoord(data.coords)) debugPrint("^6Bridge^7: ^1Prop ^2Created^7: '^6"..prop.."^7' | ^2Hash^7: ^7'^6"..data.prop.."^7' | ^2Coord^7: "..formatCoord(data.coords))
SetModelAsNoLongerNeeded(data.prop) SetModelAsNoLongerNeeded(data.prop)
Props[#Props + 1] = prop Props[keyGen()..keyGen()] = prop
return prop return prop
end end
@@ -51,17 +51,17 @@ end
--- } --- }
--- makeDistProp(propData, true, false) --- makeDistProp(propData, true, false)
--- ``` --- ```
function makeDistProp(data, freeze, synced) function makeDistProp(data, freeze, synced, range)
local prop = nil local name = keyGen()..keyGen()
createCirclePoly({ createCirclePoly({
name = keyGen()..keyGen(), name = name,
coords = vec3(data.coords.x, data.coords.y, data.coords.z - 1.03), coords = vec3(data.coords.x, data.coords.y, data.coords.z - 1.03),
radius = 50.0, radius = range or 50.0,
onEnter = function() onEnter = function()
prop = makeProp(data, freeze, synced) Props[name] = makeProp(data, freeze, synced)
end, end,
onExit = function() onExit = function()
destroyProp(prop) destroyProp(Props[name])
end, end,
debug = debugMode, debug = debugMode,
}) })
@@ -87,4 +87,8 @@ function destroyProp(entity)
end end
--- Cleans up all created props when the resource stops. --- Cleans up all created props when the resource stops.
onResourceStop(function() for i = 1, #Props do destroyProp(Props[i]) end end, true) onResourceStop(function()
for k in pairs(Props) do
destroyProp(Props[k])
end
end, true)

View File

@@ -17,12 +17,14 @@ function makeVeh(model, coords)
loadModel(model) loadModel(model)
local veh = CreateVehicle(model, coords.x, coords.y, coords.z, coords.w, true, false) local veh = CreateVehicle(model, coords.x, coords.y, coords.z, coords.w, true, false)
SetVehicleHasBeenOwnedByPlayer(veh, true) SetVehicleHasBeenOwnedByPlayer(veh, true)
if gameName ~= "rdr3" then
SetNetworkIdCanMigrate(NetworkGetNetworkIdFromEntity(veh), true) SetNetworkIdCanMigrate(NetworkGetNetworkIdFromEntity(veh), true)
Wait(100) Wait(100)
SetVehicleNeedsToBeHotwired(veh, false) SetVehicleNeedsToBeHotwired(veh, false)
SetVehRadioStation(veh, 'OFF') SetVehRadioStation(veh, 'OFF')
SetVehicleFuelLevel(veh, 100.0) SetVehicleFuelLevel(veh, 100.0)
SetVehicleModKit(veh, 0) SetVehicleModKit(veh, 0)
end
SetVehicleOnGroundProperly(veh) SetVehicleOnGroundProperly(veh)
debugPrint("^6Bridge^7: ^1Veh ^2Created^7: '^6"..veh.."^7' | ^2Hash^7: ^7'^6"..model.."^7' | ^2Coord^7: "..formatCoord(coords)) debugPrint("^6Bridge^7: ^1Veh ^2Created^7: '^6"..veh.."^7' | ^2Hash^7: ^7'^6"..model.."^7' | ^2Coord^7: "..formatCoord(coords))
@@ -31,39 +33,71 @@ function makeVeh(model, coords)
return veh return veh
end end
--- Attempts to gain network control of a vehicle and set it as a mission entity. local distanceVehicles = {}
--- Creates a vehicle that spawns when the player enters a designated polyzone area.
--- ---
--- This function forces synchronization of a vehicle with other players by requesting network control and setting the vehicle as a mission entity. --- This function sets up a circular polyzone; when the player enters the zone, the vehicle is spawned,
--- and when the player exits, the vehicle is deleted.
--- ---
---@param entity number The handle of the vehicle entity to push. ---@param data table A table containing vehicle data.
--- - **vehicle** `string`: The model name or hash of the vehicle to spawn.
--- - **coords** `vector4`: The coordinates where the vehicle will be placed. Should include x, y, z, and w (heading).
---@param freeze boolean (optional) Whether to freeze the vehicle in place. Defaults to `false`.
---@param synced boolean (optional) Whether the vehicle should be synced across clients. Defaults to `false`.
function makeDistVehicle(data, radius, onEnter, onExit)
local vehicle = nil
local zoneId = keyGen() .. keyGen()
local zone = createCirclePoly({
name = zoneId,
coords = vec3(data.coords.x, data.coords.y, data.coords.z),
radius = radius,
onEnter = function()
vehicle = makeVeh(data.model, data.coords)
if onEnter then
debugPrint("makeDistVehicle onEnter running")
onEnter(vehicle)
end
end,
onExit = function()
deleteVehicle(vehicle)
if onExit then
debugPrint("makeDistVehicle onExit running")
onExit(vehicle)
end
end,
debug = debugMode,
})
distanceVehicles[zoneId] = { zone = zone, vehicle = vehicle }
return zoneId
end
--- Removes a specific distance-based vehicle spawning zone.
--- ---
---@usage ---@param zoneId string The unique identifier of the zone to remove.
--- ```lua function removeDistVehicleZone(zoneId)
--- pushVehicle(vehicle) if distanceVehicles[zoneId].zone then
--- ``` removePolyZone(distanceVehicles[zoneId].zone) -- Adjust this if your polyzone library uses a different removal method.
function pushVehicle(entity) if distanceVehicles[zoneId].vehicle then
SetVehicleModKit(entity, 0) deleteVehicle(distanceVehicles[zoneId].vehicle)
if entity ~= 0 and DoesEntityExist(entity) then
if not NetworkHasControlOfEntity(entity) then
debugPrint("^6Bridge^7: ^3pushVehicle^7: ^2Requesting network control of vehicle^7.")
NetworkRequestControlOfEntity(entity)
local timeout = 2000
while timeout > 0 and not NetworkHasControlOfEntity(entity) do
Wait(100)
timeout -= 100
end end
if NetworkHasControlOfEntity(entity) then debugPrint("^6Bridge^7: ^3pushVehicle^7: ^2Network has control of entity^7.") end distanceVehicles[zoneId] = nil
print("Removed polyzone for zoneId: " .. zoneId)
else
print("No zone found with zoneId: " .. zoneId)
end end
if not IsEntityAMissionEntity(entity) then
debugPrint("^6Bridge^7: ^3pushVehicle^7: ^2Setting vehicle as a ^7'^2mission^7' ^2entity^7.")
SetEntityAsMissionEntity(entity, true, true)
local timeout = 2000
while timeout > 0 and not IsEntityAMissionEntity(entity) do
Wait(100)
timeout -= 100
end end
if IsEntityAMissionEntity(entity) then debugPrint("^6Bridge^7: ^3pushVehicle^7: ^2Vehicle is a ^7'^2mission^7'^2 entity^7.") end
--- Deletes a spawned vehicle.
---
---@param vehicle number The handle of the vehicle entity to delete.
function deleteVehicle(vehicle)
if vehicle then
debugPrint("^6Bridge^7: ^2Destroying Vehicle^7: '^6" .. vehicle .. "^7'")
if IsEntityAttachedToEntity(vehicle, PlayerPedId()) then
SetEntityAsMissionEntity(vehicle)
DetachEntity(vehicle, true, true)
end end
DeleteVehicle(vehicle)
end end
end end

View File

@@ -43,9 +43,10 @@ function progressBar(data)
local result = nil local result = nil
if data.cam then startTempCam(data.cam) end if data.cam then startTempCam(data.cam) end
if Config.System.ProgressBar == "ox" then if Config.System.ProgressBar == "ox" then
if exports[OXLibExport]:progressBar({ local options = {
duration = debugMode and 1000 or data.time, duration = debugMode and 1000 or data.time,
label = data.label, label = data.label,
position = data.position or "bottom",
useWhileDead = data.dead or false, useWhileDead = data.dead or false,
canCancel = data.cancel and data.cancel or true, canCancel = data.cancel and data.cancel or true,
anim = { anim = {
@@ -55,13 +56,42 @@ function progressBar(data)
scenario = data.task scenario = data.task
}, },
disable = { disable = {
combat = true combat = data.combat or true,
move = data.movement or false,
car = data.carMovement or false,
mouse = data.mouse or false
}, },
}) then }
if data.prop and data.prop.model then
options.prop = {
model = data.prop.model,
pos = data.prop.pos or vec3(0, 0, 0),
rot = data.prop.rot or vec3(0, 0, 0),
bone = data.prop.bone or 0
}
end
if data.propTwo and data.propTwo.model then
options.propTwo = {
model = data.propTwo.model,
pos = data.propTwo.pos or vec3(0, 0, 0),
rot = data.propTwo.rot or vec3(0, 0, 0),
bone = data.propTwo.bone or 0
}
end
if data.progressType == "circle" then
if exports[OXLibExport]:progressCircle(options) then
result = true result = true
else else
result = false result = false
end end
end
if not data.progressType or data.progressType == "bar" then
if exports[OXLibExport]:progressBar(options) then
result = true
else
result = false
end
end
elseif Config.System.ProgressBar == "qb" then elseif Config.System.ProgressBar == "qb" then
Core.Functions.Progressbar("progbar", Core.Functions.Progressbar("progbar",
@@ -93,74 +123,173 @@ function progressBar(data)
end end
}) })
elseif Config.System.ProgressBar == "gta" then elseif Config.System.ProgressBar == "red" then
local wait = debugMode and 1000 or data.time -- Currently only uses jim-redui if you choose this option
inProgress = true if exports["jim-redui"]:progressBar({
if not (data.dead or false) then label = data.label,
lockInv(true) time = debugMode and 1000 or data.time,
displaySpinner(data.label) dict = data.dict,
if data.dict then anim = data.anim,
playAnim(data.dict, data.anim, -1, (data.flag == 8 and 32 or data.flag) or nil) flag = data.flag or 32,
task = data.task,
cancel = true,
}) then
result = true
else
result = false
end end
if data.task then
elseif Config.System.ProgressBar == "gta" then
loadTextureDict("timerbars")
if inProgress then return false end
inProgress = true
local wait = debugMode and 1000 or data.time
local endTime = GetGameTimer() + wait
local ped = PlayerPedId()
-- Setup Animation/Task if specified
if data.dict then
playAnim(data.dict, data.anim, -1, data.flag or 32)
elseif data.task then
TaskStartScenarioInPlace(ped, data.task, -1, true) TaskStartScenarioInPlace(ped, data.task, -1, true)
end end
while inProgress and wait > 0 do
wait -= 15 -- Progress bar rendering loop
local waitTimer = 0 CreateThread(function()
while GetGameTimer() < endTime and inProgress do
Wait(0)
local elapsed = GetGameTimer()
local percentage = ((elapsed - (endTime - wait)) / wait) * 100
-- Convert to segmented progress (assuming 5 segments here)
local segments = 5 -- Number of segments in the bar
local segmentProgress = {}
local progressPerSegment = 100 / segments
for i = 1, segments do
local segmentStart = (i - 1) * progressPerSegment
local segmentEnd = i * progressPerSegment
if percentage >= segmentEnd then
segmentProgress[i] = 100
elseif percentage <= segmentStart then
segmentProgress[i] = 0
else
segmentProgress[i] = ((percentage - segmentStart) / progressPerSegment) * 100
end
end
percentage = percentage >= 100 and 100 or percentage
-- Draw your segmented progress bar
ShowGTAProgressBar(segmentProgress, data.label, ("%.0f%%"):format(percentage))
-- Controls to disable during progress
DisablePlayerFiring(ped, true) DisablePlayerFiring(ped, true)
DisableControlAction(0, 25, true) -- Disable aim DisableControlAction(0, 25, true) -- Disable aim
DisableControlAction(0, 21, true) -- Disable sprint DisableControlAction(0, 21, true) -- Disable sprint
DisableControlAction(0, 30, true) -- Disable move left/right DisableControlAction(0, 30, true) -- Disable move left/right
DisableControlAction(0, 31, true) -- Disable move forward/back DisableControlAction(0, 31, true) -- Disable move forward/back
DisableControlAction(0, 36, true) -- Disable stealth DisableControlAction(0, 36, true) -- Disable stealth
if data.cam ~= nil then
DisableControlAction(0, 1, true) -- Disable look left/right if data.cancel and (IsControlJustReleased(0, 202) or IsControlJustReleased(0, 177) or IsControlJustReleased(0, 73)) then
DisableControlAction(0, 2, true) -- Disable look up/down
DisableControlAction(0, 106, true) -- Disable vehicle mouse control
end
if data.cancel then
if IsControlJustReleased(0, 202) or IsControlJustReleased(0, 77) then -- Cancel key (Backspace or Delete)
inProgress = false inProgress = false
waitTimer = 1500
displaySpinner(Loc[Config.Lan].error["cancel"])
end end
end end
Wait(waitTimer) end)
end
inProgress = false -- Wait for completion or cancel
if data.dict then stopAnim(data.dict, data.anim, ped) end while GetGameTimer() < endTime and inProgress do
ClearPedTasks(ped) Wait(100)
end
stopSpinner()
result = (wait <= 0)
end end
while result == nil do Wait(10) end -- Cleanup animations/tasks
if data.dict then stopAnim(data.dict, data.anim, ped) end
ClearPedTasks(ped)
result = inProgress
inProgress = false
end
while result == nil do
Wait(10)
end
-- Cleanup -- Cleanup
FreezeEntityPosition(ped, false) FreezeEntityPosition(ped, false)
lockInv(false) lockInv(false)
if data.cam then stopTempCam(data.cam) end if data.cam then
stopTempCam(data.cam)
end
if result == false and data.shared then if result == false and data.shared then
debugPrint("^6Bridge^7: ^2Sending cancel to ^6"..storedPID.."^7") debugPrint("^6Bridge^7: ^2Sending cancel to ^6"..storedPID.."^7")
TriggerServerEvent(getScript().."server:sharedProg:cancel", storedPID) TriggerServerEvent(getScript().."server:sharedProg:cancel", storedPID)
end end
storedPID = nil storedPID = nil
if result == false then
currentToken = nil
TriggerServerEvent(getScript()..":clearAuthToken")
end
if result == true and data.request then
TriggerServerEvent(getScript()..":clearAuthToken")
currentToken = triggerCallback(AuthEvent)
end
return result return result
end end
function ShowGTAProgressBar(currentProg, title, level)
local loc = vec2(0.37, 0.90)
local size = vec2(0.3, 0.03)
-- Draw background box
DrawSprite("timerbars", "all_black_bg", loc.x +0.028, loc.y-0.01, 0.15, 0.07, 0.0, 255, 255, 255, 255)
DrawSprite("timerbars", "all_black_bg", loc.x +0.170, loc.y-0.01, 0.15, 0.07, 180.0, 255, 255, 255, 255)
SetTextFont(0)
SetTextProportional(1)
SetTextScale(0.35, 0.35)
SetTextColour(255, 255, 255, 255)
SetTextDropshadow(0, 0, 0, 0, 255)
SetTextDropShadow()
SetTextOutline()
SetTextEntry("STRING")
AddTextComponentString(title)
DrawText(loc.x - size.x / 4 + 0.074, loc.y - 0.034) -- Adjust text position
SetTextFont(0)
SetTextProportional(1)
SetTextScale(0.35, 0.25)
SetTextColour(255, 255, 255, 255)
SetTextEntry("STRING")
AddTextComponentString(level)
DrawText(loc.x - size.x / 4 + 0.246, loc.y - 0.030) -- Right-aligned additional text
local segmentWidth = (size.x + 0.05) / (#currentProg * 2) -- Divide the total width by 18 (9 segments * 2 gaps for each)
local gap = segmentWidth / #currentProg -- Smaller gap between segments
for i = 1, #currentProg do
local segmentX = (loc.x - size.x / 4 ) + 0.075 + (i - 1) * (segmentWidth + gap)
local fillPercentage = currentProg[i]
local progressBarWidth = segmentWidth * (fillPercentage / 100)
-- Semi-transparent background for each segment
DrawRect(segmentX + segmentWidth / 2, loc.y, segmentWidth, size.y / 3.4, 100, 100, 100, 255)
-- Filling progress for each segment
if progressBarWidth > 0 then
DrawRect(segmentX + progressBarWidth / 2, loc.y, progressBarWidth, size.y / 3.4, 93, 182, 229, 255) -- Blue progress
end
end
end
--- Stops the current progress bar. --- Stops the current progress bar.
--- ---
--- This function cancels the progress bar based on the configured progress bar system, handling any necessary cleanup. --- This function cancels the progress bar based on the configured progress bar system, handling any necessary cleanup.
function stopPropgressBar() function stopProgressBar()
if Config.System.ProgressBar == "ox" then if Config.System.ProgressBar == "ox" then
exports[OXLibExport]:cancelProgress() exports[OXLibExport]:cancelProgress()
elseif Config.System.ProgressBar == "qb" then elseif Config.System.ProgressBar == "qb" then
TriggerEvent("progressbar:client:cancel") TriggerEvent("progressbar:client:cancel")
elseif Config.System.ProgressBar == "gta" then elseif Config.System.ProgressBar == "gta" or Config.System.ProgressBar == "red" then
inProgress = false inProgress = false
BusyspinnerOff()
end end
end end
@@ -201,9 +330,5 @@ end)
--- This event is triggered when the server wants the client to cancel a shared progress bar. --- This event is triggered when the server wants the client to cancel a shared progress bar.
RegisterNetEvent(getScript()..":client:sharedProg:Cancel", function() RegisterNetEvent(getScript()..":client:sharedProg:Cancel", function()
debugPrint("^6Bridge^7: ^2Receiving cancel progressBar^7") debugPrint("^6Bridge^7: ^2Receiving cancel progressBar^7")
stopPropgressBar() stopProgressBar()
end) end)
--- Cleans up when the resource stops.
--- This event handler ensures that any active spinners or progress bars are stopped when the resource is stopped.
onResourceStop(function() stopSpinner() end, true)

157
shared/metaHandlers.lua Normal file
View File

@@ -0,0 +1,157 @@
--[[
Player Metadata Utilities Module
----------------------------------
This module provides functions for retrieving and setting metadata for players
across different frameworks (QB, ESX, OXCore). It also registers server callbacks
for getting and setting metadata.
]]
-------------------------------------------------------------
-- Player Retrieval
-------------------------------------------------------------
--- Retrieves the player object using the active core export.
---
--- @param source number The server ID of the player.
--- @return table|nil table The player object, or nil if no supported core is detected.
---
--- @usage
--- ```lua
--- local player = GetPlayer(playerId)
--- ```
function GetPlayer(source)
if isStarted(QBExport) then
debugPrint("^6Bridge^7: ^3GetPlayer^7() QBExport")
return exports[QBExport]:GetCoreObject().Functions.GetPlayer(source)
elseif isStarted(QBXExport) then
debugPrint("^6Bridge^7: ^3GetPlayer^7() QBOXExport")
return exports[QBXExport]:GetCoreObject().Functions.GetPlayer(source)
elseif isStarted(ESXExport) then
debugPrint("^6Bridge^7: ^3GetPlayer^7() ESXExport")
return ESX.GetPlayerFromId(source)
elseif isStarted(OXCoreExport) then
debugPrint("^6Bridge^7: ^3GetPlayer^7() OXCoreExport")
return exports[OXCoreExport]:GetPlayer(source)
elseif isStarted(RSGExport) then
debugPrint("^6Bridge^7: ^3GetPlayer^7() RSGExport")
return exports[RSGExport]:GetCoreObject().Functions.GetPlayer(source)
end
return nil
end
-------------------------------------------------------------
-- Metadata Retrieval
-------------------------------------------------------------
--- Retrieves metadata from a player object.
---
--- If called client-side (player is nil), it triggers a server callback to retrieve metadata.
---
--- @param player table|nil The player object; if nil, metadata is retrieved via a server callback.
--- @param key string The metadata key to retrieve.
--- @return any The value of the requested metadata, or nil if not found.
---
--- @usage
--- ```lua
--- local myMeta = GetMetadata(player, "myKey")
--- ```
function GetMetadata(player, key)
if not player then
debugPrint("^6Bridge^7: ^3GetMetadata^7() calling server: "..key)
return triggerCallback(getScript()..":server:GetMetadata", key)
else
if isStarted(QBExport) or isStarted(QBXExport) then
debugPrint("^6Bridge^7: ^3GetMetadata^7() QBExport/QBXExport", key)
return player.PlayerData.metadata[key]
elseif isStarted(ESXExport) then
debugPrint("^6Bridge^7: ^3GetMetadata^7() ESXExport", key)
return player.getMeta(key)
elseif isStarted(OXCoreExport) then
debugPrint("^6Bridge^7: ^3GetMetadata^7() OXCoreExport", key)
return player.get(key)
elseif isStarted(RSGExport) then
debugPrint("^6Bridge^7: ^3GetMetadata^7() RSGExport", key)
return player.PlayerData.metadata[key]
end
end
return nil
end
-- Register a server callback for retrieving metadata.
createCallback(getScript()..":server:GetMetadata", function(source, key)
debugPrint("^6Bridge^7: ^3GetMetadata Callback^7 from source: "..tostring(source)..", key: "..tostring(key))
local player = GetPlayer(source)
if not player then
print("Error getting metadata: player not found for source "..tostring(source))
return
end
if type(key) == "table" then
local Metadata = {}
for _, k in ipairs(key) do
Metadata[k] = GetMetadata(player, k)
end
return Metadata
elseif type(key) == "string" then
return GetMetadata(player, key)
end
end)
-------------------------------------------------------------
-- Metadata Setting
-------------------------------------------------------------
--- Sets metadata on a player object.
---
--- The function updates the player's metadata using the active core export.
---
--- @param player table The player object.
--- @param key string The metadata key to set.
--- @param value any The new value for the metadata key.
---
--- @usage
--- ```lua
--- SetMetadata(player, "myKey", "newValue")
--- ```
function SetMetadata(player, key, value)
debugPrint("^6Bridge^7: ^3SetMetadata^7() setting metadata for key: "..key)
if isStarted(QBExport) or isStarted(QBXExport) then
debugPrint("^6Bridge^7: ^3SetMetadata^7() using QBExport/QBXExport")
player.Functions.SetMetaData(key, value)
elseif isStarted(ESXExport) then
debugPrint("^6Bridge^7: ^3SetMetadata^7() using ESXExport")
player.setMeta(key, value)
elseif isStarted(OXCoreExport) then
debugPrint("^6Bridge^7: ^3SetMetadata^7() using OXCoreExport")
player.set(key, value)
elseif isStarted(RSGExport) then
debugPrint("^6Bridge^7: ^3SetMetadata^7() using RSGExport")
player.Functions.SetMetaData(key, value)
end
end
-- Register a server callback for setting metadata.
createCallback(getScript()..":server:SetMetadata", function(source, key, value)
debugPrint("SetMetadata callback triggered for source:", source, "key:", key, "value:", value)
local player = GetPlayer(source)
--[[if not player then
print("Error setting metadata: player not found for source "..tostring(source))
return false
end]]
SetMetadata(player, key, value)
print("Metadata set successfully.", key)
return true
end)

View File

@@ -1,16 +1,26 @@
-- NOTIFICATIONS -- --[[
-- This function is widely used to display notifications to the player, can be used server side or client side -- Notifications Module
----------------------
This module provides a unified interface for displaying notifications using various
notification systems. The active system is determined by the Config.System.Notify setting.
Supported systems include:
• okok
• qb
• ox
• gta (default)
• esx
]]
--- Displays notifications to the player using the configured notification system. --- Displays notifications to the player using the configured notification system.
--- ---
--- This function supports multiple notification systems based on the `Config.System.Notify` setting. --- Supports multiple notification systems based on Config.System.Notify. Can be triggered from both
--- It can be triggered from both client-side and server-side scripts. Depending on the configuration, --- client and server contexts.
--- it utilizes different exports or events to display the notification.
--- ---
---@param title string|nil The title of the notification. Optional, used by certain notification systems. --- @param title string|nil The notification title (optional for some systems).
---@param message string The main message content of the notification. --- @param message string The main message content.
---@param type string The type/category of the notification (e.g., "success", "error", "info"). --- @param type string The notification type ("success", "error", "info").
---@param src number|nil Optional. The server ID of the player to send the notification to. If `nil`, the notification is sent to the caller. --- @param src number|nil Optional server ID; if provided, the notification is sent to that player.
--- ---
--- @usage --- @usage
--- ```lua --- ```lua
@@ -22,67 +32,101 @@
--- ``` --- ```
function triggerNotify(title, message, type, src) function triggerNotify(title, message, type, src)
if Config.System.Notify == "okok" then if Config.System.Notify == "okok" then
if not src then TriggerEvent('okokNotify:Alert', title, message, 6000, type) if not src then
else TriggerClientEvent('okokNotify:Alert', src, title, message, 6000, type) end TriggerEvent('okokNotify:Alert', title, message, 6000, type)
else
TriggerClientEvent('okokNotify:Alert', src, title, message, 6000, type)
end
elseif Config.System.Notify == "qb" then elseif Config.System.Notify == "qb" then
if not src then TriggerEvent("QBCore:Notify", message, type) if not src then
else TriggerClientEvent("QBCore:Notify", src, message, type) end TriggerEvent("QBCore:Notify", message, type)
else
TriggerClientEvent("QBCore:Notify", src, message, type)
end
elseif Config.System.Notify == "ox" then elseif Config.System.Notify == "ox" then
if not src then TriggerEvent('ox_lib:notify', {title = title, description = message, type = type or "success"}) if not src then
else TriggerClientEvent('ox_lib:notify', src, { type = type or "success", title = title, description = message }) end TriggerEvent('ox_lib:notify', { title = title, description = message, type = type or "success" })
else
TriggerClientEvent('ox_lib:notify', src, { title = title, description = message, type = type or "success" })
end
elseif Config.System.Notify == "gta" then elseif Config.System.Notify == "gta" then
if not src then TriggerEvent(getScript()..":DisplayGTANotify", title, message) if not src then
else TriggerClientEvent(getScript()..":DisplayGTANotify", src, title, message) end exports.jim_bridge:Notify(title, message, type)
else
TriggerClientEvent("jim-bridge:Notify", src, title, message, type)
end
elseif Config.System.Notify == "esx" then elseif Config.System.Notify == "esx" then
if not src then exports["esx_notify"]:Notify(type, 4000, message) if not src then
else TriggerClientEvent(getScript()..":DisplayESXNotify", src, type, title, message) end exports["esx_notify"]:Notify(type, 4000, message)
else
TriggerClientEvent(getScript()..":DisplayESXNotify", src, type, message)
end
elseif Config.System.Notify == "red" then
if isStarted("jim-redui") then
if not src then
TriggerEvent("jim-redui:Notify", title, message, type)
else
TriggerClientEvent("jim-redui:Notify", src, title, message, type)
end end
end end
end
end
-------------------------------------------------------------
-- ESX Notifications
-------------------------------------------------------------
--- Registers a server-side event to display ESX notifications to clients. --- Registers a server-side event to display ESX notifications to clients.
--- ---
--- This event listens for `DisplayESXNotify` and triggers the ESX notification on the client side. --- Listens for DisplayESXNotify events and triggers the ESX notification on the client.
--- ---
--- @param type string The type/category of the notification (e.g., "success", "error", "info"). --- @param type string The notification type.
--- @param title string The title of the notification. --- @param title string The notification title.
--- @param text string The main message content of the notification. --- @param text string The notification message.
--- ---
--- @usage --- @usage
--- ```lua --- ```lua
--- -- Server-side event trigger --- TriggerClientEvent(getScript()..":DisplayESXNotify", playerId, "success", "New achievement unlocked!")
--- TriggerClientEvent(getScript()..":DisplayESXNotify", playerId, "success", "Achievement Unlocked", "You have unlocked a new achievement!")
--- ``` --- ```
RegisterNetEvent(getScript()..":DisplayESXNotify", function(type, title, text) RegisterNetEvent(getScript()..":DisplayESXNotify", function(type, text)
exports["esx_notify"]:Notify(type, 4000, text) exports["esx_notify"]:Notify(type, 4000, text)
end) end)
--- Displays default GTA-style text notifications. -------------------------------------------------------------
-- GTA-style Notifications
-------------------------------------------------------------
--- Displays GTA-style text notifications using native GTA functions.
--- ---
--- This event handles displaying text-based notifications using GTA's native functions. --- Selects an appropriate icon based on the current script (if applicable) and renders the notification.
--- It supports specific scenarios by assigning different icons based on the script name.
--- ---
---@param title string The title or identifier for the notification, used to select the appropriate icon. --- @param title string The notification title/identifier (used to select an icon).
---@param text string The main message content of the notification. --- @param text string The notification message.
--- ---
--- @usage --- @usage
--- ```lua --- ```lua
--- -- Client-side event trigger
--- TriggerEvent(getScript()..":DisplayGTANotify", "taxiname", "Taxi service has arrived.") --- TriggerEvent(getScript()..":DisplayGTANotify", "taxiname", "Taxi service has arrived.")
--- ``` --- ```
RegisterNetEvent(getScript()..":DisplayGTANotify", function(title, text) --RegisterNetEvent(getScript()..":DisplayGTANotify", function(title, text)
local iconTable = {} -- local iconTable = {}
if getScript() == "jim-npcservice" then -- if getScript() == "jim-npcservice" then
iconTable = { -- iconTable = {
[Loc[Config.Lan].notify["taxiname"]] = "CHAR_TAXI", -- [Loc[Config.Lan].notify["taxiname"]] = "CHAR_TAXI",
[Loc[Config.Lan].notify["limoname"]] = "CHAR_CASINO", -- [Loc[Config.Lan].notify["limoname"]] = "CHAR_CASINO",
[Loc[Config.Lan].notify["ambiname"]] = "CHAR_CALL911", -- [Loc[Config.Lan].notify["ambiname"]] = "CHAR_CALL911",
[Loc[Config.Lan].notify["pilotname"]] = "CHAR_DEFAULT", -- [Loc[Config.Lan].notify["pilotname"]] = "CHAR_DEFAULT",
[Loc[Config.Lan].notify["planename"]] = "CHAR_BOATSITE2", -- [Loc[Config.Lan].notify["planename"]] = "CHAR_BOATSITE2",
[Loc[Config.Lan].notify["heliname"]] = "CHAR_BOATSITE2", -- [Loc[Config.Lan].notify["heliname"]] = "CHAR_BOATSITE2",
} -- }
end -- end
BeginTextCommandThefeedPost("STRING") --
AddTextComponentSubstringKeyboardDisplay(text) -- BeginTextCommandThefeedPost("STRING")
EndTextCommandThefeedPostMessagetext(iconTable[title] or "CHAR_DEFAULT", iconTable[title] or "CHAR_DEFAULT", true, 1, title, nil, text) -- AddTextComponentSubstringKeyboardDisplay(text)
EndTextCommandThefeedPostTicker(true, false) -- EndTextCommandThefeedPostMessagetext(
end) -- iconTable[title] or "CHAR_DEFAULT",
-- iconTable[title] or "CHAR_DEFAULT",
-- true, 1, title, nil, text
-- )
-- EndTextCommandThefeedPostTicker(true, false)
--end)

278
shared/phones.lua Normal file
View File

@@ -0,0 +1,278 @@
--[[
Phone Mails Module
------------------
This module handles sending phone mails using different phone systems.
Supported systems include:
- gksphone
- yflip-phone
- qs-smartphone
- qs-smartphone-pro
- roadphone
- lb-phone
- qb-phone
- jpr-phonesystem
]]
--- Sends a phone mail using the detected phone system.
--- The function iterates through a prioritized list of supported phone systems.
--- Once an active system is found (via `isStarted`), the corresponding mail function is executed.
---
--- @param data table A table containing the mail data.
--- - subject (string): The email subject.
--- - sender (string): The sender identifier.
--- - message (string): The email body content.
--- - actions (table|nil): Optional action buttons for the email.
--- @usage
--- sendPhoneMail({
--- subject = "Welcome!",
--- sender = "Admin",
--- message = "Thank you for joining our server.",
--- actions = {
--- { label = "Reply", action = replyFunction }
--- }
--- })
function sendPhoneMail(data)
-- Define each supported phone system and its corresponding mail-sending function.
local phoneSystems = {
{ name = "gksphone",
send = function(mailData)
exports["gksphone"]:SendNewMail(mailData)
end,
},
{ name = "yflip-phone",
send = function(mailData)
TriggerServerEvent(getScript()..":yflip:SendMail", mailData)
end,
},
{ name = "qs-smartphone",
send = function(mailData)
TriggerServerEvent('qs-smartphone:server:sendNewMail', mailData)
end,
},
{ name = "qs-smartphone-pro",
send = function(mailData)
TriggerServerEvent('phone:sendNewMail', mailData)
end,
},
{ name = "roadphone",
send = function(mailData)
-- Convert HTML line breaks to newlines for roadphone.
mailData.message = mailData.message:gsub("%<br>", "\n")
exports["roadphone"]:sendMail(mailData)
end,
},
{ name = "lb-phone",
send = function(mailData)
-- Convert HTML line breaks to newlines for lb-phone.
mailData.message = mailData.message:gsub("%<br>", "\n")
TriggerServerEvent(getScript()..":lbphone:SendMail", mailData)
end,
},
{ name = "qb-phone",
send = function(mailData)
TriggerServerEvent('qb-phone:server:sendNewMail', mailData)
end,
},
{ name = "npwd_qbx_mail",
send = function(mailData)
TriggerServerEvent('qb-phone:server:sendNewMail', mailData)
end,
},
{ name = "jpr-phonesystem",
send = function(mailData)
TriggerServerEvent(getScript()..":jpr:SendMail", mailData)
end,
},
{ name = "ef-phone",
send = function(mailData)
TriggerServerEvent('qb-phone:server:sendNewMail', mailData)
end,
},
}
-- Check each phone system in order and use the first active one.
for _, phone in ipairs(phoneSystems) do
if isStarted(phone.name) then
debugPrint("^6Bridge^7[^3"..phone.name.."^7]: ^2Sending mail to player")
phone.send(data)
return true
end
end
print("^6Bridge^7: ^1ERROR ^2Sending mail to player ^7- ^2No supported phone found")
return false
end
function sendPhoneInvoice(data)
if not data.src then return end
-- Define each supported phone system and its corresponding mail-sending function.
local phoneSystems = {
{
name = "qb-phone",
send = function(mailData)
-- Defensive check for required fields
local required = { "billedCitizenid", "amount", "job", "name", "billerCitizenid", "src" }
for _, field in ipairs(required) do
if mailData[field] == nil then
print("^1[jim-payments] ERROR:^0 Missing field '" .. field .. "' in mailData")
return
end
end
-- Safe insert with all parameters present
MySQL.Async.insert(
'INSERT INTO phone_invoices (citizenid, amount, society, sender, sendercitizenid) VALUES (?, ?, ?, ?, ?)',
{
mailData.billedCitizenid,
mailData.amount,
mailData.job,
mailData.name,
mailData.billerCitizenid
},
function(id)
if id then
TriggerClientEvent('qb-phone:client:AcceptorDenyInvoice', mailData.src, id, mailData.name, mailData.job, mailData.billerCitizenid, mailData.amount, GetInvokingResource())
end
end
)
TriggerClientEvent('qb-phone:RefreshPhone', mailData.src)
end
},
{
name = "codem-phone",
send = function(mailData)
-- Defensive check for required fields
local required = { "billedCitizenid", "amount", "job", "name", "billerCitizenid", "src" }
for _, field in ipairs(required) do
if mailData[field] == nil then
print("^1[jim-payments] ERROR:^0 Missing field '" .. field .. "' in mailData")
return
end
end
-- Safe insert with all parameters present
MySQL.Async.insert(
'INSERT INTO phone_invoices (citizenid, amount, society, sender, sendercitizenid) VALUES (?, ?, ?, ?, ?)',
{
mailData.billedCitizenid,
mailData.amount,
mailData.job,
mailData.name,
mailData.billerCitizenid
},
function(id)
-- if id then
-- TriggerClientEvent('qb-phone:client:AcceptorDenyInvoice', mailData.src, id, mailData.name, mailData.job, mailData.billerCitizenid, mailData.amount, GetInvokingResource())
-- end
end
)
end
},
{
name = "gks-phone",
send = function(mailData)
-- Defensive check for required fields
local required = { "billedCitizenid", "amount", "job", "name", "billerCitizenid", "label" }
for _, field in ipairs(required) do
if mailData[field] == nil then
print("^1[jim-payments] ERROR:^0 Missing field '" .. field .. "' in mailData")
return
end
end
MySQL.Async.execute(
'INSERT INTO gksphone_invoices (citizenid, amount, society, sender, sendercitizenid, label) VALUES (@citizenid, @amount, @society, @sender, @sendercitizenid, @label)',
{
['@citizenid'] = mailData.billedCitizenid,
['@amount'] = mailData.amount,
['@society'] = mailData.job,
['@sender'] = mailData.name,
['@sendercitizenid'] = mailData.billerCitizenid,
['@label'] = mailData.label
}
)
end
}
}
-- Check each phone system in order and use the first active one.
for _, phone in ipairs(phoneSystems) do
if isStarted(phone.name) then
debugPrint("^6Bridge^7[^3"..phone.name.."^7]: ^2Sending mail to player^7", data.src)
phone.send(data)
return true
end
end
print("^6Bridge^7: ^1ERROR ^2Sending mail to player ^7- ^2No supported phone found")
return false
end
-------------------------------------------------------------
-- Phone System Event Handlers
-------------------------------------------------------------
--- Handles sending mail for lb-phone.
--- Listens for the `lbphone:SendMail` event and sends an email using lb-phone's API.
---
--- @event lbphone:SendMail
--- @param data table The mail data.
--- - subject (string): The email subject.
--- - message (string): The email content.
--- - buttons (table|nil): Optional action buttons (mapped from data.actions if present).
RegisterNetEvent(getScript()..":lbphone:SendMail", function(data)
local src = source
local phoneNumber = exports["lb-phone"]:GetEquippedPhoneNumber(src)
local emailAddress = exports["lb-phone"]:GetEmailAddress(phoneNumber)
-- Map actions to buttons if provided.
data.buttons = data.actions or data.buttons
exports["lb-phone"]:SendMail({
to = emailAddress,
subject = data.subject,
message = data.message,
actions = data.buttons,
})
end)
--- Handles sending mail for yflip-phone.
--- Listens for the `yflip:SendMail` event and sends an email using yflip-phone's API.
---
--- @event yflip:SendMail
--- @param data table The mail data.
--- - subject (string): The email subject.
--- - sender (string): The sender identifier.
--- - message (string): The email content.
--- - buttons (table|nil): Optional action buttons.
RegisterNetEvent(getScript()..":yflip:SendMail", function(data)
local src = source
exports["yflip-phone"]:SendMail({
title = data.subject,
sender = data.sender,
senderDisplayName = data.sender,
content = data.message,
actions = data.buttons,
}, 'source', src)
end)
--- Handles sending mail for jpr-phonesystem.
--- Listens for the `jpr:SendMail` event and sends an email using jpr-phonesystem's API.
---
--- @event jpr:SendMail
--- @param data table The mail data.
--- - subject (string): The email subject.
--- - sender (string): The sender identifier.
--- - message (string): The email content.
--- - buttons (table|nil): Optional action buttons.
RegisterNetEvent(getScript()..":jpr:SendMail", function(data)
local src = source
local Player = Core.Functions.GetPlayer(src)
TriggerEvent('jpr-phonesystem:server:sendEmail', {
Assunto = data.subject, -- Email subject
Conteudo = data.message, -- Email content
Enviado = data.sender, -- Sender information
Destinatario = Player.PlayerData.citizenid, -- Recipient identifier
Event = {}, -- Optional event details
})
end)

File diff suppressed because it is too large Load Diff

View File

@@ -1,20 +1,34 @@
-- This automatically detects what polyzone script it should use to create a polyzone -- --[[
-- if ox_lib is detected, it will automatically use that instead of PolyZone -- PolyZone Management Module
-- createPoly({ name = 'name', debug = true, points = { vec2(), vec2() }, onEnter = function() end, onExit = function() end, }) ----------------------------
--- This module automatically detects the available polyzone library (ox_lib or PolyZone)
and creates polygonal and circular zones accordingly. It also provides a function to remove
previously created zones.
Functions:
• createPoly(data) - Creates a polygonal zone.
• createCirclePoly(data) - Creates a circular zone.
• removePolyZone(Location) - Removes a created zone.
]]
-------------------------------------------------------------
-- Polygonal Zone Creation
-------------------------------------------------------------
--- Creates a polygonal zone using the detected polyzone library (ox_lib or PolyZone). --- Creates a polygonal zone using the detected polyzone library (ox_lib or PolyZone).
--- ---
--- This function automatically detects whether `ox_lib` or `PolyZone` is active and creates a polygonal zone accordingly. --- Automatically checks which polyzone script is active. When using ox_lib, it converts the provided
--- It supports setting up entry and exit callbacks for the zone. --- 2D points to 3D (setting a constant z value) and sets a thickness value. For PolyZone, it creates the zone
--- and attaches onEnter and onExit callbacks.
--- ---
---@param data table A table containing the zone configuration. --- @param data table Zone configuration table with the following keys:
--- - **name** (`string`): The name of the zone. --- - name (string): The zone's identifier.
--- - **debug** (`boolean`): Whether to enable debug mode for the zone. --- - debug (boolean): Whether debug mode is enabled.
--- - **points** (`table`): A list of `vec2` points defining the polygon. --- - points (table): A list of vec2 points defining the polygon.
--- - **onEnter** (`function`): Callback function to execute when a player enters the zone. --- - onEnter (function): Callback when a player enters the zone.
--- - **onExit** (`function`): Callback function to execute when a player exits the zone. --- - onExit (function): Callback when a player exits the zone.
--- ---
---@return table|nil table Returns the created zone object or `nil` if creation failed. --- @return table|nil table Returns the created zone object or nil if creation failed.
--- ---
---@usage ---@usage
---```lua ---```lua
@@ -28,18 +42,20 @@
---``` ---```
function createPoly(data) function createPoly(data)
local Location = nil local Location = nil
if isStarted(OXLibExport) then -- if it finds ox_lib, use it instead of PolyZone if isStarted(OXLibExport) then
debugPrint("^6Bridge^7: ^2Creating new poly with ^7'^4"..OXLibExport.."^7': "..data.name) debugPrint("^6Bridge^7: ^2Creating new poly with ^7'^4"..OXLibExport.."^7': "..data.name)
-- Convert 2D points to 3D with a fixed Z coordinate (e.g., 12.0)
for i = 1, #data.points do for i = 1, #data.points do
data.points[i] = vec3(data.points[i].x, data.points[i].y, 12.0) data.points[i] = vec3(data.points[i].x, data.points[i].y, 12.0)
end end
data.thickness = 1000 data.thickness = 1000 -- Set a default thickness value
Location = lib.zones.poly(data) Location = lib.zones.poly(data)
elseif isStarted("PolyZone") then elseif isStarted("PolyZone") then
debugPrint("^6Bridge^7: ^2Creating new poly with ^7'^4PolyZone^7': "..data.name) debugPrint("^6Bridge^7: ^2Creating new poly with ^7'^4PolyZone^7': "..data.name)
Location = PolyZone:Create(data.points, { name = data.name, debugPoly = data.debug }) Location = PolyZone:Create(data.points, { name = data.name, debugPoly = data.debug })
Location:onPlayerInOut(function(isPointInside) Location:onPlayerInOut(function(isPointInside)
if isPointInside then data.onEnter() else data.onExit() end if isPointInside then data.onEnter() else data.onExit() end
end) end)
else else
print("^4ERROR^7: ^2No PolyZone creation script detected ^7- ^2Check ^3exports^1.^2lua^7") print("^4ERROR^7: ^2No PolyZone creation script detected ^7- ^2Check ^3exports^1.^2lua^7")
@@ -47,19 +63,23 @@ function createPoly(data)
return Location return Location
end end
-------------------------------------------------------------
-- Circular Zone Creation
-------------------------------------------------------------
--- Creates a circular zone using the detected polyzone library (ox_lib or PolyZone). --- Creates a circular zone using the detected polyzone library (ox_lib or PolyZone).
--- ---
--- This function automatically detects whether `ox_lib` or `PolyZone` is active and creates a circular zone accordingly. --- When using ox_lib, it creates a sphere zone. For PolyZone, it creates a CircleZone and attaches
--- It supports setting up entry and exit callbacks for the zone. --- onEnter and onExit callbacks.
--- ---
---@param data table A table containing the circular zone configuration. --- @param data table Zone configuration with the following keys:
--- - **name** (`string`): The name of the circular zone. --- - name (string): The zone's identifier.
--- - **coords** (`vector3`): The center coordinates of the circle. --- - coords (vector3): The center of the circle.
--- - **radius** (`number`): The radius of the circle. --- - radius (number): The radius of the circle.
--- - **onEnter** (`function`): Callback function to execute when a player enters the zone. --- - onEnter (function): Callback when a player enters the zone.
--- - **onExit** (`function`): Callback function to execute when a player exits the zone. --- - onExit (function): Callback when a player exits the zone.
--- ---
---@return table|nil table Returns the created circular zone object or `nil` if creation failed. --- @return table|nil table Returns the created circular zone object or nil if creation failed.
--- ---
--- @usage --- @usage
--- ```lua --- ```lua
@@ -73,7 +93,7 @@ end
--- ``` --- ```
function createCirclePoly(data) function createCirclePoly(data)
local Location = nil local Location = nil
if isStarted(OXLibExport) then -- if it finds ox_lib, use it instead of PolyZone if isStarted(OXLibExport) then
debugPrint("^6Bridge^7: ^2Creating new ^3Cricle^2 poly with ^7"..OXLibExport.." "..data.name) debugPrint("^6Bridge^7: ^2Creating new ^3Cricle^2 poly with ^7"..OXLibExport.." "..data.name)
Location = lib.zones.sphere(data) Location = lib.zones.sphere(data)
elseif isStarted("PolyZone") then elseif isStarted("PolyZone") then
@@ -87,26 +107,30 @@ function createCirclePoly(data)
end end
end) end)
else else
print("^4ERROR^7: ^2No PolyZone creation script detected ^7- ^2Check ^3exports^1.^2lua^7") print("^4ERROR^7: ^2No PolyZone creation script detected ^7- ^2Check ^3starter^1.^2lua^7")
end end
debugPrint("^6Bridge^7: ^2Zone Stats - Coords: "..formatCoord(data.coords).." Radius: "..data.radius) debugPrint("^6Bridge^7: ^2Zone Stats - Coords: "..formatCoord(data.coords).." Radius: "..data.radius)
return Location return Location
end end
-------------------------------------------------------------
-- PolyZone Removal Function
-------------------------------------------------------------
--- Removes a previously created polyzone. --- Removes a previously created polyzone.
--- ---
--- This function detects the active polyzone library (`ox_lib` or `PolyZone`) and removes the specified zone accordingly. --- Detects the active polyzone library and calls the appropriate removal method.
--- ---
--- @param Location table The zone object to be removed. --- @param Location table The zone object to be removed.
--- ---
--- @usage --- @usage
--- ```lua --- ```lua
--- local zone = createPoly({...}) --- local zone = createPoly({...})
--- -- Later in the code ---
--- removePolyZone(zone) --- removePolyZone(zone)
--- ``` --- ```
function removePolyZone(Location) function removePolyZone(Location)
if isStarted(OXLibExport) then -- if it finds ox_lib, use it instead of PolyZone if isStarted(OXLibExport) then
debugPrint("^6Bridge^7: ^2Removing ^2poly with ^7"..OXLibExport) debugPrint("^6Bridge^7: ^2Removing ^2poly with ^7"..OXLibExport)
Location:remove() Location:remove()
elseif isStarted("PolyZone") then elseif isStarted("PolyZone") then

View File

@@ -1,61 +0,0 @@
function makeInstructionalButtons(info)
local build = RequestScaleformMovie("instructional_buttons")
while not HasScaleformMovieLoaded(build) do Wait(0) end
DrawScaleformMovieFullscreen(build, 255, 255, 255, 0, 0)
BeginScaleformMovieMethod(build, "CLEAR_ALL")
EndScaleformMovieMethod()
BeginScaleformMovieMethod(build, "SET_CLEAR_SPACE")
ScaleformMovieMethodAddParamInt(200)
EndScaleformMovieMethod()
for i = 1, #info do
BeginScaleformMovieMethod(build, "SET_DATA_SLOT")
ScaleformMovieMethodAddParamInt(i - 1)
for k = 1, #info[i].keys do
ScaleformMovieMethodAddParamPlayerNameString(GetControlInstructionalButton(2, info[i].keys[k], true))
end
BeginTextCommandScaleformString("STRING")
AddTextComponentSubstringKeyboardDisplay(info[i].text)
EndTextCommandScaleformString()
EndScaleformMovieMethod()
end
BeginScaleformMovieMethod(build, "DRAW_INSTRUCTIONAL_BUTTONS")
EndScaleformMovieMethod()
BeginScaleformMovieMethod(build, "SET_BACKGROUND_COLOUR")
ScaleformMovieMethodAddParamInt(0)
ScaleformMovieMethodAddParamInt(0)
ScaleformMovieMethodAddParamInt(0)
ScaleformMovieMethodAddParamInt(80)
EndScaleformMovieMethod()
DrawScaleformMovieFullscreen(build, 255, 255, 255, 255, 0)
end
-- Testing showing variables on the screen instead of only in f8
function debugScaleForm(textTable, loc)
if debugMode then
-- Define the display position (top left corner)
local loc = loc or vec2(0.05, 0.65)
-- Calculate dynamic height based on the number of lines in the textTable
local lineHeight = 0.025 -- Height of each line of text
local totalHeight = #textTable * lineHeight -- Dynamic height based on number of lines
local boxPadding = 0.01 -- Padding to add around the text inside the box
local size = vec2(0.18, totalHeight + boxPadding * 2) -- Width remains fixed, height is dynamic
DrawRect(loc.x + size.x / 2, loc.y + size.y / 2, size.x, size.y, 0, 0, 0, 255)
for i = 1, #textTable do
local textLine = textTable[i]
SetTextScale(0.30, 0.30)
BeginTextCommandDisplayText("STRING")
AddTextComponentSubstringKeyboardDisplay(textLine)
EndTextCommandDisplayText(loc.x + 0.005, loc.y + (i - 1) * lineHeight + 0.01)
end
end
end

View File

@@ -1,6 +1,17 @@
--[[
BigMessage Module
-----------------
This module provides a flexible way to display large, attention-grabbing messages
on screen using a Scaleform movie ("MP_BIG_MESSAGE_FREEMODE"). It supports multiple
message types (mission passed, colored shard, old-style, simple shard, rank-up, weapon purchased,
and large multiplayer messages), including customizable transitions and durations.
]]
BigMessage = {} BigMessage = {}
BigMessage.__index = BigMessage BigMessage.__index = BigMessage
--- Creates a new BigMessage instance.
--- @return table table A new BigMessage object.
function BigMessage:new() function BigMessage:new()
local self = setmetatable({}, BigMessage) local self = setmetatable({}, BigMessage)
self.scaleform = nil self.scaleform = nil
@@ -15,6 +26,7 @@ function BigMessage:new()
return self return self
end end
--- Loads the Scaleform movie if it has not been loaded yet.
function BigMessage:Load() function BigMessage:Load()
if self.scaleform then return end if self.scaleform then return end
self.scaleform = RequestScaleformMovie("MP_BIG_MESSAGE_FREEMODE") self.scaleform = RequestScaleformMovie("MP_BIG_MESSAGE_FREEMODE")
@@ -23,7 +35,8 @@ function BigMessage:Load()
end end
end end
-- Dispose of the scaleform --- Disposes of the Scaleform movie.
--- If manualDispose is true, executes a transition before disposing.
function BigMessage:Dispose() function BigMessage:Dispose()
if not self.scaleform then return end if not self.scaleform then return end
@@ -34,8 +47,8 @@ function BigMessage:Dispose()
ScaleformMovieMethodAddParamBool(self.transitionPreventAutoExpansion) ScaleformMovieMethodAddParamBool(self.transitionPreventAutoExpansion)
EndScaleformMovieMethod() EndScaleformMovieMethod()
-- Wait a fraction of the transition duration (in milliseconds)
Wait((self.transitionDuration * 0.5) * 1000) Wait((self.transitionDuration * 0.5) * 1000)
self.manualDispose = false self.manualDispose = false
end end
@@ -46,8 +59,10 @@ function BigMessage:Dispose()
self.isDisplaying = false self.isDisplaying = false
end end
--- Updates the display by drawing the Scaleform movie fullscreen.
function BigMessage:Update() function BigMessage:Update()
if not self.scaleform then return end if not self.scaleform then return end
DrawScaleformMovieFullscreen(self.scaleform, 255, 255, 255, 255, 0) DrawScaleformMovieFullscreen(self.scaleform, 255, 255, 255, 255, 0)
if self.manualDispose then return end if self.manualDispose then return end
@@ -60,6 +75,7 @@ function BigMessage:Update()
ScaleformMovieMethodAddParamBool(self.transitionPreventAutoExpansion) ScaleformMovieMethodAddParamBool(self.transitionPreventAutoExpansion)
EndScaleformMovieMethod() EndScaleformMovieMethod()
self.transitionExecuted = true self.transitionExecuted = true
-- Extend duration slightly for smooth transition
self.duration = self.duration + ((self.transitionDuration * 0.5) * 1000) self.duration = self.duration + ((self.transitionDuration * 0.5) * 1000)
else else
self:Dispose() self:Dispose()
@@ -67,14 +83,20 @@ function BigMessage:Update()
end end
end end
--- Sets the transition properties for disposing the message.
--- @param transition string The transition function name (default: "TRANSITION_OUT").
--- @param duration number The duration for the transition (default: 0.4).
--- @param preventAutoExpansion boolean Whether to prevent auto-expansion (default: true).
function BigMessage:SetTransition(transition, duration, preventAutoExpansion) function BigMessage:SetTransition(transition, duration, preventAutoExpansion)
self.transition = transition or "TRANSITION_OUT" self.transition = transition or "TRANSITION_OUT"
self.transitionDuration = duration or 0.4 self.transitionDuration = duration or 0.4
self.transitionPreventAutoExpansion = preventAutoExpansion or true self.transitionPreventAutoExpansion = preventAutoExpansion or true
end end
--- Starts a thread to continuously update the HUD until the message is done.
function BigMessage:StartUpdate() function BigMessage:StartUpdate()
if self.isDisplaying then return end if self.isDisplaying then return end
self.isDisplaying = true self.isDisplaying = true
CreateThread(function() CreateThread(function()
while self.isDisplaying do while self.isDisplaying do
@@ -85,10 +107,13 @@ function BigMessage:StartUpdate()
end end
--- Displays a mission passed message. --- Displays a mission passed message.
--- --- @param msg string The message to display.
--- @param msg string The main message to display. --- @param duration number|nil The duration (in milliseconds) to display the message (default: 5000).
--- @param duration number|nil The duration in milliseconds the message should be displayed. Defaults to 5000. --- @param manualDispose boolean|nil Whether to manually dispose the Scaleform after display (default: false).
--- @param manualDispose boolean|nil Whether to manually dispose of the scaleform after the message. Defaults to false. --- @usage
--- ```lua
--- BigMessage:ShowMissionPassedMessage("MISSION PASSED", 5000)
--- ```
function BigMessage:ShowMissionPassedMessage(msg, duration, manualDispose) function BigMessage:ShowMissionPassedMessage(msg, duration, manualDispose)
duration = duration or 5000 duration = duration or 5000
self:Load() self:Load()
@@ -109,13 +134,12 @@ function BigMessage:ShowMissionPassedMessage(msg, duration, manualDispose)
end end
--- Displays a colored shard message. --- Displays a colored shard message.
--- --- @param msg string The main message.
--- @param msg string The main message to display.
--- @param desc string The description text. --- @param desc string The description text.
--- @param textColor number The color index for the text. --- @param textColor number The text color index.
--- @param bgColor number The color index for the background. --- @param bgColor number The background color index.
--- @param duration number|nil The duration in milliseconds the message should be displayed. Defaults to 5000. --- @param duration number|nil Duration in milliseconds (default: 5000).
--- @param manualDispose boolean|nil Whether to manually dispose of the scaleform after the message. Defaults to false. --- @param manualDispose boolean|nil Whether to manually dispose the Scaleform (default: false).
function BigMessage:ShowColoredShard(msg, desc, textColor, bgColor, duration, manualDispose) function BigMessage:ShowColoredShard(msg, desc, textColor, bgColor, duration, manualDispose)
duration = duration or 5000 duration = duration or 5000
self:Load() self:Load()
@@ -125,8 +149,8 @@ function BigMessage:ShowColoredShard(msg, desc, textColor, bgColor, duration, ma
BeginScaleformMovieMethod(self.scaleform, "SHOW_SHARD_CENTERED_MP_MESSAGE") BeginScaleformMovieMethod(self.scaleform, "SHOW_SHARD_CENTERED_MP_MESSAGE")
ScaleformMovieMethodAddParamPlayerNameString(msg) ScaleformMovieMethodAddParamPlayerNameString(msg)
ScaleformMovieMethodAddParamPlayerNameString(desc) ScaleformMovieMethodAddParamPlayerNameString(desc)
ScaleformMovieMethodAddParamInt(bgColor)
ScaleformMovieMethodAddParamInt(textColor) ScaleformMovieMethodAddParamInt(textColor)
ScaleformMovieMethodAddParamInt(bgColor)
EndScaleformMovieMethod() EndScaleformMovieMethod()
self.duration = duration self.duration = duration
@@ -134,12 +158,9 @@ function BigMessage:ShowColoredShard(msg, desc, textColor, bgColor, duration, ma
end end
--- Displays an old-style mission passed message. --- Displays an old-style mission passed message.
--- --- @param msg string The message.
--- @param msg string The main message to display. --- @param duration number|nil Duration in milliseconds (default: 5000).
--- @param duration number|nil The duration in milliseconds the message should be displayed. Defaults to 5000. --- @param manualDispose boolean|nil Whether to manually dispose (default: false).
--- @param manualDispose boolean|nil Whether to manually dispose of the scaleform after the message. Defaults to false.
---
--- @return void
function BigMessage:ShowOldMessage(msg, duration, manualDispose) function BigMessage:ShowOldMessage(msg, duration, manualDispose)
duration = duration or 5000 duration = duration or 5000
self:Load() self:Load()
@@ -155,13 +176,10 @@ function BigMessage:ShowOldMessage(msg, duration, manualDispose)
end end
--- Displays a simple shard message. --- Displays a simple shard message.
--- --- @param msg string The main message.
--- @param msg string The main message to display.
--- @param subtitle string The subtitle text. --- @param subtitle string The subtitle text.
--- @param duration number|nil The duration in milliseconds the message should be displayed. Defaults to 5000. --- @param duration number|nil Duration in milliseconds (default: 5000).
--- @param manualDispose boolean|nil Whether to manually dispose of the scaleform after the message. Defaults to false. --- @param manualDispose boolean|nil Whether to manually dispose (default: false).
---
--- @return void
function BigMessage:ShowSimpleShard(msg, subtitle, duration, manualDispose) function BigMessage:ShowSimpleShard(msg, subtitle, duration, manualDispose)
duration = duration or 5000 duration = duration or 5000
self:Load() self:Load()
@@ -178,12 +196,11 @@ function BigMessage:ShowSimpleShard(msg, subtitle, duration, manualDispose)
end end
--- Displays a rank-up message. --- Displays a rank-up message.
--- --- @param msg string The main message.
--- @param msg string The main message to display.
--- @param subtitle string The subtitle text. --- @param subtitle string The subtitle text.
--- @param rank number The rank level achieved. --- @param rank number The rank level achieved.
--- @param duration number|nil The duration in milliseconds the message should be displayed. Defaults to 5000. --- @param duration number|nil Duration in milliseconds (default: 5000).
--- @param manualDispose boolean|nil Whether to manually dispose of the scaleform after the message. Defaults to false. --- @param manualDispose boolean|nil Whether to manually dispose (default: false).
function BigMessage:ShowRankupMessage(msg, subtitle, rank, duration, manualDispose) function BigMessage:ShowRankupMessage(msg, subtitle, rank, duration, manualDispose)
duration = duration or 5000 duration = duration or 5000
self:Load() self:Load()
@@ -203,12 +220,11 @@ function BigMessage:ShowRankupMessage(msg, subtitle, rank, duration, manualDispo
end end
--- Displays a weapon purchased message. --- Displays a weapon purchased message.
--- --- @param bigMessage string The main message.
--- @param bigMessage string The main message to display.
--- @param weaponName string The name of the weapon purchased. --- @param weaponName string The name of the weapon purchased.
--- @param weaponHash number The hash identifier of the weapon. --- @param weaponHash number The weapon hash.
--- @param duration number|nil The duration in milliseconds the message should be displayed. Defaults to 5000. --- @param duration number|nil Duration in milliseconds (default: 5000).
--- @param manualDispose boolean|nil Whether to manually dispose of the scaleform after the message. Defaults to false. --- @param manualDispose boolean|nil Whether to manually dispose (default: false).
function BigMessage:ShowWeaponPurchasedMessage(bigMessage, weaponName, weaponHash, duration, manualDispose) function BigMessage:ShowWeaponPurchasedMessage(bigMessage, weaponName, weaponHash, duration, manualDispose)
duration = duration or 5000 duration = duration or 5000
self:Load() self:Load()
@@ -228,10 +244,9 @@ function BigMessage:ShowWeaponPurchasedMessage(bigMessage, weaponName, weaponHas
end end
--- Displays a large multiplayer message. --- Displays a large multiplayer message.
--- --- @param msg string The main message.
--- @param msg string The main message to display. --- @param duration number|nil Duration in milliseconds (default: 5000).
--- @param duration number|nil The duration in milliseconds the message should be displayed. Defaults to 5000. --- @param manualDispose boolean|nil Whether to manually dispose (default: false).
--- @param manualDispose boolean|nil Whether to manually dispose of the scaleform after the message. Defaults to false.
function BigMessage:ShowMpMessageLarge(msg, duration, manualDispose) function BigMessage:ShowMpMessageLarge(msg, duration, manualDispose)
duration = duration or 5000 duration = duration or 5000
self:Load() self:Load()
@@ -254,11 +269,10 @@ function BigMessage:ShowMpMessageLarge(msg, duration, manualDispose)
end end
--- Displays a "Wasted" multiplayer message. --- Displays a "Wasted" multiplayer message.
--- --- @param msg string The main message.
--- @param msg string The main message to display.
--- @param subtitle string The subtitle text. --- @param subtitle string The subtitle text.
--- @param duration number|nil The duration in milliseconds the message should be displayed. Defaults to 5000. --- @param duration number|nil Duration in milliseconds (default: 5000).
--- @param manualDispose boolean|nil Whether to manually dispose of the scaleform after the message. Defaults to false. --- @param manualDispose boolean|nil Whether to manually dispose (default: false).
function BigMessage:ShowMpWastedMessage(msg, subtitle, duration, manualDispose) function BigMessage:ShowMpWastedMessage(msg, subtitle, duration, manualDispose)
duration = duration or 5000 duration = duration or 5000
self:Load() self:Load()
@@ -274,4 +288,19 @@ function BigMessage:ShowMpWastedMessage(msg, subtitle, duration, manualDispose)
self:StartUpdate() self:StartUpdate()
end end
--- Starts the update loop for displaying the message.
function BigMessage:StartUpdate()
if self.isDisplaying then return end
self.isDisplaying = true
CreateThread(function()
while self.isDisplaying do
Wait(0)
self:Update()
end
end)
end
-- Create an instance of BigMessage and return it.
BigMessage = BigMessage:new()
return BigMessage return BigMessage

View File

@@ -1,6 +1,18 @@
--[[
CountdownHandler Module
-------------------------
This module provides a countdown HUD using a Scaleform movie ("COUNTDOWN").
It handles loading, updating, and disposing of the scaleform, as well as
playing sounds and displaying messages for each countdown tick.
TriggerNetEvent(getScript()..":startCountdown", 5, 25)
]]
CountdownHandler = {} CountdownHandler = {}
CountdownHandler.__index = CountdownHandler CountdownHandler.__index = CountdownHandler
--- Creates a new CountdownHandler instance.
--- @return table table A new CountdownHandler object.
function CountdownHandler:new() function CountdownHandler:new()
local self = setmetatable({}, CountdownHandler) local self = setmetatable({}, CountdownHandler)
self.scaleform = nil self.scaleform = nil
@@ -9,14 +21,18 @@ function CountdownHandler:new()
return self return self
end end
--- Loads the "COUNTDOWN" scaleform movie.
function CountdownHandler:Load() function CountdownHandler:Load()
if self.scaleform then return end if self.scaleform then
return
end
self.scaleform = RequestScaleformMovie("COUNTDOWN") self.scaleform = RequestScaleformMovie("COUNTDOWN")
while not HasScaleformMovieLoaded(self.scaleform) do while not HasScaleformMovieLoaded(self.scaleform) do
Wait(0) Wait(0)
end end
end end
--- Disposes of the currently loaded scaleform movie.
function CountdownHandler:Dispose() function CountdownHandler:Dispose()
if self.scaleform then if self.scaleform then
SetScaleformMovieAsNoLongerNeeded(self.scaleform) SetScaleformMovieAsNoLongerNeeded(self.scaleform)
@@ -24,15 +40,19 @@ function CountdownHandler:Dispose()
end end
end end
--- Updates the HUD by drawing the scaleform movie fullscreen.
function CountdownHandler:Update() function CountdownHandler:Update()
if self.scaleform then if self.scaleform then
DrawScaleformMovieFullscreen(self.scaleform, 255, 255, 255, 255, 0) DrawScaleformMovieFullscreen(self.scaleform, 255, 255, 255, 255, 0)
end end
end end
--- Displays a message on the countdown HUD.
--- @param message string The message to display.
function CountdownHandler:ShowMessage(message) function CountdownHandler:ShowMessage(message)
local r, g, b, a = self.colour.r, self.colour.g, self.colour.b, self.colour.a local r, g, b, a = self.colour.r, self.colour.g, self.colour.b, self.colour.a
-- Set the message in the scaleform.
BeginScaleformMovieMethod(self.scaleform, "SET_MESSAGE") BeginScaleformMovieMethod(self.scaleform, "SET_MESSAGE")
ScaleformMovieMethodAddParamPlayerNameString(message) ScaleformMovieMethodAddParamPlayerNameString(message)
ScaleformMovieMethodAddParamInt(r) ScaleformMovieMethodAddParamInt(r)
@@ -41,6 +61,7 @@ function CountdownHandler:ShowMessage(message)
ScaleformMovieMethodAddParamBool(true) ScaleformMovieMethodAddParamBool(true)
EndScaleformMovieMethod() EndScaleformMovieMethod()
-- Trigger a fade effect (optional).
BeginScaleformMovieMethod(self.scaleform, "FADE_MP") BeginScaleformMovieMethod(self.scaleform, "FADE_MP")
ScaleformMovieMethodAddParamPlayerNameString(message) ScaleformMovieMethodAddParamPlayerNameString(message)
ScaleformMovieMethodAddParamInt(r) ScaleformMovieMethodAddParamInt(r)
@@ -49,17 +70,14 @@ function CountdownHandler:ShowMessage(message)
EndScaleformMovieMethod() EndScaleformMovieMethod()
end end
--- Starts the countdown with the specified number and HUD color. --- Starts the countdown HUD.
--- --- @param number number|nil The starting number for the countdown (default: 3).
--- @param number number|nil The starting number for the countdown. Defaults to 3. --- @param hudColour number|nil The HUD colour index (default: 18).
--- @param hudColour number|nil The HUD color index. Defaults to 18. --- @return boolean boolean True when the countdown has finished.
---
--- @return boolean `true` when the countdown has finished.
---
--- @usage --- @usage
--- ```lua --- ```lua
--- -- Start a countdown of 5 seconds with HUD color 25
--- if CountdownHandler:Start(5, 25) then --- if CountdownHandler:Start(5, 25) then
--- -- When run in an if statement, the script will wait until its finished to continue
--- print("Countdown Complete") --- print("Countdown Complete")
--- end --- end
--- ``` --- ```
@@ -68,6 +86,7 @@ function CountdownHandler:Start(number, hudColour)
number = number or 3 number = number or 3
hudColour = hudColour or 18 hudColour = hudColour or 18
-- Get HUD colour using framework function; alternatives could be added here.
local r, g, b, a = GetHudColour(hudColour) local r, g, b, a = GetHudColour(hudColour)
self.colour = { r = r, g = g, b = b, a = a } self.colour = { r = r, g = g, b = b, a = a }
@@ -81,18 +100,17 @@ function CountdownHandler:Start(number, hudColour)
end end
end) end)
-- Begin the countdown -- Countdown logic
CreateThread(function() CreateThread(function()
local currentNumber = number local currentNumber = number
while currentNumber > 0 do while currentNumber > 0 do
-- Play countdown sound
playSound("Count") playSound("Count")
self:ShowMessage(tostring(currentNumber)) self:ShowMessage(tostring(currentNumber))
Wait(1000) Wait(1000)
currentNumber = currentNumber - 1 currentNumber = currentNumber - 1
end end
playSound("Go")
playSound("Go")
self:ShowMessage("GO") self:ShowMessage("GO")
finished = true finished = true
@@ -101,14 +119,15 @@ function CountdownHandler:Start(number, hudColour)
self:Dispose() self:Dispose()
finished = true finished = true
end) end)
while not finished do Wait(10) end while not finished do Wait(10) end
return true return true
end end
-- Create an instance of CountdownHandler -- Create a singleton instance of CountdownHandler.
CountdownHandler = CountdownHandler:new() CountdownHandler = CountdownHandler:new()
-- Optional: Register an event to start the countdown -- Register an event to start the countdown.
RegisterNetEvent(getScript()..":startCountdown", function(number, hudColour) RegisterNetEvent(getScript()..":startCountdown", function(number, hudColour)
CountdownHandler:Start(number, hudColour) CountdownHandler:Start(number, hudColour)
end) end)

View File

@@ -1,40 +1,43 @@
-------------------------------------------------------------
-- Debug Text Display Functionality
-------------------------------------------------------------
--- Displays debug information on the player's screen. --- Draws debug text on the screen if debugMode is enabled.
--- ---
--- This function renders a semi-transparent box with multiple lines of text for debugging purposes. --- Calculates a background rectangle based on the number of text lines and renders each line on-screen.
--- It is controlled by the `debugMode` flag and can be positioned dynamically on the screen.
--- ---
--- @param textTable table A table containing strings to display. --- @param textTable table An array of strings to display.
--- @param loc vector2|nil Optional. The screen position to display the debug box. Defaults to `vec2(0.05, 0.65)`. --- @param loc vector2 (Optional) Top-left coordinate for the text box (default: vec2(0.05, 0.65)).
--- ---
--- @usage --- @usage
--- ```lua --- ```lua
---CreateThread(function()
--- while true do
--- debugScaleForm({ --- debugScaleForm({
--- "Player Position: X=123.45 Y=678.90 Z=12.34", --- "Line 1: Debug info",
--- "Current Action: Running", --- "Line 2: More info"
--- }) --- })
--- Wait(0)
--- end
---end)
--- ``` --- ```
function debugScaleForm(textTable, loc) function debugScaleForm(textTable, loc)
if debugMode then if debugMode then
-- Define the display position (top left corner) loc = loc or vec2(0.05, 0.65)
local loc = loc or vec2(0.05, 0.65)
-- Calculate dynamic height based on the number of lines in the textTable local lineHeight = 0.025 -- Height per line.
local lineHeight = 0.025 -- Height of each line of text local totalHeight = #textTable * lineHeight
local totalHeight = #textTable * lineHeight -- Dynamic height based on number of lines local boxPadding = 0.01 -- Padding around the text.
local boxPadding = 0.01 -- Padding to add around the text inside the box local size = vec2(0.18, totalHeight + boxPadding * 2)
local size = vec2(0.18, totalHeight + boxPadding * 2) -- Width remains fixed, height is dynamic
DrawRect(loc.x + size.x / 2, loc.y + size.y / 2, size.x, size.y, 0, 0, 0, 255) -- Draw background rectangle.
DrawRect(loc.x + size.x / 2, loc.y + size.y / 2, size.x, size.y, 0, 0, 0, 200)
-- Render each line of text.
for i = 1, #textTable do for i = 1, #textTable do
local textLine = textTable[i]
SetTextScale(0.30, 0.30) SetTextScale(0.30, 0.30)
BeginTextCommandDisplayText("STRING") BeginTextCommandDisplayText("STRING")
AddTextComponentSubstringKeyboardDisplay(textLine) AddTextComponentSubstringKeyboardDisplay(textTable[i])
EndTextCommandDisplayText(loc.x + 0.005, loc.y + (i - 1) * lineHeight + 0.01) EndTextCommandDisplayText(loc.x + 0.005, loc.y + (i - 1) * lineHeight + 0.01)
end end
end end

View File

@@ -1,30 +1,45 @@
--- Creates instructional buttons using the detected polyzone library (ox_lib or PolyZone). -------------------------------------------------------------
-- Instructional Buttons Functionality
-------------------------------------------------------------
--- Loads and draws instructional buttons on-screen using a scaleform movie.
--- ---
--- This function generates instructional buttons on the player's screen based on the provided information. --- Requests the "instructional_buttons" scaleform, clears previous data, sets clear space,
--- It supports different polyzone libraries by automatically detecting which one is active. --- creates data slots for each button option provided in `info`, and then draws the scaleform fullscreen.
--- ---
---@param info table A table containing the instructional buttons configuration. --- @param info table An array of tables, where each table represents a button option:
--- - **keys** (`table`): A list of control keys to display. --- - keys (table): An array of key codes (e.g., {38, 29}) to display.
--- - **text** (`string`): The description text for the buttons. --- - text (string): The label for the button.
--- ---
--- @usage --- @usage
--- ```lua --- ```lua
---CreateThread(function()
--- while true do
--- makeInstructionalButtons({ --- makeInstructionalButtons({
--- { keys = { 38 }, text = "Interact" }, --- { keys = {38, 29}, text = "Open Menu" },
--- { keys = { 47 }, text = "Pick Up" }, --- { keys = {45}, text = "Close Menu" }
--- }) --- })
--- Wait(0)
--- end
---end)
--- ``` --- ```
function makeInstructionalButtons(info) function makeInstructionalButtons(info)
local build = RequestScaleformMovie("instructional_buttons") local build = RequestScaleformMovie("instructional_buttons")
while not HasScaleformMovieLoaded(build) do Wait(0) end while not HasScaleformMovieLoaded(build) do Wait(0) end
-- Draw the scaleform fullscreen (initial draw).
DrawScaleformMovieFullscreen(build, 255, 255, 255, 0, 0) DrawScaleformMovieFullscreen(build, 255, 255, 255, 0, 0)
-- Clear previous instructions.
BeginScaleformMovieMethod(build, "CLEAR_ALL") BeginScaleformMovieMethod(build, "CLEAR_ALL")
EndScaleformMovieMethod() EndScaleformMovieMethod()
-- Set clear spacing between buttons.
BeginScaleformMovieMethod(build, "SET_CLEAR_SPACE") BeginScaleformMovieMethod(build, "SET_CLEAR_SPACE")
ScaleformMovieMethodAddParamInt(200) ScaleformMovieMethodAddParamInt(200)
EndScaleformMovieMethod() EndScaleformMovieMethod()
-- Add each button option to the scaleform.
for i = 1, #info do for i = 1, #info do
BeginScaleformMovieMethod(build, "SET_DATA_SLOT") BeginScaleformMovieMethod(build, "SET_DATA_SLOT")
ScaleformMovieMethodAddParamInt(i - 1) ScaleformMovieMethodAddParamInt(i - 1)
@@ -37,8 +52,11 @@ function makeInstructionalButtons(info)
EndScaleformMovieMethod() EndScaleformMovieMethod()
end end
-- Draw the instructional buttons.
BeginScaleformMovieMethod(build, "DRAW_INSTRUCTIONAL_BUTTONS") BeginScaleformMovieMethod(build, "DRAW_INSTRUCTIONAL_BUTTONS")
EndScaleformMovieMethod() EndScaleformMovieMethod()
-- Set a translucent black background.
BeginScaleformMovieMethod(build, "SET_BACKGROUND_COLOUR") BeginScaleformMovieMethod(build, "SET_BACKGROUND_COLOUR")
ScaleformMovieMethodAddParamInt(0) ScaleformMovieMethodAddParamInt(0)
ScaleformMovieMethodAddParamInt(0) ScaleformMovieMethodAddParamInt(0)
@@ -46,5 +64,47 @@ function makeInstructionalButtons(info)
ScaleformMovieMethodAddParamInt(80) ScaleformMovieMethodAddParamInt(80)
EndScaleformMovieMethod() EndScaleformMovieMethod()
-- Final full-screen draw with full opacity.
DrawScaleformMovieFullscreen(build, 255, 255, 255, 255, 0) DrawScaleformMovieFullscreen(build, 255, 255, 255, 255, 0)
end end
-- EXPERIMENTAL --
-- RedM Button Prompts --
-- Creates the promot, then shows it, this needs to be run in a loop
local promptGroups = {}
function makeRedInstructionalButtons(info, title)
if not promptGroups[title] then -- Create group if not exists
promptGroups[title] = {
title = CreateVarString(10, 'LITERAL_STRING', title),
id = GetRandomIntInRange(0, 0xffffff),
prompts = {},
}
for i = 1, #info do
promptGroups[title].prompts[i] = {
keys = info[i].keys,
text = info[i].text,
}
local keyTitle = CreateVarString(10, 'LITERAL_STRING', info[i].text)
-- Create one prompt per entry
local promptSet = UiPromptRegisterBegin()
-- Register all keys for this prompt
for k = 1, #info[i].keys do
PromptSetControlAction(promptSet, info[i].keys[k])
end
PromptSetText(promptSet, keyTitle)
PromptSetEnabled(promptSet, true)
PromptSetVisible(promptSet, true)
PromptSetGroup(promptSet, promptGroups[title].id)
PromptRegisterEnd(promptSet)
end
end
PromptSetActiveGroupThisFrame(promptGroups[title].id, promptGroups[title].title)
end
onResourceStop(function()
for k, v in pairs(promptGroups) do
print("^5Bridge^7: ^2Removing Prompt Group^7: ^3" .. k .. "^7")
PromptDelete(promptGroups[k].id, 1)
end
end, true)

View File

@@ -0,0 +1,115 @@
-------------------------------------------------------------
-- 3D Text Rendering
-------------------------------------------------------------
--- Draws 3D text at specified world coordinates.
---
--- Configures text properties, draws the text, and displays a background rectangle behind it.
---
--- @param coord table A vector3 with x, y, and z coordinates.
--- @param text string The text to display.
--- @param highlight boolean (Optional) If true, highlights parts of the text.
---
--- @usage
--- ```lua
--- CreateThread(function()
--- while true do
--- DrawText3D(vector3(100, 200, 300), "Hello World", true)
--- Wait(0)
--- end
--- end)
--- ```
function DrawText3D(coord, text, highlight)
SetTextScale(0.30, 0.30)
SetTextFont(0)
SetTextProportional(1)
SetTextColour(255, 255, 255, 215)
SetTextEntry("STRING")
SetTextCentre(true)
local totalLength = string.len(text)
local textMaxLength = 99 -- max 99
local text = totalLength > textMaxLength and text:sub(1, totalLength - (totalLength - textMaxLength)) or text
AddTextComponentString(highlight and text:gsub("%~w~", "~y~") or text)
SetDrawOrigin(coord.x, coord.y, coord.z, 0)
DrawText(0.0, 0.0)
local count, length = GetLineCountAndMaxLength(text)
local padding = 0.005
local heightFactor = (count / 43) + padding
local weightFactor = (length / 150) + padding
local height = (heightFactor / 2) - padding / 1
local width = (weightFactor / 2) - padding / 1
DrawRect(0.0, height, width, heightFactor, 0, 0, 0, 150)
ClearDrawOrigin()
end
--- Calculates the number of lines and the maximum line length from the given text.
---
--- @param text string The text to analyze.
--- @return number, number The line count and maximum line length.
---
--- @usage
--- ```lua
--- local count, maxLen = GetLineCountAndMaxLength("Hello World")
--- ```
function GetLineCountAndMaxLength(text)
local lineCount, maxLength = 0, 0
for line in text:gmatch("[^\n]+") do
lineCount += 1
local lineLength = string.len(line)
if lineLength > maxLength then
maxLength = lineLength
end
end
if lineCount == 0 then lineCount = 1 end
return lineCount, maxLength
end
-------------------------------------------------------------
-- Additional UI Helpers
-------------------------------------------------------------
--- Displays a help message on the screen.
---
--- @param text string The message to display.
---
--- @usage
--- ```lua
--- DisplayHelpMsg("Press E to interact")
--- ```
function DisplayHelpMsg(text)
BeginTextCommandDisplayHelp("STRING")
AddTextComponentScaleform(text)
EndTextCommandDisplayHelp(0, true, false, -1)
end
--- Displays a "Saving/Loading" spinner with a custom message.
---
--- @param text string The message to display alongside the spinner.
---
--- @usage
--- ```lua
--- displaySpinner("Saving data...")
--- ```
function displaySpinner(text)
BeginTextCommandBusyspinnerOn('STRING')
AddTextComponentSubstringPlayerName(text)
EndTextCommandBusyspinnerOn(4)
end
--- Stops the "Saving/Loading" spinner.
---
--- This function should only be called client-side.
---
--- @usage
--- ```lua
--- stopSpinner()
--- ```
function stopSpinner()
if not isServer() then
BusyspinnerOff()
end
end

View File

@@ -1,3 +1,21 @@
--- Creates and displays a timer HUD on the screen.
--- Draws a title (if provided) and a series of timer bars from the supplied data.
---
--- @param title string|nil Optional title to display at the top of the HUD.
--- @param data table A table of timer bar entries. Each entry should include:
--- - stat (string): The statistic name.
--- - value (string): The value to display.
--- - multi (number|nil): Optional, indicates multiple checkpoints (e.g., progress levels).
--- @param alpha number|nil Optional alpha value (transparency) for the HUD; defaults to 255.
---
--- @usage
--- ```lua
--- createTimerHud("Timer", {
--- { stat = "Health", value = "85%" },
--- { stat = "Armor", value = "50%", multi = 2 },
--- { stat = "Stamina", value = "100%" },
--- }, 255)
--- ```
function createTimerHud(title, data, alpha) function createTimerHud(title, data, alpha)
loadTextureDict("timerbars") loadTextureDict("timerbars")

266
shared/shops.lua Normal file
View File

@@ -0,0 +1,266 @@
-------------------------------------------------------------
-- Selling Menu and Animation
-------------------------------------------------------------
--- Opens a selling menu with available items and prices.
---
--- @param data table Contains selling menu data:
--- - sellTable (`table`) Table with Header and Items (item names and prices).
--- - ped (optional) (`number`) Ped entity involved.
--- - onBack (optional) (`function`) Callback for returning.
--- @usage
--- ```lua
--- sellMenu({
--- sellTable = {
--- Header = "Sell Items",
--- Items = {
--- ["gold_ring"] = 100,
--- ["diamond"] = 500,
--- },
--- },
--- ped = pedEntity,
--- onBack = function() print("Returning to previous menu") end,
--- })
--- ```
function sellMenu(data)
local origData = data
local Menu = {}
if data.sellTable.Items then
local itemList = {}
for k, v in pairs(data.sellTable.Items) do itemList[k] = 1 end
local _, hasTable = hasItem(itemList)
for k, v in pairsByKeys(data.sellTable.Items) do
if Items[k] then
Menu[#Menu + 1] = {
isMenuHeader = not hasTable[k].hasItem,
icon = invImg(k),
header = Items[k].label..(hasTable[k].hasItem and "💰 (x"..hasTable[k].count..")" or ""),
txt = (Loc and Loc[Config.Lan]) and Loc[Config.Lan].info["sell_all"]..v.." "..Loc[Config.Lan].info["sell_each"]
or "Sell ALL at $"..v.." each",
onSelect = function()
sellAnim({ item = k, price = v, ped = data.ped, onBack = function() sellMenu(data) end })
end,
}
end
end
else
for k, v in pairsByKeys(data.sellTable) do
if type(v) == "table" then
Menu[#Menu + 1] = {
arrow = true,
header = k,
txt = "Amount of items: "..countTable(v.Items),
onSelect = function()
v.onBack = function()
sellMenu(origData)
end
v.sellTable = data.sellTable[k]
sellMenu(v)
end,
}
end
end
end
openMenu(Menu, {
header = data.sellTable.Header or "Amount of items: "..countTable(data.sellTable.Items or data.sellTable),
headertxt = data.sellTable.Header and "Amount of items: "..countTable(data.sellTable.Items or data.sellTable),
canClose = true,
onBack = data.onBack,
})
end
--- Plays the selling animation and processes the sale transaction.
---
--- Checks if the player has the item, plays animations, triggers the server event for selling,
--- and then calls the onBack callback if provided.
---
--- @param data table Contains:
--- `- item: The item to sell.
--- `- price: Price per item.
--- `- ped (optional): Ped entity involved.
--- `- onBack (optional): Callback to call on completion.
---@usage
--- ```lua
--- sellAnim({
--- item = "gold_ring",
--- price = 100,
--- ped = pedEntity,
--- onBack = function() sellMenu(data) end,
--- })
--- ```
function sellAnim(data)
if not hasItem(data.item, 1) then
triggerNotify(nil, Loc[Config.Lan].error["dont_have"].." "..Items[data.item].label, "error")
return
end
-- Remove any attached clipboard objects.
for _, obj in pairs(GetGamePool('CObject')) do
for _, model in pairs({ `p_cs_clipboard` }) do
if GetEntityModel(obj) == model and IsEntityAttachedToEntity(data.ped, obj) then
DeleteObject(obj)
DetachEntity(obj, 0, 0)
SetEntityAsMissionEntity(obj, true, true)
Wait(100)
DeleteEntity(obj)
end
end
end
TriggerServerEvent(getScript().."Sellitems", data)
lookEnt(data.ped)
local dict = "mp_common"
playAnim(dict, "givetake2_a", 0.3, 48)
playAnim(dict, "givetake2_b", 0.3, 48, data.ped)
Wait(2000)
StopAnimTask(PlayerPedId(), dict, "givetake2_a", 0.5)
StopAnimTask(data.ped, dict, "givetake2_b", 0.5)
if data.onBack then
data.onBack()
end
end
--- Server event handler for processing item sales.
--- Removes sold items from inventory and funds the player based on the sale.
RegisterNetEvent(getScript().."Sellitems", function(data)
local src = source
local hasItems, hasTable = hasItem(data.item, 1, src)
if hasItems then
removeItem(data.item, hasTable[data.item].count, src)
fundPlayer((hasTable[data.item].count * data.price), "cash", src)
else
triggerNotify(nil, Loc[Config.Lan].error["dont_have"].." "..Items[data.item].label, "error", src)
end
end)
-------------------------------------------------------------
-- Shop Interface
-------------------------------------------------------------
--- Opens a shop interface for the player.
---
--- Checks job/gang restrictions, then uses the active inventory system to open the shop.
--- @param data table Contains:
--- - shop (`string`) The shop identifier.
--- - items (`table`) The items available in the shop.
--- - coords (`vector3`) where the shop is located.
--- - job/gang (optional) (`string`) Job or gang requirements.
---@usage
--- ```lua
--- openShop({
--- shop = "weapon_shop",
--- items = weaponShopItems,
--- coords = vector3(100.0, 200.0, 300.0),
--- job = "police",
--- })
--- ```
function openShop(data)
jsonPrint(data)
if (data.job or data.gang) and not jobCheck(data.job or data.gang) then return end
if Config.General.JimShops then
TriggerServerEvent("jim-shops:ShopOpen", "shop", data.items.label, data.items)
elseif isStarted(OXInv) then
exports[OXInv]:openInventory('shop', { type = data.shop })
elseif isStarted(QSInv) then
TriggerServerEvent("inventory:server:OpenInventory", "shop", data.items.label, data.items)
elseif isStarted(TgiannInv) then
TriggerServerEvent(getScript()..':server:openServerShop', data.shop)
elseif isStarted(CodeMInv) then
--print(data.shop)
TriggerEvent("codem-inventory:openshop", data.shop)
elseif isStarted(QBInv) then
if QBInvNew then
TriggerServerEvent(getScript()..':server:openServerShop', data.shop)
else
TriggerServerEvent("inventory:server:OpenInventory", "shop", data.items.label, data.items)
end
elseif isStarted(PSInv) then
if QBInvNew then
TriggerServerEvent(getScript()..':server:openServerShop', data.shop)
else
TriggerServerEvent("inventory:server:OpenInventory", "shop", data.items.label, data.items)
end
elseif isStarted(RSGInv) then
TriggerServerEvent(getScript()..':server:openServerShop', data.shop)
end
lookEnt(data.coords)
end
RegisterNetEvent(getScript()..':server:openServerShop', function(data)
if isStarted(QBInv) then
exports[QBInv]:OpenShop(source, data)
end
if isStarted(PSInv) then
exports[PSInv]:OpenShop(source, data)
end
if isStarted(TgiannInv) then
exports[TgiannInv]:OpenShop(source, data)
end
if isStarted(RSGInv) then
exports[RSGInv]:OpenShop(source, data)
end
end)
--- Registers a shop with the active inventory system.
--- Supports either OXInv or QBInv (with QBInvNew flag).
---
--- @param name string Unique shop identifier.
--- @param label string Display name for the shop.
--- @param items table List of available shop items.
--- @param society string|nil (Optional) Society identifier for shared shops.
--- @usage
--- ```lua
--- registerShop("weaponShop", "Weapon Shop", weaponItems, "society_weapons")
--- ```
function registerShop(name, label, items, society)
if isStarted(OXInv) then
debugPrint("^6Bridge^7: ^2Registering ^3OX ^2Store^7:", name, label)
exports[OXInv]:RegisterShop(name, {
name = label,
inventory = items,
society = society,
})
elseif isStarted(TgiannInv) then
debugPrint("^6Bridge^7: ^2Registering ^3Tgiann ^2Store^7:", name, label)
exports[TgiannInv]:RegisterShop(name, items)
elseif isStarted(QBInv) and QBInvNew then
debugPrint("^6Bridge^7: ^2Registering ^3QB ^2Store^7:", name, label)
exports[QBInv]:CreateShop({
name = name,
label = label,
slots = #items,
items = items,
society = society,
})
elseif isStarted(PSInv) and QBInvNew then
debugPrint("^6Bridge^7: ^2Registering ^3PS ^2Store^7:", name, label)
exports[PSInv]:CreateShop({
name = name,
label = label,
slots = #items,
items = items,
society = society,
})
elseif isStarted(RSGInv) then
debugPrint("^6Bridge^7: ^2Registering ^3RSG ^2Store^7:", name, label)
exports[RSGInv]:CreateShop({
name = name,
label = label,
slots = #items,
items = items,
society = society,
})
end
end

39
shared/skillcheck.lua Normal file
View File

@@ -0,0 +1,39 @@
local activeSkillCheck = false
function skillCheck(data)
local result = false
if Config.System.skillCheck == "qb" then
local Skillbar = exports["qb-minigames"]:Skillbar()
if Skillbar then
result = true
else
result = false
end
elseif Config.System.skillCheck == "ox" then
local Skillbar = exports[OXLibExport]:skillCheck(
{
"easy",
"easy",
"easy"
},
{
"1",
"2",
"3",
"4"
})
if Skillbar then
result = true
else
result = false
end
elseif Config.System.skillCheck == "gta" then
exports.jim_bridge:skillCheck()
else
result = true
end
return result
end

203
shared/societybank.lua Normal file
View File

@@ -0,0 +1,203 @@
--[[
Society Banking Module
------------------------
This module provides functions to interact with society bank accounts across
different banking systems. Supported systems include:
• qb-banking
• esx_society *testing*
• Renewed-Banking
• fd_banking
• okokBanking
• Tgiann-bank
]]
--- Retrieves the current balance of a society's bank account.
--- @param society string The identifier of the society.
--- @return number number The current account balance.
--- @usage
--- ```lua
--- local balance = getSocietyAccount("police")
--- print("Police account balance: $"..balance)
--- ```
function getSocietyAccount(society)
local bankScript, amount = "", 0
if society == nil or society == "none" then return amount end
if isStarted("qb-banking") then
bankScript = "qb-banking"
if not exports["qb-banking"]:GetAccount(society) then
if Jobs[society] then
print("^6Bridge^7: ^2Making new bank account in ^7'^3qb-banking^7' ^2for ^7'^3"..society.."^7'")
exports["qb-banking"]:CreateJobAccount(society, 0)
Wait(150)
elseif Gangs[society] then
print("^6Bridge^7: ^2Making new bank account in ^7'^3qb-banking^7' ^2for ^7'^3"..society.."^7'")
exports["qb-banking"]:CreateGangAccount(society, 0)
Wait(150)
end
end
amount = exports["qb-banking"]:GetAccountBalance(society)
--elseif isStarted("esx_society") then
-- bankScript = "esx_society"
-- -- Since esx_society does not have a native client export for retrieving money,
-- -- we use a server callback to get the final amount.
-- amount = triggerCallback(getScript()..":getESXSocietyAccount", society) or 0
elseif isStarted("Renewed-Banking") then
bankScript = "Renewed-Banking"
amount = exports["Renewed-Banking"]:getAccountMoney(society)
elseif isStarted("fd_banking") then
bankScript = "fd_banking"
amount = exports["fd_banking"]:GetAccount(society)
elseif isStarted("okokBanking") then
bankScript = "okokBanking"
amount = exports['okokBanking']:GetAccount(society)
elseif isStarted("tgiann-bank") then
bankScript = "tgiann-bank"
if Jobs[society] then
amount = exports["tgiann-bank"]:GetJobAccountBalance(society)
else
amount = exports["tgiann-bank"]:GetGangAccountBalance(society)
end
end
if bankScript == "" then
print("^1Error^7: ^3GetSocietyAccount^7: ^2No supported banking script found")
else
debugPrint("^6Bridge^7: ^3"..bankScript.."^7: ^2Retrieved account ^7'^6"..society.."^7' ($"..amount..")")
end
return amount
end
--- Deducts funds from a society's bank account.
--- @param society string The identifier of the society.
--- @param amount number The amount of money to remove.
--- @usage
--- ```lua
--- chargeSociety("police", 1000)
--- ```
function chargeSociety(society, amount)
local bankScript, newAmount = "", 0
if isStarted("qb-banking") then
bankScript = "qb-banking"
if not exports["qb-banking"]:GetAccount(society) then
if Jobs[society] then
print("^6Bridge^7: ^2Making new bank account in ^7'^3qb-banking^7' ^2for ^7'^3"..society.."^7'")
exports["qb-banking"]:CreateJobAccount(society, 0) Wait(150) -- make new account if return "null"
elseif Gangs[society] then
print("^6Bridge^7: ^2Making new bank account in ^7'^3qb-banking^7' ^2for ^7'^3"..society.."^7'")
exports["qb-banking"]:CreateGangAccount(society, 0) Wait(150) -- make new account if return "null"
end
end
exports["qb-banking"]:RemoveMoney(society, amount)
--elseif isStarted("esx_society") then
-- bankScript = "esx_society"
-- TriggerEvent("esx_society:withdrawMoney", society, amount)
elseif isStarted("Renewed-Banking") then
bankScript = "Renewed-Banking"
exports['Renewed-Banking']:removeAccountMoney(society, amount)
elseif isStarted("fd_banking") then
bankScript = "fd_banking"
exports["fd_banking"]:RemoveMoney(society, amount)
elseif isStarted("okokBanking") then
bankScript = "okokBanking"
exports['okokBanking']:RemoveMoney(society, amount)
elseif isStarted("tgiann-bank") then
bankScript = "tgiann-bank"
if Jobs[society] then
exports["tgiann-bank"]:RemoveJobMoney(society, amount)
else
exports["tgiann-bank"]:RemoveGangMoney(society, amount)
end
end
if bankScript == "" then
print("^1Error^7: ^3ChargeSociety^7: ^2No supported banking script found")
else
newAmount = getSocietyAccount(society)
debugPrint("^6Bridge^7: ^3"..bankScript.."^7: ^2Removing $"..amount.." from account '^6"..society.."^7' ($"..newAmount..")")
end
end
--- Adds funds to a society's bank account.
--- @param society string The identifier of the society.
--- @param amount number The amount of money to add.
--- @usage
--- ```lua
--- fundSociety("police", 500)
--- ```
function fundSociety(society, amount)
local bankScript, newAmount, success = "", 0, false
if isStarted("qb-banking") then
bankScript = "qb-banking"
if not exports["qb-banking"]:GetAccount(society) then
if Jobs[society] then
print("^6Bridge^7: ^2Making new bank account in ^7'^3qb-banking^7' ^2for ^7'^3"..society.."^7'")
exports["qb-banking"]:CreateJobAccount(society, 0)
Wait(150)
elseif Gangs[society] then
print("^6Bridge^7: ^2Making new bank account in ^7'^3qb-banking^7' ^2for ^7'^3"..society.."^7'")
exports["qb-banking"]:CreateGangAccount(society, 0)
Wait(150)
end
end
exports["qb-banking"]:AddMoney(society, amount)
--elseif isStarted("esx_society") then
-- bankScript = "esx_society"
-- -- Use the esx_society event to deposit money.
-- TriggerServerEvent('esx_society:depositMoney', society, amount)
-- -- Use callback to return the updated balance.
-- newAmount = triggerCallback(getScript()..":getESXSocietyAccount", society) or 0
elseif isStarted("Renewed-Banking") then
bankScript = "Renewed-Banking"
exports['Renewed-Banking']:addAccountMoney(society, amount)
newAmount = exports["Renewed-Banking"]:getAccountMoney(society)
elseif isStarted("fd_banking") then
bankScript = "fd_banking"
exports["fd_banking"]:AddMoney(society, amount)
elseif isStarted("okokBanking") then
bankScript = "okokBanking"
exports['okokBanking']:AddMoney(society, amount)
elseif isStarted("tgiann-bank") then
bankScript = "tgiann-bank"
if Jobs[society] then
exports["tgiann-bank"]:AddJobMoney(society, amount)
else
exports["tgiann-bank"]:AddGangMoney(society, amount)
end
end
if bankScript == "" then
print("^1Error^7: ^3FundSociety^7: ^2No supported banking script found")
else
newAmount = getSocietyAccount(society)
debugPrint("^6Bridge^7: ^3"..bankScript.."^7: ^2Adding ^7$"..amount.." ^2to account ^7'^6"..society.."^7' ($"..newAmount..")")
end
end
-- other
if isStarted("esx_society") then
createCallback(getScript()..":getESXSocietyAccount", function(source, society)
-- Example query adjust table/field names to match your esx_society implementation.
local result = MySQL.scalar.await('SELECT money FROM society_money WHERE society = ?', { society })
return result or 0
end)
end

View File

@@ -1,46 +1,105 @@
if isServer() then --[[
createCallback(getScript()..':server:GetStashItems', function(source, stashName) local stash = getStash(stashName) return stash end) Stash Management Module
end -------------------------
This module handles stash-related operations including:
• Retrieving stash items (from server or local cache).
• Checking for required items in stashes.
• Opening stashes using different inventory systems.
• Removing items from stashes.
• Checking if a stash has specific items.
]]
local stashCache ={} -- Global variable to hold the current stash (used in callbacks).
function GetStashTimeout(stashName, stop) local stash
if stop then stashCache = {} return end
local stash = stashCache[stashName] -- If running on the server, create a callback to retrieve stash items.
if not stash then if isServer() then
stashCache[stashName] = { items = {}, timeout = 0 } createCallback(getScript()..':server:GetStashItems', function(source, stashName)
stash = stashCache[stashName] stash = getStash(stashName)
end return stash
if #stash.items > 0 then return true end
if stash.timeout <= 0 then
stash.items = triggerCallback(getScript()..':server:GetStashItems', stashName)
stash.timeout = 10000
CreateThread(function()
while stash.timeout > 0 do stash.timeout -= 1000 Wait(1000) end
stashCache[stashName] = nil
end) end)
end end
-- Local cache for stashes.
local stashCache = {}
--- Retrieves (or updates) a local stash cache entry with a timeout.
--- When the cache is empty or expired, it triggers a server callback to update the items.
---
--- @param stashName string The name of the stash.
--- @param stop boolean (Optional) If true, clears the entire stash cache.
--- @return boolean True if items exist in cache (and recheck is skipped), false otherwise.
---
--- @usage
--- ```lua
--- local cached = GetStashTimeout("playerStash")
--- ```
function GetStashTimeout(stashName, stop)
if stop then
stashCache = {}
return
end
-- Retrieve cache for this stash, or initialize if not present.
stash = stashCache[stashName]
if not stash then
debugPrint("^6Bridge^7: ^2Local Stash ^7'^3"..stashName.."^7'^2 cache ^1not ^2found^7, ^2need to grab from server^7")
stashCache[stashName] = { items = {}, timeout = 0 }
stash = stashCache[stashName]
else
debugPrint("^6Bridge^7: ^2Local Stash for ^7'^3"..stashName.."^7'^2 cache found^7")
end
-- If there are already items in cache, skip recheck.
if countTable(stashCache[stashName].items) > 0 then
debugPrint("^6Bridge^7: '^3"..stashName.."^7' ^2Items found in local cache, skipping server recheck")
return true
end
-- If timeout has expired, update the stash items from the server.
if stashCache[stashName].timeout <= 0 then
stashCache[stashName].items = triggerCallback(getScript()..':server:GetStashItems', stashName)
stashCache[stashName].timeout = 10000 -- Timeout in milliseconds.
CreateThread(function()
while stashCache[stashName] and stashCache[stashName].timeout > 0 do
stashCache[stashName].timeout -= 1000
Wait(1000)
end
debugPrint("^6Bridge^7: ^2Local Stash ^7'^3"..stashName.."^7'^2 cache timed out^7, ^3Clearing^7")
stashCache[stashName] = nil
end)
end
return false return false
end end
function checkHasItem(stashes, itemTable) --- Checks if the specified stashes have the required items.
if not stashes then return hasItem(itemTable), nil end ---
--- If multiple stashes are provided (as a table), it iterates over each until all required items are found.
---
--- @param stashes string|table Either a single stash name or a table of stash names.
--- @param itemTable table A table where keys are item names and values are the required amounts.
--- @return boolean, string|nil `boolean, string` true and the stash name if found, otherwise false and nil.
---
--- @usage
--- ```lua
--- local found, stashName = checkStashItem({"playerStash", "storageStash"}, { iron = 2, wood = 5 })
--- ```
function checkStashItem(stashes, itemTable)
if not stashes then
return hasItem(itemTable), nil
end
if type(stashes) == "table" then if type(stashes) == "table" then
local succeses = 0 debugPrint("^6Bridge^7: ^2Checking multiple stashes for ingredients^7")
local itemCount = 0 -- Iterate over each provided stash name.
for _, item in pairs(itemTable) do itemCount += 1 end
for _, name in pairs(stashes) do for _, name in pairs(stashes) do
GetStashTimeout(name) GetStashTimeout(name)
for item, amount in pairs(itemTable) do if stashhasItem(stashCache[name].items, itemTable, nil) then
debugPrint("^6Bridge^7: ^2Checking"..(name and " ^7'^6"..name.."^7'" or "").." ^2ingredients^7 - ^6"..item.."^7") return true, name
if stashhasItem(stashCache[name].items, item, amount) then
succeses += 1
if succeses == itemCount then return true, name end
end
end end
end end
else else
debugPrint("^6Bridge^7: ^2Checking"..(stashes and " ^7'^6"..stashes.."^7'" or "").." ^2ingredients^7 - ^6"..k.."^7") debugPrint("^6Bridge^7: ^2Checking "..(stashes and " '^3"..stashes.."^7'" or "").." ingredients")
GetStashTimeout(stashes) GetStashTimeout(stashes)
return stashhasItem(stashCache[stashes].items, itemTable), stashes return stashhasItem(stashCache[stashes].items, itemTable), stashes
end end
@@ -48,56 +107,280 @@ function checkHasItem(stashes, itemTable)
return false, nil return false, nil
end end
-------------------------------------------------------------
-- Stash Opening Functions
-------------------------------------------------------------
-- Stash Items --- Opens a stash using the active inventory system.
---
--- Checks for job or gang restrictions before opening the stash.
---
--- @param data table A table containing stash data:
--- - stash (string): The stash identifier.
--- - label (string): Display label.
--- - maxWeight (number|nil): Maximum weight (default 600000).
--- - slots (number|nil): Number of slots (default 40).
--- - stashOptions (table|nil): Additional options for the stash.
--- - job/gang (string|nil): Restriction for access.
--- - coords (vector3): Coordinates to "look" at.
---
--- @usage
--- ```lua
--- openStash({ stash = "playerStash", label = "Player Stash", coords = vector3(100, 200, 30) })
--- ```
function openStash(data) function openStash(data)
if (data.job or data.gang) and not jobCheck(data.job or data.gang) then return end if (data.job or data.gang) and not jobCheck(data.job or data.gang) then return end
if isStarted(OXInv) then if isStarted(OXInv) then
exports[OXInv]:openInventory('stash', data.stash) exports[OXInv]:openInventory('stash', data.stash)
elseif isStarted(CoreInv) then
TriggerServerEvent('core_inventory:server:openInventory', data.stash, 'stash')
elseif isStarted(CodeMInv) then elseif isStarted(CodeMInv) then
exports[CodeMInv]:OpenStash(data.stash, StashWeight, 100) TriggerServerEvent('codem-inventory:server:openstash', data.stash, data.slots, data.maxWeight, data.label)
elseif isStarted(OrigenInv) then
exports[OrigenInv]:openInventory('stash', data.stash, { label = data.label })
elseif isStarted(TgiannInv) then
TriggerServerEvent(getScript()..':server:openServerStash', {
stashName = data.stash,
label = data.label,
maxweight = data.maxWeight or 600000,
slots = data.slots or 40
})
elseif isStarted(JPRInv) then
if QBInvNew then
TriggerServerEvent(getScript()..':server:openServerStash', {
stashName = data.stash,
label = data.label,
maxweight = data.maxWeight or 600000,
slots = data.slots or 40
})
else
TriggerEvent("inventory:client:SetCurrentStash", data.stash)
TriggerServerEvent("inventory:server:OpenInventory", "stash", data.stash, {
slots = data.slots or 50,
maxWeight = data.maxWeight or 600000
})
end
elseif isStarted(QBInv) then elseif isStarted(QBInv) then
if QBInvNew then if QBInvNew then
TriggerServerEvent(getScript()..':server:OpenStashQB', { stashName = data.stash, label = data.label, maxweight = data.maxWeight or 600000, slots = data.slots or 40 }) TriggerServerEvent(getScript()..':server:openServerStash', {
stashName = data.stash,
label = data.label,
maxweight = data.maxWeight or 600000,
slots = data.slots or 40
})
else else
TriggerEvent("inventory:client:SetCurrentStash", data.stash) TriggerEvent("inventory:client:SetCurrentStash", data.stash)
TriggerServerEvent("inventory:server:OpenInventory", "stash", data.stash, data.stashOptions) TriggerServerEvent("inventory:server:OpenInventory", "stash", data.stash, {
slots = data.slots or 50,
maxWeight = data.maxWeight or 600000
})
end end
elseif isStarted(PSInv) then
if QBInvNew then
TriggerServerEvent(getScript()..':server:openServerStash', {
stashName = data.stash,
label = data.label,
maxweight = data.maxWeight or 600000,
slots = data.slots or 40
})
else else
TriggerEvent("inventory:client:SetCurrentStash", data.stash) TriggerEvent("inventory:client:SetCurrentStash", data.stash)
TriggerServerEvent("inventory:server:OpenInventory", "stash", data.stash, data.stashOptions) TriggerServerEvent("inventory:server:OpenInventory", "stash", data.stash, {
slots = data.slots or 50,
maxWeight = data.maxWeight or 600000
})
end end
elseif isStarted(RSGInv) then
TriggerServerEvent(getScript()..':server:openServerStash', {
stashName = data.stash,
label = data.label,
maxweight = data.maxWeight or 600000,
slots = data.slots or 40
})
else
--Fallback to these commands
TriggerEvent("inventory:client:SetCurrentStash", data.stash)
TriggerServerEvent("inventory:server:OpenInventory", "stash", data.stash, {
slots = data.slots or 50,
maxWeight = data.maxWeight or 600000
})
end
lookEnt(data.coords) lookEnt(data.coords)
end end
RegisterNetEvent(getScript()..':server:OpenStashQB', function(data)
-- Wrapper function for opening stash from the server.
-- Messy but not much else I can do about it.
RegisterNetEvent(getScript()..":server:openServerStash", function(data)
local src = source
if isStarted(TgiannInv) then
exports[TgiannInv]:OpenInventory(source, 'stash', data.stashName, data)
end
if isStarted(JPRInv) then
exports[JPRInv]:OpenInventory(source, data.stashName, data)
end
if isStarted(QBInv) then
exports[QBInv]:OpenInventory(source, data.stashName, data) exports[QBInv]:OpenInventory(source, data.stashName, data)
end
if isStarted(PSInv) then
exports[PSInv]:OpenInventory(source, data.stashName, data)
end
if isStarted(RSGInv) then
exports[RSGInv]:OpenInventory(source, data.stashName, data)
end
end) end)
function getStash(stashName) local stashResource = "" function clearStash(stashId)
if type(stashName) ~= "string" then return print("Stash name was not a string %s(%s)", stashName, type(stashName)) end if isStarted(JPRInv) then
local stashItems, items = {}, {} debugPrint("^5Bridge^7: ^2Cleared ^3"..JPRInv.."^2 Stash^7", stashId)
if isStarted(OXInv) then stashResource = OXInv if QBInvNew then
stashItems = exports[OXInv]:Inventory(stashName).items exports[JPRInv]:ClearStash(stashId)
else
MySQL.Async.insert('INSERT INTO stashitems (stash, items) VALUES (:stash, :items) ON DUPLICATE KEY UPDATE items = :items', {
['stash'] = stashId,
['items'] = json.encode({})
})
end
elseif isStarted(QSInv) then stashResource = QSInv elseif isStarted(QBInv) then
debugPrint("^5Bridge^7: ^2Cleared ^3"..QBInv.."^2 Stash^7", stashId)
if QBInvNew then
exports[QBInv]:ClearStash(stashId)
else
MySQL.Async.insert('INSERT INTO stashitems (stash, items) VALUES (:stash, :items) ON DUPLICATE KEY UPDATE items = :items', {
['stash'] = stashId,
['items'] = json.encode({})
})
end
elseif isStarted(OXInv) then
debugPrint("^5Bridge^7: ^2Cleared ^3"..OXInv.."^2 Stash^7", stashId)
exports[OXInv]:ClearInventory(stashId)
elseif isStarted(PSInv) then
debugPrint("^5Bridge^7: ^2Cleared ^3"..PSInv.."^2 Stash^7", stashId)
if QBInvNew then
exports[PSInv]:ClearStash(stashId)
else
MySQL.Async.insert('INSERT INTO stashitems (stash, items) VALUES (:stash, :items) ON DUPLICATE KEY UPDATE items = :items', {
['stash'] = stashId,
['items'] = json.encode({})
})
end
elseif isStarted(QSInv) then
debugPrint("^5Bridge^7: ^2Cleared ^3"..QSInv.."^2 Stash^7", stashId)
exports[QSInv]:ClearOtherInventory('stash', stashId)
elseif isStarted(CoreInv) then
debugPrint("^5Bridge^7: ^2Cleared ^3"..CoreInv.."^2 Stash^7", stashId)
exports[CoreInv]:clearInventory("stash-"..stashId)
elseif isStarted(CodeMInv) then
debugPrint("^5Bridge^7: ^2Cleared ^3"..CodeMInv.."^2 Stash^7", stashId)
exports[CodeMInv]:ClearInventory(stashId)
elseif isStarted(OrigenInv) then
debugPrint("^5Bridge^7: ^2Cleared ^3"..OrigenInv.."^2 Stash^7", stashId)
exports[OrigenInv]:ClearInventory(stashId)
elseif isStarted(TgiannInv) then
debugPrint("^5Bridge^7: ^2Cleared ^3"..TgiannInv.."^2 Stash^7", stashId)
exports["tgiann-inventory"]:DeleteInventory("stash", stashId)
elseif isStarted(RSGInv) then
debugPrint("^5Bridge^7: ^2Cleared ^3"..RSGInv.."^2 Stash^7", stashId)
exports[RSGInv]:ClearStash(stashId)
end
end
-------------------------------------------------------------
-- Stash Retrieval Function
-------------------------------------------------------------
--- Retrieves stash items from the active inventory system.
---
--- This function converts the raw stash items into a standardized table using the global Items lookup.
---
--- @param stashName string The identifier for the stash.
--- @return stashTable table A table of items from the stash.
---
--- @usage
--- ```lua
--- local items = getStash("playerStash")
--- ```
function getStash(stashName)
local stashResource = ""
if type(stashName) ~= "string" then
print("^6Bridge^7: ^2Stash name was not a string ^3"..stashName.."^7(^3"..type(stashName).."^7)")
return {}
end
local stashItems, items = {}, {}
if isStarted(OXInv) then
stashResource = OXInv
local stash = exports[OXInv]:Inventory(stashName)
-- Add fallback if ox can't find the stash and returns a boolean
stashItems = type(stash) == "table" and stash.items or {}
elseif isStarted(QSInv) then
stashResource = QSInv
stashItems = exports[QSInv]:GetStashItems(stashName) stashItems = exports[QSInv]:GetStashItems(stashName)
elseif isStarted(CoreInv) then stashResource = CoreInv elseif isStarted(CoreInv) then
stashResource = CoreInv
stashItems = exports[CoreInv]:getInventory(stashName) stashItems = exports[CoreInv]:getInventory(stashName)
elseif isStarted(CodeMInv) then stashResource = CodeMInv elseif isStarted(CodeMInv) then
stashItems = exports[CodeMInv]:GetInventoryItems('Stash', stashName) stashResource = CodeMInv
stashItems = exports[CodeMInv]:GetStashItems(stashName)
elseif isStarted(OrigenInv) then stashResource = OrigenInv elseif isStarted(OrigenInv) then
stashItems = exports[OrigenInv]:GetStashItems(stashName) stashResource = OrigenInv
stashItems = exports[OrigenInv]:getInventory(stashName)
elseif isStarted(PSInv) then stashResource = PSInv elseif isStarted(TgiannInv) then
stashResource = TgiannInv
stashItems = exports[TgiannInv]:GetSecondaryInventoryItems("stash", stashName)
elseif isStarted(PSInv) then
stashResource = PSInv
local result = MySQL.scalar.await('SELECT items FROM stashitems WHERE stash = ?', { stashName }) local result = MySQL.scalar.await('SELECT items FROM stashitems WHERE stash = ?', { stashName })
if result then stashItems = json.decode(result) end if result then stashItems = json.decode(result) end
elseif isStarted(QBInv) then stashResource = QBInv
local result = MySQL.scalar.await("SELECT items FROM "..(QBInvNew and "inventories" or "stashitem").." WHERE identifier = ?", { stashName }) elseif isStarted(JPRInv) then
stashResource = JPRInv
local result = MySQL.scalar.await('SELECT items FROM stashitems WHERE stash = ?', { stashName })
if result then stashItems = json.decode(result) end if result then stashItems = json.decode(result) end
elseif isStarted(QBInv) then
stashResource = QBInv
if QBInvNew then
local result = exports[QBInv]:GetInventory(stashName) or {}
stashItems = result.items or {}
else
local result = MySQL.scalar.await("SELECT items FROM stashitems WHERE stash = ?", { stashName })
if result then stashItems = json.decode(result) end
end
elseif isStarted(RSGInv) then
stashResource = RSGInv
stashItems = exports[RSGInv]:GetInventory(stashName)
end end
debugPrint("^6Bridge^7: ^2Retrieving ^3Stash^2 with ^7"..stashResource) debugPrint("^6Bridge^7: ^2Retrieving ^3Stash^2 with ^7"..stashResource)
@@ -105,8 +388,8 @@ function getStash(stashName) local stashResource = ""
for _, item in pairs(stashItems) do for _, item in pairs(stashItems) do
local itemInfo = Items[item.name:lower()] local itemInfo = Items[item.name:lower()]
if itemInfo then if itemInfo then
local indexNum = #items+1 -- Added to help recreate missing slot numbers local indexNum = #items + 1 -- Fallback index if slot is missing.
items[(item.slot and item.slot) or indexNum] = { items[(item.slot or indexNum)] = {
name = itemInfo.name or nil, name = itemInfo.name or nil,
amount = tonumber(item.amount) or tonumber(item.count), amount = tonumber(item.amount) or tonumber(item.count),
info = item.info or "", info = item.info or "",
@@ -122,19 +405,35 @@ function getStash(stashName) local stashResource = ""
} }
end end
end end
debugPrint("^6Bridge^7: ^3GetStashItems^7: ^2Stash information for ^7'^6"..stashName.."^7' ^2retrieved^7") debugPrint("^6Bridge^7: ^3GetStashItems^7: ^2Stash information for '^6"..stashName.."^7' retrieved")
end end
jsonPrint(items)
return items return items
end end
function stashRemoveItem(stashItems, stashName, items) local amount = amount and amount or 1 -------------------------------------------------------------
-- print("stashItems: "..json.encode(stashItems, { indent = true})) -- Stash Item Removal Function
-- print("stashName: "..json.encode(stashName, { indent = true})) -------------------------------------------------------------
-- print("items: "..json.encode(items, { indent = true}))
--- Removes items from a stash using the active inventory system.
---
--- Iterates over the provided items and adjusts the stash contents accordingly.
---
--- @param stashItems table The current stash items.
--- @param stashName string|table The stash identifier (or table of identifiers).
--- @param items table A table of items to remove (keys are item names, values are amounts).
---
--- @usage
--- ```lua
--- stashRemoveItem(currentItems, "playerStash", { iron = 2, wood = 5 })
--- ```
function stashRemoveItem(stashItems, stashName, items)
if type(stashName) ~= "table" then
stashName = { stashName }
end
if isStarted(OXInv) then if isStarted(OXInv) then
for k, v in pairs(items) do for k, v in pairs(items) do
debugPrint("^6Bridge^7: ^2Removing item from ^3Stash^2 with ^7"..OXInv, k, v)
if type(stashName) == "table" then
for _, name in pairs(stashName) do for _, name in pairs(stashName) do
local success = exports[OXInv]:RemoveItem(name, k, v) local success = exports[OXInv]:RemoveItem(name, k, v)
if success then if success then
@@ -142,29 +441,17 @@ function stashRemoveItem(stashItems, stashName, items) local amount = amount and
break break
end end
end end
else
exports[OXInv]:RemoveItem(stashName, k, v)
end
end end
elseif isStarted(QSInv) then elseif isStarted(QSInv) then
for k, v in pairs(items) do for k, v in pairs(items) do
for l in pairs(stashItems) do exports[QSInv]:RemoveItemIntoStash(stashName[1], k, v)
if stashItems[l].name == k then debugPrint("^6Bridge^7: ^2Removing item from ^3Stash^2 with ^7"..QSInv, k, v)
if (stashItems[l].amount - v) <= 0 then
debugPrint("^6Bridge^7: ^2None of this item left in stash ^3Stash^7", k, v)
stashItems[l] = nil
else
debugPrint("^6Bridge^7: ^2Removing item from ^3Stash^2 with ^7"..QBInv, k, v)
exports[QSInv]:RemoveItemIntoStash(stashName, k, v, l)
end
end
end
end end
elseif isStarted(CoreInv) then elseif isStarted(CoreInv) then
for k, v in pairs(items) do for k, v in pairs(items) do
exports[CoreInv]:removeItemExact(stashName, k, v) exports[CoreInv]:removeItemExact(stashName[1], k, v)
debugPrint("^6Bridge^7: ^2Removing item from ^3Stash^2 with ^7"..CoreInv, k, v) debugPrint("^6Bridge^7: ^2Removing item from ^3Stash^2 with ^7"..CoreInv, k, v)
end end
@@ -182,15 +469,26 @@ function stashRemoveItem(stashItems, stashName, items) local amount = amount and
end end
end end
end end
debugPrint("^6Bridge^7: ^3saveStash^7: ^2Saving ^3QB^2 stash ^7'^6"..stashName.."^7'") exports[CodeMInv]:UpdateStash(stashName[1], stashItems)
debugPrint("^6Bridge^7: ^3saveStash^7: ^2Saving ^3CodeM^2 stash ^7'^6"..stashName.."^7'")
elseif isStarted(OrigenInv) then elseif isStarted(OrigenInv) then
for k, v in pairs(items) do for k, v in pairs(items) do
exports[OrigenInv]:RemoveFromStash(stashName, k, v) exports[OrigenInv]:RemoveFromStash(stashName[1], k, v)
debugPrint("^6Bridge^7: ^2Removing item from ^3Stash^2 with ^7"..OrigenInv, k, v) debugPrint("^6Bridge^7: ^2Removing item from ^3Stash^2 with ^7"..OrigenInv, k, v)
end end
elseif isStarted(PSInv) then elseif isStarted(TgiannInv) then
for k, v in pairs(items) do
local itemData = exports[TgiannInv]:GetItemByNameFromSecondaryInventory("stash", stashName[1], k)
exports[TgiannInv]:RemoveItemFromSecondaryInventory("stash", stashName[1], k, v, itemData.slot, nil)
debugPrint("^6Bridge^7: ^2Removing item from ^3Stash^2 with ^7"..TgiannInv, k, v)
end
elseif isStarted(JPRInv) then
if not stashItems or not next(stashItems) then
stashItems = getStash(stashName[1])
end
for k, v in pairs(items) do for k, v in pairs(items) do
for l in pairs(stashItems) do for l in pairs(stashItems) do
if stashItems[l].name == k then if stashItems[l].name == k then
@@ -198,51 +496,101 @@ function stashRemoveItem(stashItems, stashName, items) local amount = amount and
debugPrint("^6Bridge^7: ^2None of this item left in stash ^3Stash^7", k, v) debugPrint("^6Bridge^7: ^2None of this item left in stash ^3Stash^7", k, v)
stashItems[l] = nil stashItems[l] = nil
else else
debugPrint("^6Bridge^7: ^2Removing item from ^3Stash^2 with ^7"..QBInv, k, v) debugPrint("^6Bridge^7: ^2Removing item from ^3Stash^2 with "..JPRInv, k, v)
stashItems[l].amount -= v stashItems[l].amount -= v
end end
end end
end end
end end
debugPrint("^6Bridge^7: ^3saveStash^7: ^2Saving ^3QB^2 stash ^7'^6"..stashName.."^7'") debugPrint("^6Bridge^7: ^3saveStash^7: ^2Saving ^3JPR^2 stash '^6"..stashName[1].."^7'")
MySQL.Async.insert('INSERT INTO stashitems (stash, items) VALUES (:stash, :items) ON DUPLICATE KEY UPDATE items = :items', { ['stash'] = stashName, ['items'] = json.encode(stashItems) }) MySQL.Async.insert('INSERT INTO stashitems (stash, items) VALUES (:stash, :items) ON DUPLICATE KEY UPDATE items = :items', {
['stash'] = stashName[1],
['items'] = json.encode(stashItems)
})
elseif isStarted(QBInv) then elseif isStarted(QBInv) then
if QBInvNew then if QBInvNew then
for k, v in pairs(items) do for k, v in pairs(items) do
exports[QBInv]:RemoveItem(stashName[1], k, v, false, 'crafting') exports[QBInv]:RemoveItem(stashName[1], k, v, false, 'crafting')
debugPrint("^6Bridge^7: ^2Removing item from ^3Stash^2 with ^7"..QBInv, k, v) debugPrint("^6Bridge^7: ^2Removing item from ^3Stash^2 with ^7"..QBInv, k, v)
end end
debugPrint("^6Bridge^7: ^3saveStash^7: ^2Saving ^3QB^2 stash ^7'^6"..stashName[1].."^7'")
MySQL.Async.insert('INSERT INTO inventories (identifier, items) VALUES (:stash, :items) ON DUPLICATE KEY UPDATE items = :items', { ['stash'] = stashName[1], ['items'] = json.encode(stashItems) })
else else
if not stashItems or not next(stashItems) then
stashItems = getStash(stashName[1])
end
for k, v in pairs(items) do for k, v in pairs(items) do
for l in pairs(stashItems) do for l in pairs(stashItems) do
if stashItems[l].name == k then if stashItems[l].name == k then
if (stashItems[l].amount - v) <= 0 then if (stashItems[l].amount - v) <= 0 then
if Config.System.Debug then debugPrint("^6Bridge^7: ^2None of this item left in stash ^3Stash^7", k, v)
print("^6Bridge^7: ^2None of this item left in stash ^3Stash^7", k, v)
end
stashItems[l] = nil stashItems[l] = nil
else else
if Config.System.Debug then debugPrint("^6Bridge^7: ^2Removing item from ^3Stash^2 with "..QBInv, k, v)
print("^6Bridge^7: ^2Removing item from ^3Stash^2 with ^7"..QBInv, k, v)
end
stashItems[l].amount -= v stashItems[l].amount -= v
end end
end end
end end
end end
debugPrint("^6Bridge^7: ^3saveStash^7: ^2Saving ^3QB^2 stash ^7'^6"..stashName.."^7'") debugPrint("^6Bridge^7: ^3saveStash^7: ^2Saving ^3QB^2 stash '^6"..stashName[1].."^7'")
MySQL.Async.insert('INSERT INTO stashitems (stash, items) VALUES (:stash, :items) ON DUPLICATE KEY UPDATE items = :items', { ['stash'] = stashName, ['items'] = json.encode(stashItems) }) MySQL.Async.insert('INSERT INTO stashitems (stash, items) VALUES (:stash, :items) ON DUPLICATE KEY UPDATE items = :items', {
['stash'] = stashName[1],
['items'] = json.encode(stashItems)
})
end
elseif isStarted(PSInv) then
if not stashItems or not next(stashItems) then
stashItems = getStash(stashName[1])
end
for k, v in pairs(items) do
for l in pairs(stashItems) do
if stashItems[l].name == k then
if (stashItems[l].amount - v) <= 0 then
debugPrint("^6Bridge^7: ^2None of this item left in stash ^3Stash^7", k, v)
stashItems[l] = nil
else
debugPrint("^6Bridge^7: ^2Removing item from ^3Stash^2 with ^7"..PSInv, k, v)
stashItems[l].amount -= v
end
end
end
end
debugPrint("^6Bridge^7: ^3saveStash^7: ^2Saving ^3PS^2 stash ^7'^6"..stashName[1].."^7'")
MySQL.Async.insert('INSERT INTO stashitems (stash, items) VALUES (:stash, :items) ON DUPLICATE KEY UPDATE items = :items', {
['stash'] = stashName[1],
['items'] = json.encode(stashItems)
})
elseif isStarted(RSGInv) then
for k, v in pairs(items) do
exports[RSGInv]:RemoveItem(stashName[1], k, v, false, 'crafting')
debugPrint("^6Bridge^7: ^2Removing item from ^3Stash^2 with ^7"..RSGInv, k, v)
end end
else else
print("^4ERROR^7: ^2No Inventory detected ^7- ^2Check ^3exports^1.^2lua^7") print("^4ERROR^7: ^2No Inventory detected ^7- ^2Check ^3starter^1.^2lua^7")
end end
end end
RegisterNetEvent(getScript()..":server:stashRemoveItem", stashRemoveItem) RegisterNetEvent(getScript()..":server:stashRemoveItem", stashRemoveItem)
-------------------------------------------------------------
-- Stash Item Availability Check
-------------------------------------------------------------
--- Checks whether a stash has the required amount of specific items.
---
--- It iterates through the provided items and tallies available quantities.
---
--- @param stashItems table The items available in the stash.
--- @param items string|table The item name or table of required items (key: item, value: amount).
--- @param amount number (Optional) The required amount (if a single item is provided).
--- @return boolean, table (`boolean, string`) Returns true (and a table with counts) if all items are available; false otherwise.
---
--- @usage
--- ```lua
--- local hasAll, details = stashhasItem(currentStashItems, { iron = 2, wood = 5 })
--- ```
function stashhasItem(stashItems, items, amount) function stashhasItem(stashItems, items, amount)
local invs = {OXInv, QSInv, CoreInv, CodeMInv, OrigenInv, QBInv, PSInv} local invs = { OXInv, QSInv, CoreInv, CodeMInv, OrigenInv, TgiannInv, JPRInv, QBInv, PSInv, RSGInv }
local foundInv = "" local foundInv = ""
for _, inv in ipairs(invs) do for _, inv in ipairs(invs) do
if isStarted(inv) then if isStarted(inv) then
@@ -251,9 +599,11 @@ function stashhasItem(stashItems, items, amount)
end end
end end
-- Ensure items is a table.
if type(items) ~= "table" then items = { [items] = amount and amount or 1, } end if type(items) ~= "table" then items = { [items] = amount and amount or 1, } end
local hasTable = {} local hasTable = {}
for item, amount in pairs(items) do for item, requiredAmount in pairs(items) do
local count = 0 local count = 0
for _, itemData in pairs(stashItems) do for _, itemData in pairs(stashItems) do
if itemData and (itemData.name == item) then if itemData and (itemData.name == item) then
@@ -261,11 +611,100 @@ function stashhasItem(stashItems, items, amount)
end end
end end
local debugMsg = string.format("^6Bridge^7: ^3stashHasItem^7[^6%s^7]: %s '%s' ^3%d^7/^3%d^7", foundInv, (count >= amount and "^5FOUND^7" or "^1NOT FOUND^7"), item, count, amount) local debugMsg = string.format("^6Bridge^7: ^3stashHasItem^7[^6%s^7]: %s '%s' ^3%d^7/^3%d^7", foundInv, (count >= requiredAmount and "^5FOUND^7" or "^1NOT FOUND^7"), item, count, requiredAmount)
debugPrint(debugMsg) debugPrint(debugMsg)
hasTable[item] = { hasItem = (count >= amount), count = count } hasTable[item] = { hasItem = (count >= requiredAmount), count = count }
end end
for k, v in pairs(hasTable) do if v.hasItem == false then return false, hasTable end end for k, v in pairs(hasTable) do if v.hasItem == false then return false, hasTable end end
return true, hasTable return true, hasTable
end end
--- Registers a stash with the active inventory system.
--- Supports either OXInv or QSInv.
---
--- @param name string Unique stash identifier.
--- @param label string Display name for the stash.
--- @param slots number|nil (Optional) Number of slots (default 50).
--- @param weight number|nil (Optional) Maximum weight (default 4000000).
--- @param owner string|nil (Optional) Owner identifier for personal stashes.
--- @param coords table|nil (Optional) Coordinates for the stash location.
--- @usage
--- ```lua
--- registerStash(
--- "playerStash",
--- "Player Stash",
--- 100,
--- 8000000,
--- "player123",
--- { x = 100.0, y = 200.0, z = 30.0 }
--- )
--- ```
function registerStash(name, label, slots, weight, owner, coords)
if isStarted(OXInv) then
debugPrint("^6Bridge^7: ^2Registering ^3OX ^2Stash^7:", name, label, owner or nil)
exports[OXInv]:RegisterStash(name, label, slots or 50, weight or 4000000, owner or nil)
--elseif isStarted(QSInv) then
-- debugPrint("^6Bridge^7: ^2Registering ^3QS ^2Stash^7:", name, label)
-- exports[QSInv]:RegisterStash(name, label, slots or 50, weight or 4000000)
--elseif isStarted(CoreInv) then
-- debugPrint("^6Bridge^7: ^2Registering ^3CoreInv ^2Stash^7:", name, label)
-- exports[CoreInv]:openHolder(nil, name, 'stash', nil, nil, false, nil)
elseif isStarted(OrigenInv) then
debugPrint("^6Bridge^7: ^2Registering ^3OrigenInv ^2Stash^7:", name, label)
exports["origen_inventory"]:registerStash(name, label, slots or 50, weight or 4000000)
elseif isStarted(TgiannInv) then
debugPrint("^6Bridge^7: ^2Registering ^3TgiannInv ^2Stash^7:", name, label)
exports[TgiannInv]:RegisterStash(name, label, slots or 50, weight or 4000000)
end
end
if isServer() then
--- Registers an event to create an OX stash from the server.
--- When triggered, it calls registerStash with the provided parameters.
---
--- @event server:makeOXStash
--- @param name string Unique stash identifier.
--- @param label string Display name for the stash.
--- @param slots number|nil (Optional) Number of slots.
--- @param weight number|nil (Optional) Maximum weight.
--- @param owner string|nil (Optional) Owner identifier.
--- @param coords table|nil (Optional) Stash coordinates.
--- @usage
--- ```lua
--- TriggerEvent(getScript()..":server:makeOXStash", name, label, slots, weight, owner, coords, token)
--- ```
RegisterNetEvent(getScript()..":server:makeOXStash", function(name, label, slots, weight, owner, coords, token)
local src = source or nil
if src then
if not checkToken(src, token, "stash", name) then
return
end
end
registerStash(name, label, slots, weight, owner, coords)
end)
end
RegisterNetEvent(getScript()..":openGrabBox", function(data)
if isStarted(OXInv) then
return
end
local id = ""
if data.metadata then
id = data.metadata.id
elseif data.info then
id = data.info.id
end
openStash({
stash = id,
})
end)

View File

@@ -1,185 +1,167 @@
-- This is for experimental targets based on GTA in-world text prompts -- --[[
local TextTargets = {} Experimental GTA In-World Text Prompts Targets Module
local Keys = { -------------------------------------------------------
[322] = "ESC", [288] = "F1", [289] = "F2", [170] = "F3", [166] = "F5", This module handles the creation, removal, and management of in-world text targets
[167] = "F6", [168] = "F7", [169] = "F8", [56] = "F9", [57] = "F10", for interacting with entities and zones using GTA text prompts. It supports multiple
[243] = "~", [157] = "1", [158] = "2", [160] = "3", [164] = "4", [165] = "5", targeting systems: OX Target, QB Target, or a fallback using DrawText3D.
[159] = "6", [161] = "7", [162] = "8", [163] = "9", [84] = "-", [83] = "=",
[177] = "BACKSPACE", [37] = "TAB",
[44] = "Q", [32] = "W", [38] = "E", [45] = "R", [245] = "T", [246] = "Y",
[303] = "U", [199] = "P",
[39] = "[", [40] = "]", [18] = "ENTER", [137] = "CAPS",
[34] = "A", [8] = "S", [9] = "D", [23] = "F", [47] = "G",
[74] = "H", [311] = "K", [182] = "L", [21] = "LEFTSHIFT",
[20] = "Z", [73] = "X", [26] = "C", [0] = "V", [29] = "B", [249] = "N",
[244] = "M", [82] = ",", [81] = "."
}
-- Target Creation -- Available functionalities:
-- Target Entities, this is more based on qb-target's style of target creation, and translates those into ox or qb-target code -- • createEntityTarget - Creates a target for a specific entity.
local targetEntities = {} • createBoxTarget - Creates a box-shaped zone target.
• createCircleTarget - Creates a circular zone target.
• createModelTarget - Creates a target for specified models.
• removeEntityTarget - Removes a target from an entity.
• removeZoneTarget - Removes a zone target.
Fallback: If no targeting system is detected (or if disabled via Config.System.DontUseTarget),
the module uses DrawText3D prompts. This is experimental and may not work as expected.
]]
-------------------------------------------------------------
-- Utility Data & Tables
-------------------------------------------------------------
-- Tables for storing created targets for the fallback system and zone management.
local TextTargets = {} -- For fallback DrawText3D targets.
local targetEntities = {} -- For entity targets.
local boxTargets = {} -- For box-shaped zone targets.
local circleTargets = {} -- For circular zone targets.
-------------------------------------------------------------
-- Entity Target Creation
-------------------------------------------------------------
--- Creates a target for an entity with specified options and interaction distance. --- Creates a target for an entity with specified options and interaction distance.
--- Supports different targeting systems (OX Target, QB Target, or custom DrawText3D)
--- based on the server configuration.
--- ---
--- This function supports different targeting systems (OX Target, QB Target, or custom DrawText3D targets) --- @param entity number The entity ID for which the target is created.
--- based on the server configuration. It translates qb-target style options into the appropriate format --- @param opts table Array of option tables. Each option should include:
--- for the detected targeting system. --- - icon (string): The icon to display.
--- --- - label (string): The text label for the option.
---@param entity number The entity ID to create a target for. --- - item (string|nil): (Optional) An associated item.
---@param opts table A table of option configurations for the target. --- - job (string|nil): (Optional) The job required to interact.
--- - **icon** (`string`): The icon to display for the option. --- - gang (string|nil): (Optional) The gang required to interact.
--- - **label** (`string`): The label text for the option. --- - action (function|nil): (Optional) The function executed on selection.
--- - **item** (`string|nil`): (Optional) The item associated with the option.
--- - **job** (`string|nil`): (Optional) The job required to interact with the option.
--- - **gang** (`string|nil`): (Optional) The gang required to interact with the option.
--- - **action** (`function|nil`): (Optional) The function to execute when the option is selected.
--- @param dist number The interaction distance for the target. --- @param dist number The interaction distance for the target.
--- ---
--- @usage --- @usage
--- ```lua --- ```lua
---createEntityTarget(entityId, { ---createEntityTarget(entityId, {
--- { icon = "fas fa-car", label = "Open Vehicle", action = openVehicle }, --- {
--- { icon = "fas fa-lock", label = "Lock Vehicle", action = lockVehicle } --- action = function()
--- }, 2.5) --- openStorage()
--- end,
--- icon = "fas fa-box",
--- job = "police",
--- label = "Open Storage",
--- },
---}, 2.0)
--- ``` --- ```
function createEntityTarget(entity, opts, dist) function createEntityTarget(entity, opts, dist)
-- Store the target entity for later cleanup.
targetEntities[#targetEntities + 1] = entity targetEntities[#targetEntities + 1] = entity
local entityCoords = GetEntityCoords(entity)
if Config.System.DontUseTarget then
debugPrint("^6Bridge^7: ^2Creating new ^3Entity^2 target with ^6DrawText ^7"..entity)
local existingTarget = nil
for key, target in pairs(TextTargets) do
if #(target.coords - entityCoords) < 0.01 then -- Adjust the threshold for coordinate matching
existingTarget = target
break
end
end
if existingTarget then -- Fallback: Use DrawText3D if targeting systems are disabled or unavailable.
-- Combine options if Config.System.DontUseTarget or (not isStarted(OXTargetExport) and not isStarted(QBTargetExport)) then
local keyTable = { 38, 29, 303, 45, 46, 47, 48 } -- Extend key table as needed debugPrint("^6Bridge^7: ^2Creating new ^3Entity ^2target with ^6"..OXTargetExport.." ^2for entity ^7"..entity)
for i = 1, #opts do exports.jim_bridge:createEntityTarget(entity, opts, dist)
local key = keyTable[#existingTarget.options + i]
opts[i].key = key
existingTarget.buttontext[#existingTarget.buttontext + 1] = " ~b~[~w~"..Keys[key].."~b~] ~w~"..opts[i].label
existingTarget.options[#existingTarget.options + 1] = opts[i]
end
else
-- Create new target
local tempText = {}
local keyTable = { 38, 29, 303, 45, 46, 47, 48 }
for i = 1, #opts do
opts[i].key = keyTable[i]
tempText[#tempText + 1] = " ~b~[~w~"..Keys[opts[i].key].."~b~] ~w~"..opts[i].label
end
TextTargets[entity] = { coords = vec3(entityCoords.x, entityCoords.y, entityCoords.z), buttontext = tempText, options = opts, dist = dist }
end
elseif isStarted(OXTargetExport) then elseif isStarted(OXTargetExport) then
debugPrint("^6Bridge^7: ^2Creating new ^3Entity^2 target with ^6"..OXTargetExport.." ^7"..entity) debugPrint("^6Bridge^7: ^2Creating new ^3Entity ^2target with ^6"..OXTargetExport.." ^2for entity ^7"..entity)
local options = {} local options = {}
for i = 1, #opts do for i = 1, #opts do
options[i] = { options[i] = {
icon = opts[i].icon, icon = opts[i].icon,
label = opts[i].label, label = opts[i].label,
item = opts[i].item or nil, items = opts[i].item or nil,
groups = opts[i].job or opts[i].gang, groups = opts[i].job or opts[i].gang,
onSelect = opts[i].action, onSelect = opts[i].action,
canInteract = function(_, distance) distance = dist,
return distance < dist and true or false canInteract = opts[i].canInteract or nil,
end
} }
end end
exports[OXTargetExport]:addLocalEntity(entity, options) exports[OXTargetExport]:addLocalEntity(entity, options)
elseif isStarted(QBTargetExport) then elseif isStarted(QBTargetExport) then
debugPrint("^6Bridge^7: ^2Creating new ^3Entity^2 target with ^6"..QBTargetExport.." ^7"..entity) debugPrint("^6Bridge^7: ^2Creating new ^3Entity ^2target with ^6"..QBTargetExport.." ^2for entity ^7"..entity)
local options = { options = opts, distance = dist } local options = { options = opts, distance = dist }
exports[QBTargetExport]:AddTargetEntity(entity, options) exports[QBTargetExport]:AddTargetEntity(entity, options)
end end
end end
local boxTargets = {} -------------------------------------------------------------
-- Box Zone Target Creation
-------------------------------------------------------------
--- Creates a box-shaped target zone with specified options and interaction distance. --- Creates a box-shaped target zone with specified options and interaction distance.
--- --- Supports different targeting systems based on the server configuration.
--- This function supports different targeting systems (OX Target, QB Target, or custom DrawText3D targets)
--- based on the server configuration. It translates qb-target style options into the appropriate format
--- for the detected targeting system.
---
---@param data table A table containing the box zone configuration. ---@param data table A table containing the box zone configuration.
--- - **name** (`string`): The name identifier for the zone. --- - name (`string`): The name identifier for the zone.
--- - **coords** (`vector3`): The center coordinates of the box. --- - coords (`vector3`): The center coordinates of the box.
--- - **width** (`number`): The width of the box. --- - width (`number`): The width of the box.
--- - **height** (`number`): The height of the box. --- - height (`number`): The height of the box.
--- - **options** (`table`): A table with additional options: --- - options (`table`): A table with additional options:
--- - **heading** (`number`): The rotation angle of the box. --- - heading (`number`): The rotation angle of the box.
--- - **debugPoly** (`boolean`): Whether to enable debug mode for the zone. --- - debugPoly (`boolean`): Whether to enable debug mode for the zone.
--- ---
---@param opts table A table of option configurations for the target. ---@param opts table A table of option configurations for the target.
--- - **icon** (`string`): The icon to display for the option. --- - icon (`string`): The icon to display for the option.
--- - **label** (`string`): The label text for the option. --- - label (`string`): The label text for the option.
--- - **item** (`string|nil`): (Optional) The item associated with the option. --- - item (`string|nil`): (Optional) The item associated with the option.
--- - **job** (`string|nil`): (Optional) The job required to interact with the option. --- - job (`string|nil`): (Optional) The job required to interact with the option.
--- - **gang** (`string|nil`): (Optional) The gang required to interact with the option. --- - gang (`string|nil`): (Optional) The gang required to interact with the option.
--- - **onSelect** (`function|nil`): (Optional) The function to execute when the option is selected. --- - onSelect (`function|nil`): (Optional) The function to execute when the option is selected.
---@param dist number The interaction distance for the target. ---@param dist number The interaction distance for the target.
--- ---
---@return string|table name identifier or target object of the created zone. ---@return string|table name identifier or target object of the created zone.
--- ---
---@usage ---@usage
---```lua ---```lua
--- createBoxTarget({ ---createBoxTarget(
--- {
--- 'storageBox',
--- vector3(100.0, 200.0, 30.0),
--- 2.0,
--- 2.0,
--- {
--- name = 'storageBox', --- name = 'storageBox',
--- coords = vector3(100.0, 200.0, 30.0), --- heading = 100.0,
--- width = 2.0, --- debugPoly = true,
--- height = 2.0, --- minZ = 27.0,
--- options = { heading = 0, debugPoly = false } --- maxZ = 32.0,
--- }, { --- },
--- { icon = "fas fa-box", label = "Open Storage", action = openStorage } --- },
--- }, 1.5) ---{
--- {
--- action = function()
--- openStorage()
--- end,
--- icon = "fas fa-box",
--- job = "police",
--- label = "Open Storage",
--- },
---}, 2.0)
---``` ---```
function createBoxTarget(data, opts, dist) function createBoxTarget(data, opts, dist)
if Config.System.DontUseTarget then if Config.System.DontUseTarget or (not isStarted(OXTargetExport) and not isStarted(QBTargetExport)) then
debugPrint("^6Bridge^7: ^2Creating new ^3Box^2 target with ^6DrawText ^7"..data[1]) debugPrint("^6Bridge^7: ^2Creating new ^3Box^2 target with ^6DrawText ^2 for zone ^7"..data[1])
local existingTarget = nil return exports.jim_bridge:createZoneTarget(data, opts, dist)
for key, target in pairs(TextTargets) do
if #(target.coords - data[2]) < 0.01 then -- Adjust the threshold as needed for coordinate precision
existingTarget = target
break
end
end
local keyTable = { 38, 29, 303, 45, 46, 47, 48 }
if existingTarget then
-- Combine options
for i = 1, #opts do
local key = keyTable[#existingTarget.options + i]
opts[i].key = key
existingTarget.buttontext[#existingTarget.buttontext+1] = " ~b~[~w~"..Keys[key].."~b~] ~w~"..opts[i].label
existingTarget.options[#existingTarget.options+1] = opts[i]
end
else
-- Create new target
local tempText = {}
for i = 1, #opts do
opts[i].key = keyTable[i]
tempText[#tempText+1] = " ~b~[~w~"..Keys[opts[i].key].."~b~] ~w~"..opts[i].label
end
TextTargets[data[1]] = { coords = data[2], buttontext = tempText, options = opts, dist = 1.5 }
end
return data[1]
elseif isStarted(OXTargetExport) then elseif isStarted(OXTargetExport) then
debugPrint("^6Bridge^7: ^2Creating new ^3Box^2 target with ^6"..OXTargetExport.." ^7"..data[1]) debugPrint("^6Bridge^7: ^2Creating new ^3Box^2 target with ^6"..OXTargetExport.." ^2for zone ^7"..data[1])
local options = {} local options = {}
for i = 1, #opts do for i = 1, #opts do
options[i] = { options[i] = {
icon = opts[i].icon, icon = opts[i].icon,
label = opts[i].label, label = opts[i].label,
item = opts[i].item or nil, items = opts[i].item or nil,
groups = opts[i].job or opts[i].gang, groups = opts[i].job or opts[i].gang,
onSelect = opts[i].onSelect or opts[i].action, onSelect = opts[i].onSelect or opts[i].action,
canInteract = function(_, distance) distance = dist,
return distance < dist and true or false canInteract = opts[i].canInteract or nil,
end
} }
end end
if not data[5].useZ then if not data[5].useZ then
@@ -195,37 +177,38 @@ function createBoxTarget(data, opts, dist)
}) })
boxTargets[#boxTargets + 1] = target boxTargets[#boxTargets + 1] = target
return target return target
elseif isStarted(QBTargetExport) then elseif isStarted(QBTargetExport) then
debugPrint("^6Bridge^7: ^2Creating new ^3Box^2 target with ^6"..QBTargetExport.." ^7"..data[1]) debugPrint("^6Bridge^7: ^2Creating new ^3Box^2 target with ^6"..QBTargetExport.." ^2for zone ^7"..data[1])
local options = { options = opts, distance = dist } local options = { options = opts, distance = dist }
local target = exports[QBTargetExport]:AddBoxZone(data[1], data[2], data[3], data[4], data[5], options) local target = exports[QBTargetExport]:AddBoxZone(data[1], data[2], data[3], data[4], data[5], options)
boxTargets[#boxTargets + 1] = target boxTargets[#boxTargets + 1] = target
return data[1] return data[1]
end end
end end
local circleTargets = {} -------------------------------------------------------------
-- Circle Zone Target Creation
-------------------------------------------------------------
--- Creates a circular target zone with specified options and interaction distance. --- Creates a circular target zone with specified options and interaction distance.
--- --- Supports different targeting systems based on server configuration.
--- This function supports different targeting systems (OX Target, QB Target, or custom DrawText3D targets)
--- based on the server configuration. It translates qb-target style options into the appropriate format
--- for the detected targeting system.
--- ---
---@param data table A table containing the circle zone configuration. ---@param data table A table containing the circle zone configuration.
--- - **name** (`string`): The name identifier for the zone. --- - name (`string`): The name identifier for the zone.
--- - **coords** (`vector3`): The center coordinates of the circle. --- - coords (`vector3`): The center coordinates of the circle.
--- - **radius** (`number`): The radius of the circle. --- - radius (`number`): The radius of the circle.
--- - **options** (`table`): A table with additional options: --- - options (`table`): A table with additional options:
--- - **debugPoly** (`boolean`): Whether to enable debug mode for the zone. --- - debugPoly (`boolean`): Whether to enable debug mode for the zone.
--- ---
---@param opts table A table of option configurations for the target. ---@param opts table A table of option configurations for the target.
--- - **icon** (`string`): The icon to display for the option. --- - icon (`string`): The icon to display for the option.
--- - **label** (`string`): The label text for the option. --- - label (`string`): The label text for the option.
--- - **item** (`string|nil`): (Optional) The item associated with the option. --- - item (`string|nil`): (Optional) The item associated with the option.
--- - **job** (`string|nil`): (Optional) The job required to interact with the option. --- - job (`string|nil`): (Optional) The job required to interact with the option.
--- - **gang** (`string|nil`): (Optional) The gang required to interact with the option. --- - gang (`string|nil`): (Optional) The gang required to interact with the option.
--- - **onSelect** (`function|nil`): (Optional) The function to execute when the option is selected. --- - onSelect (`function|nil`): (Optional) The function to execute when the option is selected.
---@param dist number The interaction distance for the target. ---@param dist number The interaction distance for the target.
--- ---
---@return string|table name identifier or target object of the created zone. ---@return string|table name identifier or target object of the created zone.
@@ -243,48 +226,21 @@ local circleTargets = {}
--- ``` --- ```
function createCircleTarget(data, opts, dist) function createCircleTarget(data, opts, dist)
if Config.System.DontUseTarget then if Config.System.DontUseTarget then
debugPrint("^6Bridge^7: ^2Creating new ^3Circle^2 target with ^6DrawText ^7"..data[1]) debugPrint("^6Bridge^7: ^2Creating new ^3Circle ^2target with ^6DrawText ^2for zone ^7"..data[1])
local existingTarget = nil return exports.jim_bridge:createZoneTarget(data, opts, dist)
for key, target in pairs(TextTargets) do
if #(target.coords - data[2]) < 0.01 then -- Adjust the threshold for precision
existingTarget = target
break
end
end
if existingTarget then
-- Combine options
local keyTable = { 38, 29, 303, 45, 46, 47, 48 } -- Extend key table as needed
for i = 1, #opts do
local key = keyTable[#existingTarget.options + i]
opts[i].key = key
existingTarget.buttontext[#existingTarget.buttontext+1] = " ~b~[~w~"..Keys[key].."~b~] ~w~"..opts[i].label
existingTarget.options[#existingTarget.options+1] = opts[i]
end
else
-- Create new target
local tempText = ""
local keyTable = { 38, 29, 303, 45, 46, 47, 48 }
for i = 1, #opts do
opts[i].key = keyTable[i]
tempText[#tempText+1] = " ~b~[~w~"..Keys[opts[i].key].."~b~] ~w~"..opts[i].label
end
TextTargets[data[1]] = { coords = data[2], buttontext = tempText, options = opts, dist = dist }
end
return data[1]
elseif isStarted(OXTargetExport) then elseif isStarted(OXTargetExport) then
debugPrint("^6Bridge^7: ^2Creating new ^3Sphere^2 target with ^6"..OXTargetExport.." ^7"..data[1]) debugPrint("^6Bridge^7: ^2Creating new ^3Circle ^2target with ^6"..OXTargetExport.." ^2for zone ^7"..data[1])
local options = {} local options = {}
for i = 1, #opts do for i = 1, #opts do
options[i] = { options[i] = {
icon = opts[i].icon, icon = opts[i].icon,
label = opts[i].label, label = opts[i].label,
item = opts[i].item or nil, items = opts[i].item or nil,
groups = opts[i].job or opts[i].gang, groups = opts[i].job or opts[i].gang,
onSelect = opts[i].onSelect or opts[i].action, onSelect = opts[i].onSelect or opts[i].action,
canInteract = function(_, distance) distance = dist,
return distance < dist and true or false canInteract = opts[i].canInteract or nil,
end
} }
end end
local target = exports[OXTargetExport]:addSphereZone({ local target = exports[OXTargetExport]:addSphereZone({
@@ -296,7 +252,7 @@ function createCircleTarget(data, opts, dist)
circleTargets[#circleTargets + 1] = target circleTargets[#circleTargets + 1] = target
return target return target
elseif isStarted(QBTargetExport) then elseif isStarted(QBTargetExport) then
debugPrint("^6Bridge^7: ^2Creating new ^3Circle^2 target with ^6"..QBTargetExport.." ^7"..data[1]) debugPrint("^6Bridge^7: ^2Creating new ^3Circle ^2target with ^6"..QBTargetExport.." ^2for zone ^7"..data[1])
local options = { options = opts, distance = dist } local options = { options = opts, distance = dist }
local target = exports[QBTargetExport]:AddCircleZone(data[1], data[2], data[3], data[4], options) local target = exports[QBTargetExport]:AddCircleZone(data[1], data[2], data[3], data[4], options)
circleTargets[#circleTargets + 1] = target circleTargets[#circleTargets + 1] = target
@@ -304,26 +260,83 @@ function createCircleTarget(data, opts, dist)
end end
end end
-- Simple function to remove an entity target created within the script -- -------------------------------------------------------------
--- Removes a previously created entity target. -- Model Target Creation
-------------------------------------------------------------
--- Creates a target for models with specified options and interaction distance.
--- Supports different targeting systems (OX Target, QB Target) based on server configuration.
--- ---
--- This function removes the target associated with the specified entity based on the active targeting system. --- @param models table Array of model identifiers.
--- @param opts table Array of option tables (same structure as in createEntityTarget).
--- @param dist number The interaction distance for the target.
---
--- @usage
--- ```lua
---createModelTarget({ model1, model2 },
---{
--- {
--- action = function()
--- openStorage()
--- end,
--- icon = "fas fa-box",
--- job = "police",
--- label = "Open Storage",
--- },
---}, 2.0)
---```
function createModelTarget(models, opts, dist)
if Config.System.DontUseTarget or (not isStarted(OXTargetExport) and not isStarted(QBTargetExport)) then
return exports.jim_bridge:createModelTarget(models, opts, dist)
elseif isStarted(OXTargetExport) then
debugPrint("^6Bridge^7: ^2Creating new ^3Model^2 target with ^6"..OXTargetExport)
local options = {}
for i = 1, #opts do
options[i] = {
icon = opts[i].icon,
label = opts[i].label,
items = opts[i].item or nil,
groups = opts[i].job or opts[i].gang,
onSelect = opts[i].action,
distance = dist,
canInteract = opts[i].canInteract or nil,
}
end
exports[OXTargetExport]:addModel(models, options)
elseif isStarted(QBTargetExport) then
debugPrint("^6Bridge^7: ^2Creating new ^3Model^2 target with ^6"..QBTargetExport)
local options = { options = opts, distance = dist }
exports[QBTargetExport]:AddTargetModel(models, options)
end
end
-------------------------------------------------------------
-- Target Removal Functions
-------------------------------------------------------------
--- Removes a previously created entity target.
--- ---
--- @param entity number The entity ID whose target should be removed. --- @param entity number The entity ID whose target should be removed.
--- ---
--- @usage --- @usage
--- ```lua
--- removeEntityTarget(entityId) --- removeEntityTarget(entityId)
--- ```
function removeEntityTarget(entity) function removeEntityTarget(entity)
if isStarted(QBTargetExport) then exports[QBTargetExport]:RemoveTargetEntity(entity) end if isStarted(QBTargetExport) then
if isStarted(OXTargetExport) then exports[OXTargetExport]:removeLocalEntity(entity, nil) end exports[QBTargetExport]:RemoveTargetEntity(entity)
if Config.System.DontUseTarget then TextTargets[entity] = nil end end
if isStarted(OXTargetExport) then
exports[OXTargetExport]:removeLocalEntity(entity, nil)
end
if Config.System.DontUseTarget or (not isStarted(OXTargetExport) and not isStarted(QBTargetExport)) then
exports.jim_bridge:removeEntityTarget(entity)
end
end end
-- Simple function to remove circle or box targets in the script --
--- Removes a previously created zone target. --- Removes a previously created zone target.
--- ---
--- This function removes the target associated with the specified zone based on the active targeting system.
---
--- @param target string|table The name identifier or target object of the zone to remove. --- @param target string|table The name identifier or target object of the zone to remove.
--- ---
--- @usage --- @usage
@@ -332,73 +345,182 @@ end
--- removeZoneTarget(targetObject) --- removeZoneTarget(targetObject)
--- ``` --- ```
function removeZoneTarget(target) function removeZoneTarget(target)
if isStarted(QBTargetExport) then exports[QBTargetExport]:RemoveZone(target) end if isStarted(QBTargetExport) then
if isStarted(OXTargetExport) then exports[OXTargetExport]:removeZone(target, true) end exports[QBTargetExport]:RemoveZone(target)
if Config.System.DontUseTarget then TextTargets[target] = nil end end
if isStarted(OXTargetExport) then
exports[OXTargetExport]:removeZone(target, true)
end
if Config.System.DontUseTarget or (not isStarted(OXTargetExport) and not isStarted(QBTargetExport)) then
exports.jim_bridge:removeZoneTarget(target)
end
end end
-- If no target script is found, default to DrawText3D targets -- * experimental * --- Removes a previously created model target.
if Config.System.DontUseTarget and not isServer() then ---
--- @param model table The model ID whose target should be removed.
---
--- @usage
--- ```lua
--- removeModelTarget(model)
--- ```
function removeModelTarget(model)
if isStarted(QBTargetExport) then
exports[QBTargetExport]:RemoveTargetModel(model, "Test")
end
if isStarted(OXTargetExport) then
exports[OXTargetExport]:removeModel(model, nil)
end
if Config.System.DontUseTarget or (not isStarted(OXTargetExport) and not isStarted(QBTargetExport)) then
exports.jim_bridge:removeZoneTarget(target)
end
end
-------------------------------------------------------------
-- Fallback: DrawText3D Targets (Experimental)
-------------------------------------------------------------
-- If no targeting system is detected and this is a client script, use DrawText3D for targets.
if (Config.System.DontUseTarget or (not isStarted(OXTargetExport) and not isStarted(QBTargetExport))) and not isServer() then
CreateThread(function() CreateThread(function()
while true do while true do
local pedCoords = GetEntityCoords(PlayerPedId()) local ped = PlayerPedId()
local pedCoords = GetEntityCoords(ped)
local camCoords = GetGameplayCamCoord() local camCoords = GetGameplayCamCoord()
local camRotation = GetGameplayCamRot(2) -- Get camera rotation in degrees local camRot = GetGameplayCamRot(2)
local camForwardVector = RotationToDirection(camRotation) -- Convert rotation to direction vector local camForward = RotationToDirection(camRot)
local closestTarget = nil local closestTarget = nil
local closestDist = math.huge local closestDist = math.huge
local targetEntity = nil
-- Shallow copy for safety
local targetsCopy = {}
for k, v in pairs(TextTargets) do for k, v in pairs(TextTargets) do
local targetCoords = v.coords targetsCopy[k] = v
local dist = #(pedCoords - targetCoords) end
local vecToTarget = targetCoords - camCoords
-- Normalize the vector to the target -- Detect models and update coords
local vecToTargetNormalized = normalizeVector(vecToTarget) for _, target in pairs(targetsCopy) do
if target.models then
if not target.entity or not DoesEntityExist(target.entity) then
for _, model in ipairs(target.models) do
local entity = GetClosestObjectOfType(pedCoords.x, pedCoords.y, pedCoords.z, target.dist, model, false, false, false)
if entity and entity ~= 0 then
target.entity = entity
target.coords = GetEntityCoords(entity)
break
end
end
else
target.coords = GetEntityCoords(target.entity)
end
end
end
-- Dot product to check if facing the target -- Identify closest visible target
local dot = camForwardVector.x * vecToTargetNormalized.x + camForwardVector.y * vecToTargetNormalized.y + camForwardVector.z * vecToTargetNormalized.z for _, target in pairs(targetsCopy) do
if target.coords then
local dist = #(pedCoords - target.coords)
local vecToTarget = target.coords - camCoords
local normVec = normalizeVector(vecToTarget)
local dot = camForward.x * normVec.x + camForward.y * normVec.y + camForward.z * normVec.z
local isFacing = dot > 0.5
local isFacingTarget = dot > 0.5 -- Adjust threshold as needed if dist <= target.dist and isFacing then
if dist <= v.dist and isFacingTarget then
if dist < closestDist then if dist < closestDist then
closestDist = dist closestDist = dist
closestTarget = v closestTarget = target
targetEntity = target.entity
end
end end
end end
end end
for k, v in pairs(TextTargets) do -- Render + handle input
local isClosest = (v == closestTarget) for _, target in pairs(targetsCopy) do
if #(pedCoords - v.coords) <= v.dist then if target.coords and #(pedCoords - target.coords) <= target.dist then
for i = 1, #v.options do local isClosest = (target == closestTarget)
if IsControlJustPressed(0, v.options[i].key) and isClosest then
if v.options[i].onSelect then v.options[i].onSelect() end for _, opt in ipairs(target.options) do
if v.options[i].action then v.options[i].action() end if IsControlJustPressed(0, opt.key) and isClosest then
local canInteract = (not target.canInteract or target.canInteract())
local hasItem = (not opt.item or hasItem(opt.item))
local hasJob = (not opt.job or hasJob(opt.job, nil))
if canInteract and hasItem and hasJob then
if opt.onSelect then opt.onSelect(targetEntity) end
if opt.action then opt.action(targetEntity) end
end end
end end
DrawText3D(vec3(v.coords.x, v.coords.y, v.coords.z + 0.7), concatenateText(v.buttontext), isClosest) end
-- Draw each eligible text line
local baseZ = target.coords.z + 1.0
local lineHeight = -0.16
local lineOffset = 0
for i, opt in ipairs(target.options) do
local canInteract = (not target.canInteract or target.canInteract())
local hasItem = (not opt.item or hasItem(opt.item))
local hasJob = (not opt.job or hasJob(opt.job, nil))
if canInteract and hasItem and hasJob then
local text = target.buttontext[i]
local zOffset = lineOffset * lineHeight
DrawText3D(vec3(target.coords.x, target.coords.y, baseZ + zOffset), text, isClosest)
lineOffset += 1
end end
end end
end
end
Wait(0) Wait(0)
end end
end) end)
end end
-- If the current loaded script is stopped, automatically remove targets --
function ShowFloatingHelpNotification(coord, text, highlight)
AddTextEntry("FloatingText", text)
SetFloatingHelpTextWorldPosition(1, coord.x, coord.y, coord.z)
SetFloatingHelpTextStyle(1, 1, 62, -1, 3, 0)
BeginTextCommandDisplayHelp("FloatingText")
EndTextCommandDisplayHelp(2, false, false, -1)
end
function updateCachedText(target)
target.text = table.concat(target.buttontext, "\n")
end
-------------------------------------------------------------
-- Cleanup on Resource Stop
-------------------------------------------------------------
-- When the current resource stops, remove all targets.
onResourceStop(function() onResourceStop(function()
-- Remove entity targets.
for i = 1, #targetEntities do for i = 1, #targetEntities do
if isStarted(OXTargetExport) then exports[OXTargetExport]:removeLocalEntity(targetEntities[i], nil) if isStarted(OXTargetExport) then
elseif isStarted(QBTargetExport) then exports[QBTargetExport]:RemoveTargetEntity(targetEntities[i]) end exports[OXTargetExport]:removeLocalEntity(targetEntities[i], nil)
elseif isStarted(QBTargetExport) then
exports[QBTargetExport]:RemoveTargetEntity(targetEntities[i])
end end
end
-- Remove box zone targets.
for i = 1, #boxTargets do for i = 1, #boxTargets do
if isStarted(OXTargetExport) then exports[OXTargetExport]:removeZone(boxTargets[i], true) if isStarted(OXTargetExport) then
elseif isStarted(QBTargetExport) then exports[QBTargetExport]:RemoveZone(boxTargets[i].name) end exports[OXTargetExport]:removeZone(boxTargets[i], true)
elseif isStarted(QBTargetExport) then
exports[QBTargetExport]:RemoveZone(boxTargets[i].name)
end end
end
-- Remove circle zone targets.
for i = 1, #circleTargets do for i = 1, #circleTargets do
if isStarted(OXTargetExport) then exports[OXTargetExport]:removeZone(circleTargets[i], true) if isStarted(OXTargetExport) then
elseif isStarted(QBTargetExport) then exports[QBTargetExport]:RemoveZone(circleTargets[i].name) end exports[OXTargetExport]:removeZone(circleTargets[i], true)
elseif isStarted(QBTargetExport) then
exports[QBTargetExport]:RemoveZone(circleTargets[i].name)
end
end end
end, true) end, true)

View File

@@ -1,22 +1,29 @@
-- Get Vehicle Info -- --[[
local lastCar = nil Vehicle Info & Properties Module
local carInfo = {} ----------------------------------
This module provides utilities for:
- Retrieving vehicle information from a Vehicles table.
- Getting and setting vehicle properties using the active framework.
- Comparing vehicle property differences.
- Synchronizing vehicle properties across clients.
- Managing network control of vehicles.
- Finding the closest vehicle to a given position.
]]
--- Searches the 'Vehicles' table for a specific vehicle's 'name', 'price', and 'class'. -- Cached vehicle info to avoid unnecessary re-searches.
--- local lastCar, carInfo = nil, {}
--- This function checks if the provided vehicle is different from the last searched vehicle.
--- If it's a new vehicle, it retrieves its model and searches the 'Vehicles' table for matching entries. --- Searches the 'Vehicles' table for a specific vehicle's details.
--- It populates the `carInfo` table with the vehicle's name, price, and class. --- If the vehicle differs from the last searched, it retrieves its model and updates the carInfo table.
--- If the vehicle is not found in the table, it defaults to using the vehicle's display name and sets the price to 0. --- The table includes the vehicle's name, price, and class information.
--- ---
--- @param vehicle number The entity ID of the vehicle to search for. --- @param vehicle number The entity ID of the vehicle to search for.
--- --- @return table|nil table A table containing the vehicle's details or nil if the vehicle is invalid.
---@return table|nil table containing the vehicle's `name`, `price`, and `class`, or `nil` if the vehicle is invalid.
--- ---
--- @usage --- @usage
--- ```lua --- ```lua
--- local info = searchCar(vehicleEntity) --- local info = searchCar(vehicleEntity)
--- print(info.name, info.price, info.class) --- print(info.name, info.price, info.class.name, info.class.index)
--- ``` --- ```
function searchCar(vehicle) function searchCar(vehicle)
if lastCar ~= vehicle then -- If same car, use previous info if lastCar ~= vehicle then -- If same car, use previous info
@@ -78,30 +85,30 @@ function searchCar(vehicle)
end end
end end
-- Vehicle Properties -- -------------------------------------------------------------
-- Vehicle Properties Functions
-------------------------------------------------------------
--- Retrieves the properties of a given vehicle. --- Retrieves the properties of a given vehicle using the active framework.
---
--- This function fetches the vehicle's properties based on the active framework (QBCore or ox).
--- It utilizes the framework's native functions or events to obtain the vehicle's mod list and other details.
--- ---
--- @param vehicle number The entity ID of the vehicle. --- @param vehicle number The entity ID of the vehicle.
--- --- @return table|nil table A table containing the vehicle's properties or nil if invalid.
--- @return table|nil table containing the vehicle's properties, or `nil` if the vehicle is invalid or the framework is not detected.
--- ---
--- @usage --- @usage
--- ```lua --- ```lua
--- local props = getVehicleProperties(vehicleEntity) --- local props = getVehicleProperties(vehicleEntity)
--- if props then --- if props then
--- -- Manipulate vehicle properties --- -- Use vehicle properties
--- end --- end
--- ``` --- ```
function getVehicleProperties(vehicle) function getVehicleProperties(vehicle)
if not vehicle then return nil end
local properties = {} local properties = {}
if vehicle == nil then return nil end
if isStarted(QBExport) and not isStarted(QBXExport) then if isStarted(QBExport) and not isStarted(QBXExport) then
properties = Core.Functions.GetVehicleProperties(vehicle) properties = Core.Functions.GetVehicleProperties(vehicle)
debugPrint("^6Bridge^7: ^2Getting Vehicle Properties ^7[^6"..QBExport.."^7] - [^3"..vehicle.."^7] - [^3"..GetEntityModel(vehicle).."^7/^3"..properties.model.."^7] - [^3"..properties.plate.."^7]") debugPrint("^6Bridge^7: ^2Getting Vehicle Properties ^7[^6"..QBExport.."^7] - [^3"..vehicle.."^7] - [^3"..GetEntityModel(vehicle).."^7/^3"..properties.model.."^7] - [^3"..properties.plate.."^7]")
elseif isStarted(OXLibExport) then elseif isStarted(OXLibExport) then
properties = lib.getVehicleProperties(vehicle) properties = lib.getVehicleProperties(vehicle)
debugPrint("^6Bridge^7: ^2Getting Vehicle Properties ^7[^6"..OXLibExport.."^7] - [^3"..vehicle.."^7] - [^3"..GetEntityModel(vehicle).."^7/^3"..properties.model.."^7] - [^3"..properties.plate.."^7]") debugPrint("^6Bridge^7: ^2Getting Vehicle Properties ^7[^6"..OXLibExport.."^7] - [^3"..vehicle.."^7] - [^3"..GetEntityModel(vehicle).."^7/^3"..properties.model.."^7] - [^3"..properties.plate.."^7]")
@@ -109,30 +116,29 @@ function getVehicleProperties(vehicle)
return properties return properties
end end
--- Sets the properties of a given vehicle. --- Sets the properties of a given vehicle if changes are detected.
--- --- It compares the current properties with the new ones and applies the update using the active framework.
--- This function applies the provided properties to the vehicle using the active framework's functions or events.
--- It first retrieves the current properties and checks for differences before applying the new ones.
--- ---
--- @param vehicle number The entity ID of the vehicle. --- @param vehicle number The entity ID of the vehicle.
---@param props table The properties to set on the vehicle. --- @param props table The new properties to apply.
--- ---
--- @usage --- @usage
--- ```lua --- ```lua
--- setVehicleProperties(vehicleEntity, newProperties) --- setVehicleProperties(vehicleEntity, newProperties)
--- ``` --- ```
function setVehicleProperties(vehicle, props) function setVehicleProperties(vehicle, props)
local oldProps = getVehicleProperties(vehicle)
if checkDifferences(vehicle, props) then if checkDifferences(vehicle, props) then
--if debugMode then debugDifferences(vehicle, props) end
if not DoesEntityExist(vehicle) then if not DoesEntityExist(vehicle) then
print(("Unable to set vehicle properties for '%s' (entity does not exist)"):format(vehicle)) print("Unable to set vehicle properties for '"..vehicle.."' (^1entity does not exist^7)")
end end
if isStarted(QBExport) and not isStarted(QBXExport) then if isStarted(QBExport) and not isStarted(QBXExport) then
Core.Functions.SetVehicleProperties(vehicle, props) Core.Functions.SetVehicleProperties(vehicle, props)
debugPrint("^6Bridge^7: ^2Setting Vehicle Properties ^7[^6"..QBExport.."^7] - [^3"..vehicle.."^7] - [^3"..GetEntityModel(vehicle).."^7/^3"..props.model.."^7] - [^3"..props.plate.."^7]") debugPrint("^6Bridge^7: ^2Setting Vehicle Properties ^7[^6"..QBExport.."^7] - [^3"..vehicle.."^7] - [^3"..GetEntityModel(vehicle).."^7/^3"..props.model.."^7] - [^3"..props.plate.."^7]")
else
TriggerServerEvent(getScript()..":ox:setVehicleProperties", VehToNet(vehicle), props) elseif isStarted(OXLibExport) then
lib.setVehicleProperties(vehicle, props, false)
debugPrint("^6Bridge^7: ^2Setting Vehicle Properties ^7[^6"..OXLibExport.."^7] - [^3"..vehicle.."^7] - [^3"..GetEntityModel(vehicle).."^7/^3"..props.model.."^7] - [^3"..props.plate.."^7]")
end end
else else
debugPrint("^6Bridge^7: ^2No Changes Found ^7 [^3"..vehicle.."^7] - [^3"..GetEntityModel(vehicle).."^7/^3"..props.model.."^7] - [^3"..props.plate.."^7]") debugPrint("^6Bridge^7: ^2No Changes Found ^7 [^3"..vehicle.."^7] - [^3"..GetEntityModel(vehicle).."^7/^3"..props.model.."^7] - [^3"..props.plate.."^7]")
@@ -140,14 +146,11 @@ function setVehicleProperties(vehicle, props)
end end
--- Checks for differences between the current and new vehicle properties. --- Checks for differences between the current and new vehicle properties.
--- --- Compares properties using JSON encoding for deep comparison and logs differences.
--- This function compares each property of the vehicle to determine if any changes have been made.
--- It logs the differences for debugging purposes.
--- ---
--- @param vehicle number The entity ID of the vehicle. --- @param vehicle number The entity ID of the vehicle.
---@param newProps table The new properties to compare against the current ones. --- @param newProps table The new properties to compare.
--- --- @return boolean `true` if differences are found; `false` otherwise.
---@return boolean `true` if differences are found, `false` otherwise.
--- ---
--- @usage --- @usage
--- ```lua --- ```lua
@@ -158,58 +161,58 @@ end
function checkDifferences(vehicle, newProps) function checkDifferences(vehicle, newProps)
local oldProps = getVehicleProperties(vehicle) local oldProps = getVehicleProperties(vehicle)
debugPrint("^6Bridge^7: ^2Finding differences in ^3Vehicle Properties^7") debugPrint("^6Bridge^7: ^2Finding differences in ^3Vehicle Properties^7")
local allow = false local differencesFound = true
for k in pairs(oldProps) do for k in pairs(oldProps) do
if json.encode(oldProps[k]) ~= json.encode(newProps[k]) then if json.encode(oldProps[k]) ~= json.encode(newProps[k]) then
allow = true differencesFound = true
debugPrint("^6Bridge^7: ^5Old ^7[^3"..k.."^7] - "..json.encode(oldProps[k], { indent = true })) debugPrint("^6Bridge^7: ^5Old ^7[^3"..k.."^7] - "..json.encode(oldProps[k], { indent = true }))
debugPrint("^6Bridge^7: ^5New ^7[^3"..k.."^7] - "..json.encode(newProps[k], { indent = true })) debugPrint("^6Bridge^7: ^5New ^7[^3"..k.."^7] - "..json.encode(newProps[k], { indent = true }))
end end
end end
return allow
return differencesFound
end end
--- Handles setting vehicle properties received from the server. -------------------------------------------------------------
-- Vehicle Properties Synchronization
-------------------------------------------------------------
--- Event handler for setting vehicle properties received from the server.
--- Listens for the `ox:setVehicleProperties` event and applies the properties.
--- ---
--- This event listens for the `ox:setVehicleProperties` event and applies the received properties to the vehicle. --- @event `getScript()..ox:setVehicleProperties`
---
---@event
--- @param netId number The network ID of the vehicle. --- @param netId number The network ID of the vehicle.
---@param props table The properties to set on the vehicle. --- @param props table The new vehicle properties.
---
---@usage
--- -- Server-side: TriggerClientEvent(getScript()..":ox:setVehicleProperties", netId, properties)
RegisterNetEvent(getScript()..":ox:setVehicleProperties", function(netId, props) RegisterNetEvent(getScript()..":ox:setVehicleProperties", function(netId, props)
local vehicle = NetworkGetEntityFromNetworkId(netId) local vehicle = NetworkGetEntityFromNetworkId(netId)
local value = props local value = props
Entity(vehicle).state[getScript()..':setVehicleProperties'] = value Entity(vehicle).state[getScript()..':setVehicleProperties'] = value
end) end)
--- Handles state bag changes for setting vehicle properties. --- Handles state bag changes for updating vehicle properties.
--- When the state bag changes, the new properties are applied to the vehicle.
--- ---
--- This handler listens for changes to the vehicle's state bag and applies the new properties accordingly. --- @param bagName string The state bag's name.
---
---@param bagName string The name of the state bag.
--- @param key string The key that changed. --- @param key string The key that changed.
---@param value table The new value of the state. --- @param value table The new state value.
---
---@usage
--- -- Automatically handled when the state bag changes
AddStateBagChangeHandler(getScript()..':setVehicleProperties', '', function(bagName, _, value) AddStateBagChangeHandler(getScript()..':setVehicleProperties', '', function(bagName, _, value)
if not value or not GetEntityFromStateBagName then return end if not value or not GetEntityFromStateBagName then return end
local entity = GetEntityFromStateBagName(bagName) local entity = GetEntityFromStateBagName(bagName)
local networked = not bagName:find('localEntity') local networked = not bagName:find('localEntity')
debugPrint("^6Bridge^7: ^2Setting Vehicle Properties ^7[^6"..OXLibExport.."^7] - [^3"..entity.."^7] - [^3"..GetEntityModel(entity).."^7] - [^3"..value.plate.."^7]") debugPrint("^6Bridge^7: ^2Setting Vehicle Properties ^7[^6"..OXLibExport.."^7] - [^3"..entity.."^7] - [^3"..GetEntityModel(entity).."^7] - [^3"..value.plate.."^7]")
if networked and NetworkGetEntityOwner(entity) ~= cache.playerId then return end if networked then return end
if lib.setVehicleProperties(entity, value) then if lib.setVehicleProperties(entity, value) then
Entity(entity).state:set('setVehicleProperties', nil, true) Entity(entity).state:set('setVehicleProperties', nil, true)
end end
end) end)
--- Pushes a vehicle to other players by syncing it. -------------------------------------------------------------
--- -- Vehicle Control Functions
-------------------------------------------------------------
--- This function ensures that the vehicle is controlled by the current player and is set as a mission entity. --- This function ensures that the vehicle is controlled by the current player and is set as a mission entity.
--- It requests network control and sets the vehicle accordingly to synchronize changes across clients. --- It requests network control and sets the vehicle accordingly to synchronize changes across clients.
--- ---
@@ -222,6 +225,7 @@ end)
function pushVehicle(entity) function pushVehicle(entity)
SetVehicleModKit(entity, 0) SetVehicleModKit(entity, 0)
if entity ~= 0 and DoesEntityExist(entity) then if entity ~= 0 and DoesEntityExist(entity) then
-- Request network control if not already controlled.
if not NetworkHasControlOfEntity(entity) then if not NetworkHasControlOfEntity(entity) then
debugPrint("^6Bridge^7: ^3pushVehicle^7: ^2Requesting network control of vehicle^7.") debugPrint("^6Bridge^7: ^3pushVehicle^7: ^2Requesting network control of vehicle^7.")
NetworkRequestControlOfEntity(entity) NetworkRequestControlOfEntity(entity)
@@ -231,11 +235,13 @@ function pushVehicle(entity)
timeout = timeout - 100 timeout = timeout - 100
end end
if NetworkHasControlOfEntity(entity) then if NetworkHasControlOfEntity(entity) then
debugPrint("^6Bridge^7: ^3pushVehicle^7: ^2Network has control of entity^7.") debugPrint("^6Bridge^7: ^3pushVehicle^7: ^2Network now has control of the entity^7.")
end end
end end
-- Set as mission entity if not already set.
if not IsEntityAMissionEntity(entity) then if not IsEntityAMissionEntity(entity) then
debugPrint("^6Bridge^7: ^3pushVehicle^7: ^2Setting vehicle as a ^7'^2mission^7' &2entity^7.") debugPrint("^6Bridge^7: ^3pushVehicle^7: ^2Setting vehicle as a ^7'^2mission^7' ^2entity^7.")
SetEntityAsMissionEntity(entity, true, true) SetEntityAsMissionEntity(entity, true, true)
local timeout = 2000 local timeout = 2000
while timeout > 0 and not IsEntityAMissionEntity(entity) do while timeout > 0 and not IsEntityAMissionEntity(entity) do
@@ -248,3 +254,48 @@ function pushVehicle(entity)
end end
end end
end end
--- Finds the closest vehicle to the specified coordinates.
--- The function uses different APIs based on whether a source is provided.
---
--- @param coords table|vector3 (Optional) The reference coordinates. If nil, uses the player's position.
--- @param src boolean (Optional) If true, uses GetPlayerPed(source) and GetAllVehicles.
--- @return number|number closestVehicle|closestDistance The closest vehicle entity and its distance.
---
--- @usage
--- ```lua
--- local closestVeh, distance = getClosestVehicle({ x = 100, y = 200, z = 30 }, src)
--- ```
function getClosestVehicle(coords, src)
local ped, vehicles, closestDistance, closestVehicle
if src then
ped = GetPlayerPed(src)
vehicles = GetAllVehicles()
else
ped = PlayerPedId()
vehicles = GetGamePool('CVehicle')
end
local closestDistance, closestVehicle = -1, -1
if coords then
if type(coords) == 'table' then
coords = vec3(coords.x, coords.y, coords.z)
end
else
coords = GetEntityCoords(ped)
end
for i = 1, #vehicles, 1 do
local vehicleCoords = GetEntityCoords(vehicles[i])
local distance = #(vehicleCoords - coords)
if closestDistance == -1 or distance < closestDistance then
closestDistance = distance
closestVehicle = vehicles[i]
end
end
return closestVehicle, closestDistance
end

View File

@@ -1,47 +0,0 @@
-- Version check for jim_bridge --
function CheckBridgeVersion()
if isServer() then
local currentVersion = "^3"..GetResourceMetadata("jim_bridge", 'version'):gsub("%.", "^7.^3").."^7"
PerformHttpRequest('https://raw.githubusercontent.com/jimathy/jim_bridge/master/version.txt', function(err, newestVersion, headers)
if not newestVersion then print("^1Currently unable to run a version check for ^7'^3jim_bridge^7' ("..currentVersion.."^7)") return end
newestVersion = "^3"..newestVersion:sub(1, -2):gsub("%.", "^7.^3"):gsub("%\r", "").."^7"
print(newestVersion == currentVersion and "^7'^3jim_bridge^7' - ^6You are running the latest version.^7 ("..currentVersion..")" or "^7'^3jim_bridge^7' - ^1You are currently running an outdated version^7, ^1please update^7!")
end)
end
end
--CheckBridgeVersion()
-- Print Script names
function capitalize(str)
return (str:gsub("^%l", string.upper):gsub("%-%l", function(letter) return "-" .. string.upper(letter:sub(2)) end))
end
local scriptName = ("^2"..capitalize(getScript()):gsub("%-", "^7-^2"):gsub("%_", "^7_^2")) or ""
local scriptVersion = ("^5"..GetResourceMetadata(getScript(), 'version', nil):gsub("%.", "^7.^5")) or ""
local scriptDescription = ("^2"..GetResourceMetadata(getScript(), 'description', nil)) or ""
local scriptAuthor = ("^2by ^4"..GetResourceMetadata(getScript(), 'author', nil):gsub("%and", "^7and^4")) or ""
print(scriptName.." ^7v"..scriptVersion.."^7 - "..scriptDescription.." "..scriptAuthor.."^7")
-- Loaded script Version Check, requires CheckVersion() to be placed in a server file
function CheckVersion()
if isServer() then
local currentVersion = "^3"..GetResourceMetadata(getScript(), 'version'):gsub("%.", "^7.^3").."^7"
PerformHttpRequest('https://raw.githubusercontent.com/jimathy/UpdateVersions/master/'..getScript()..'.txt', function(err, newestVersion, headers)
if not newestVersion then
PerformHttpRequest('https://raw.githubusercontent.com/jimathy/'..getScript()..'/master/version.txt', function(err, freeVersion, headers)
if not freeVersion then print("^1Currently unable to run a version check for ^7'^3"..getScript().."^7' ("..currentVersion.."^7)") return end
local currentVersion = "^3"..GetResourceMetadata(getScript(), 'version'):gsub("%.", "^7.^3").."^7"
freeVersion = "^3"..freeVersion:sub(1, -2):gsub("%.", "^7.^3"):gsub("%\r", "").."^7"
print("^6Version Check^7: ^2Running^7: "..currentVersion.." ^2Latest^7: "..freeVersion)
print(freeVersion == currentVersion and "^7'^3"..getScript().."^7' - ^6You are running the latest version.^7 ("..currentVersion..")" or "^7'^3"..getScript().."^7' - ^1You are currently running an outdated version^7, ^1please update^7!")
end)
else
newestVersion = "^3"..newestVersion:sub(1, -2):gsub("%.", "^7.^3"):gsub("%\r", "").."^7"
print("^6Version Check^7: ^2Running^7: "..currentVersion.." ^2Latest^7: "..newestVersion)
print(newestVersion == currentVersion and '^6You are running the latest version.^7 ('..currentVersion..')' or "^1You are currently running an outdated version^7, ^1please update^7!")
end
end)
end
end
--CheckVersion()

694
shared/warmenu.lua Normal file
View File

@@ -0,0 +1,694 @@
WarMenu = { }
WarMenu.__index = WarMenu
if not isServer() then
-- Deprecated
WarMenu.debug = false
function WarMenu.SetDebugEnabled(enabled)
end
function WarMenu.IsDebugEnabled()
return false
end
---
local menus = { }
local keys = { down = 187, scrollDown = 242, up = 188, scrollUp = 241, left = 189, right = 190, select = 191, accept = 237, back = 194, cancel = 238 }
local skipInputNextFrame = true
local optionCount = 0
local currentKey = nil
local currentMenu = nil
local toolTipWidth = 0.153
local spriteWidth = 0.027
local spriteHeight = spriteWidth * GetAspectRatio()
local titleHeight = 0.101
local titleYOffset = 0.021
local titleFont = 1
local titleScale = 1.0
local buttonHeight = 0.038
local buttonFont = 0
local buttonScale = 0.365
local buttonTextXOffset = 0.005
local buttonTextYOffset = 0.005
local buttonSpriteXOffset = 0.002
local buttonSpriteYOffset = 0.005
local defaultStyle = {
x = 0.0175,
y = 0.025,
width = 0.23,
maxOptionCountOnScreen = 10,
titleVisible = true,
titleColor = { 0, 0, 0, 255 },
titleBackgroundColor = { 245, 127, 23, 255 },
titleBackgroundSprite = nil,
subTitleColor = { 245, 127, 23, 255 },
textColor = { 254, 254, 254, 255 },
subTextColor = { 189, 189, 189, 255 },
focusTextColor = { 0, 0, 0, 255 },
focusColor = { 245, 245, 245, 255 },
backgroundColor = { 0, 0, 0, 160 },
subTitleBackgroundColor = { 0, 0, 0, 255 },
buttonPressedSound = { name = 'SELECT', set = 'HUD_FRONTEND_DEFAULT_SOUNDSET' }, --https://pastebin.com/0neZdsZ5
}
local function IsNavigatedDown()
return IsControlJustReleased(2, keys.down) or IsControlJustReleased(2, keys.scrollDown)
end
local function IsNavigatedUp()
return IsControlJustReleased(2, keys.up) or IsControlJustReleased(2, keys.scrollUp)
end
local function IsSelectedPressed()
return IsControlJustReleased(2, keys.select) or IsControlJustReleased(2, keys.accept)
end
local function IsBackPressed()
return IsControlJustReleased(2, keys.back) or IsControlJustReleased(2, keys.cancel)
end
local function setMenuProperty(id, property, value)
if not id then
return
end
local menu = menus[id]
if menu then
menu[property] = value
end
end
local function setStyleProperty(id, property, value)
if not id then
return
end
local menu = menus[id]
if menu then
if not menu.overrideStyle then
menu.overrideStyle = { }
end
menu.overrideStyle[property] = value
end
end
local function getStyleProperty(property, menu)
menu = menu or currentMenu
if menu.overrideStyle then
local value = menu.overrideStyle[property]
if value ~= nil then
return value
end
end
return menu.style and menu.style[property] or defaultStyle[property]
end
local function getTitleHeight()
return getStyleProperty('titleVisible') and titleHeight or 0
end
local function copyTable(t)
if type(t) ~= 'table' then
return t
end
local result = { }
for k, v in pairs(t) do
result[k] = copyTable(v)
end
return result
end
local function setMenuVisible(id, visible, holdCurrentOption)
if currentMenu then
if visible then
if currentMenu.id == id then
return
end
else
if currentMenu.id ~= id then
return
end
end
end
if visible then
local menu = menus[id]
if not currentMenu then
menu.currentOption = 1
else
if not holdCurrentOption then
menus[currentMenu.id].currentOption = 1
end
end
currentMenu = menu
skipInputNextFrame = true
SetUserRadioControlEnabled(false)
HudWeaponWheelIgnoreControlInput(true)
else
HudWeaponWheelIgnoreControlInput(false)
SetUserRadioControlEnabled(true)
currentMenu = nil
end
end
local function setTextParams(font, color, scale, center, shadow, alignRight, wrapFrom, wrapTo)
SetTextFont(font)
SetTextColour(color[1], color[2], color[3], color[4] or 255)
SetTextScale(scale, scale)
if shadow then
SetTextDropShadow()
end
if center then
SetTextCentre(true)
elseif alignRight then
SetTextRightJustify(true)
end
if not wrapFrom or not wrapTo then
wrapFrom = wrapFrom or getStyleProperty('x')
wrapTo = wrapTo or getStyleProperty('x') + getStyleProperty('width') - buttonTextXOffset
end
SetTextWrap(wrapFrom, wrapTo)
end
local function getLinesCount(text, x, y)
BeginTextCommandLineCount('TWOSTRINGS')
AddTextComponentString(tostring(text))
return EndTextCommandGetLineCount(x, y)
end
local function drawText(text, x, y)
BeginTextCommandDisplayText('TWOSTRINGS')
AddTextComponentString(tostring(text))
EndTextCommandDisplayText(x, y)
end
local function drawRect(x, y, width, height, color)
DrawRect(x, y, width, height, color[1], color[2], color[3], color[4] or 255)
end
local function getCurrentIndex()
if currentMenu.currentOption <= getStyleProperty('maxOptionCountOnScreen') and optionCount <= getStyleProperty('maxOptionCountOnScreen') then
return optionCount
elseif optionCount > currentMenu.currentOption - getStyleProperty('maxOptionCountOnScreen') and optionCount <= currentMenu.currentOption then
return optionCount - (currentMenu.currentOption - getStyleProperty('maxOptionCountOnScreen'))
end
return nil
end
local function drawTitle()
if not getStyleProperty('titleVisible') then
return
end
local x = getStyleProperty('x') + getStyleProperty('width') / 2
local y = getStyleProperty('y') + titleHeight / 2
if getStyleProperty('titleBackgroundSprite') then
DrawSprite(getStyleProperty('titleBackgroundSprite').dict, getStyleProperty('titleBackgroundSprite').name, x, y, getStyleProperty('width'), titleHeight, 0., 255, 255, 255, 255)
else
drawRect(x, y, getStyleProperty('width'), titleHeight, getStyleProperty('titleBackgroundColor'))
end
if currentMenu.title then
setTextParams(titleFont, getStyleProperty('titleColor'), titleScale, true)
drawText(currentMenu.title, x, y - titleHeight / 2 + titleYOffset)
end
end
local function drawSubTitle()
local x = getStyleProperty('x') + getStyleProperty('width') / 2
local y = getStyleProperty('y') + getTitleHeight() + buttonHeight / 2
drawRect(x, y, getStyleProperty('width'), buttonHeight, getStyleProperty('subTitleBackgroundColor'))
setTextParams(buttonFont, getStyleProperty('subTitleColor'), buttonScale, false)
drawText(currentMenu.subTitle, getStyleProperty('x') + buttonTextXOffset, y - buttonHeight / 2 + buttonTextYOffset)
if optionCount > getStyleProperty('maxOptionCountOnScreen') then
setTextParams(buttonFont, getStyleProperty('subTitleColor'), buttonScale, false, false, true)
drawText(tostring(currentMenu.currentOption)..' / '..tostring(optionCount), getStyleProperty('x') + getStyleProperty('width'), y - buttonHeight / 2 + buttonTextYOffset)
end
end
local function drawButton(text, subText)
local currentIndex = getCurrentIndex()
if not currentIndex then
return
end
local backgroundColor = nil
local textColor = nil
local subTextColor = nil
local shadow = false
if currentMenu.currentOption == optionCount then
backgroundColor = getStyleProperty('focusColor')
textColor = getStyleProperty('focusTextColor')
subTextColor = getStyleProperty('focusTextColor')
else
backgroundColor = getStyleProperty('backgroundColor')
textColor = getStyleProperty('textColor')
subTextColor = getStyleProperty('subTextColor')
shadow = true
end
local x = getStyleProperty('x') + getStyleProperty('width') / 2
local y = getStyleProperty('y') + getTitleHeight() + buttonHeight + (buttonHeight * currentIndex) - buttonHeight / 2
drawRect(x, y, getStyleProperty('width'), buttonHeight, backgroundColor)
setTextParams(buttonFont, textColor, buttonScale, false, shadow)
drawText(text, getStyleProperty('x') + buttonTextXOffset, y - (buttonHeight / 2) + buttonTextYOffset)
if subText then
setTextParams(buttonFont, subTextColor, buttonScale, false, shadow, true)
drawText(subText, getStyleProperty('x') + buttonTextXOffset, y - buttonHeight / 2 + buttonTextYOffset)
end
end
function WarMenu.CreateMenu(id, title, subTitle, style)
-- Default settings
local menu = { }
-- Members
menu.id = id
menu.previousMenu = nil
menu.currentOption = 1
menu.title = title
menu.subTitle = subTitle and string.upper(subTitle) or 'INTERACTION MENU'
-- Style
if style then
menu.style = style
end
menus[id] = menu
end
function WarMenu.CreateSubMenu(id, parent, subTitle, style)
local parentMenu = menus[parent]
if not parentMenu then
return
end
WarMenu.CreateMenu(id, parentMenu.title, subTitle and string.upper(subTitle) or parentMenu.subTitle)
local menu = menus[id]
menu.previousMenu = parent
if parentMenu.overrideStyle then
menu.overrideStyle = copyTable(parentMenu.overrideStyle)
end
if style then
menu.style = style
elseif parentMenu.style then
menu.style = copyTable(parentMenu.style)
end
end
function WarMenu.CurrentMenu()
return currentMenu and currentMenu.id or nil
end
function WarMenu.OpenMenu(id)
if id and menus[id] then
PlaySoundFrontend(-1, 'SELECT', 'HUD_FRONTEND_DEFAULT_SOUNDSET', true)
setMenuVisible(id, true, true)
end
end
function WarMenu.IsMenuOpened(id)
return currentMenu and currentMenu.id == id
end
WarMenu.Begin = WarMenu.IsMenuOpened
function WarMenu.IsAnyMenuOpened()
return currentMenu ~= nil
end
function WarMenu.IsMenuAboutToBeClosed()
return false
end
function WarMenu.CloseMenu()
if currentMenu then
setMenuVisible(currentMenu.id, false)
optionCount = 0
currentKey = nil
PlaySoundFrontend(-1, 'QUIT', 'HUD_FRONTEND_DEFAULT_SOUNDSET', true)
end
end
function WarMenu.ToolTip(text, width, flipHorizontal)
if not currentMenu then
return
end
local currentIndex = getCurrentIndex()
if not currentIndex then
return
end
width = width or toolTipWidth
local x = nil
if not flipHorizontal then
x = getStyleProperty('x') + getStyleProperty('width') + width / 2 + buttonTextXOffset
else
x = getStyleProperty('x') - width / 2 - buttonTextXOffset
end
local textX = x - (width / 2) + buttonTextXOffset
setTextParams(buttonFont, getStyleProperty('textColor'), buttonScale, false, true, false, textX, textX + width - (buttonTextYOffset * 2))
local linesCount = getLinesCount(text, textX, getStyleProperty('y'))
local height = GetTextScaleHeight(buttonScale, buttonFont) * (linesCount + 1) + buttonTextYOffset
local y = getStyleProperty('y') + getTitleHeight() + (buttonHeight * currentIndex) + height / 2
drawRect(x, y, width, height, getStyleProperty('backgroundColor'))
y = y - (height / 2) + buttonTextYOffset
drawText(text, textX, y)
end
function WarMenu.Button(text, subText)
if not currentMenu then
return
end
optionCount = optionCount + 1
drawButton(text, subText)
local pressed = false
if currentMenu.currentOption == optionCount then
if currentKey == keys.select then
pressed = true
PlaySoundFrontend(-1, getStyleProperty('buttonPressedSound').name, getStyleProperty('buttonPressedSound').set, true)
elseif currentKey == keys.left or currentKey == keys.right then
PlaySoundFrontend(-1, 'NAV_UP_DOWN', 'HUD_FRONTEND_DEFAULT_SOUNDSET', true)
end
end
return pressed
end
function WarMenu.SpriteButton(text, dict, name, r, g, b, a)
if not currentMenu then
return
end
local pressed = WarMenu.Button(text)
local currentIndex = getCurrentIndex()
if not currentIndex then
return
end
if not HasStreamedTextureDictLoaded(dict) then
RequestStreamedTextureDict(dict)
end
DrawSprite(dict, name, getStyleProperty('x') + getStyleProperty('width') - spriteWidth / 2 - buttonSpriteXOffset, getStyleProperty('y') + getTitleHeight() + buttonHeight + (buttonHeight * currentIndex) - spriteHeight / 2 + buttonSpriteYOffset, spriteWidth, spriteHeight, 0., r or 255, g or 255, b or 255, a or 255)
return pressed
end
function WarMenu.InputButton(text, windowTitleEntry, defaultText, maxLength, subText)
if not currentMenu then
return
end
local pressed = WarMenu.Button(text, subText)
local inputText = nil
if pressed then
DisplayOnscreenKeyboard(1, windowTitleEntry or 'FMMC_MPM_NA', '', defaultText or '', '', '', '', maxLength or 255)
while true do
DisableAllControlActions(0)
local status = UpdateOnscreenKeyboard()
if status == 2 then
break
elseif status == 1 then
inputText = GetOnscreenKeyboardResult()
break
end
Citizen.Wait(0)
end
end
return pressed, inputText
end
function WarMenu.MenuButton(text, id, subText)
if not currentMenu then
return
end
local pressed = WarMenu.Button(text, subText)
if pressed then
currentMenu.currentOption = optionCount
setMenuVisible(currentMenu.id, false)
setMenuVisible(id, true, true)
end
return pressed
end
function WarMenu.CheckBox(text, checked, callback)
if not currentMenu then
return
end
local name = nil
if currentMenu.currentOption == optionCount + 1 then
name = checked and 'shop_box_tickb' or 'shop_box_blankb'
else
name = checked and 'shop_box_tick' or 'shop_box_blank'
end
local pressed = WarMenu.SpriteButton(text, 'commonmenu', name)
if pressed then
checked = not checked
if callback then callback(checked) end
end
return pressed
end
function WarMenu.ComboBox(text, items, currentIndex, selectedIndex, callback)
if not currentMenu then
return
end
local itemsCount = #items
local selectedItem = items[currentIndex]
local isCurrent = currentMenu.currentOption == optionCount + 1
selectedIndex = selectedIndex or currentIndex
if itemsCount > 1 and isCurrent then
selectedItem = ''..tostring(selectedItem)..''
end
local pressed = WarMenu.Button(text, selectedItem)
if pressed then
selectedIndex = currentIndex
elseif isCurrent then
if currentKey == keys.left then
if currentIndex > 1 then currentIndex = currentIndex - 1 else currentIndex = itemsCount end
elseif currentKey == keys.right then
if currentIndex < itemsCount then currentIndex = currentIndex + 1 else currentIndex = 1 end
end
end
if callback then callback(currentIndex, selectedIndex) end
return pressed, currentIndex
end
function WarMenu.Display()
if currentMenu then
if not IsPauseMenuActive() then
ClearAllHelpMessages()
HudWeaponWheelIgnoreSelection()
DisablePlayerFiring(PlayerId(), true)
DisableControlAction(0, 25, true)
drawTitle()
drawSubTitle()
currentKey = nil
if skipInputNextFrame then
skipInputNextFrame = false
else
if IsNavigatedDown() then
PlaySoundFrontend(-1, 'NAV_UP_DOWN', 'HUD_FRONTEND_DEFAULT_SOUNDSET', true)
if currentMenu.currentOption < optionCount then
currentMenu.currentOption = currentMenu.currentOption + 1
else
currentMenu.currentOption = 1
end
elseif IsNavigatedUp() then
PlaySoundFrontend(-1, 'NAV_UP_DOWN', 'HUD_FRONTEND_DEFAULT_SOUNDSET', true)
if currentMenu.currentOption > 1 then
currentMenu.currentOption = currentMenu.currentOption - 1
else
currentMenu.currentOption = optionCount
end
elseif IsControlJustReleased(2, keys.left) then
currentKey = keys.left
elseif IsControlJustReleased(2, keys.right) then
currentKey = keys.right
elseif IsSelectedPressed() then
currentKey = keys.select
elseif IsBackPressed() then
if menus[currentMenu.previousMenu] then
setMenuVisible(currentMenu.previousMenu, true)
PlaySoundFrontend(-1, 'BACK', 'HUD_FRONTEND_DEFAULT_SOUNDSET', true)
else
WarMenu.CloseMenu()
end
end
end
end
optionCount = 0
end
end
WarMenu.End = WarMenu.Display
function WarMenu.CurrentOption()
if currentMenu and optionCount ~= 0 then
return currentMenu.currentOption
end
return nil
end
function WarMenu.IsItemHovered()
if not currentMenu or optionCount == 0 then
return false
end
return currentMenu.currentOption == optionCount
end
function WarMenu.IsItemSelected()
return currentKey == keys.select and WarMenu.IsItemHovered()
end
function WarMenu.SetTitle(id, title)
setMenuProperty(id, 'title', title)
end
WarMenu.SetMenuTitle = WarMenu.SetTitle
function WarMenu.SetSubTitle(id, text)
setMenuProperty(id, 'subTitle', string.upper(text))
end
WarMenu.SetMenuSubTitle = WarMenu.SetSubTitle
function WarMenu.SetMenuStyle(id, style)
setMenuProperty(id, 'style', style)
end
function WarMenu.SetMenuTitleVisible(id, visible)
setStyleProperty(id, 'titleVisible', visible)
end
function WarMenu.SetMenuX(id, x)
setStyleProperty(id, 'x', x)
end
function WarMenu.SetMenuY(id, y)
setStyleProperty(id, 'y', y)
end
function WarMenu.SetMenuWidth(id, width)
setStyleProperty(id, 'width', width)
end
function WarMenu.SetMenuMaxOptionCountOnScreen(id, count)
setStyleProperty(id, 'maxOptionCountOnScreen', count)
end
function WarMenu.SetTitleColor(id, r, g, b, a)
setStyleProperty(id, 'titleColor', { r, g, b, a })
end
WarMenu.SetMenuTitleColor = WarMenu.SetTitleColor
function WarMenu.SetMenuSubTitleColor(id, r, g, b, a)
setStyleProperty(id, 'subTitleColor', { r, g, b, a })
end
function WarMenu.SetMenuSubTitleBackgroundColor(id, r, g, b, a)
setStyleProperty(id, 'subTitleBackgroundColor', { r, g, b, a })
end
function WarMenu.SetTitleBackgroundColor(id, r, g, b, a)
setStyleProperty(id, 'titleBackgroundColor', { r, g, b, a })
end
WarMenu.SetMenuTitleBackgroundColor = WarMenu.SetTitleBackgroundColor
function WarMenu.SetTitleBackgroundSprite(id, dict, name)
RequestStreamedTextureDict(dict)
setStyleProperty(id, 'titleBackgroundSprite', { dict = dict, name = name })
end
WarMenu.SetMenuTitleBackgroundSprite = WarMenu.SetTitleBackgroundSprite
function WarMenu.SetMenuBackgroundColor(id, r, g, b, a)
setStyleProperty(id, 'backgroundColor', { r, g, b, a })
end
function WarMenu.SetMenuTextColor(id, r, g, b, a)
setStyleProperty(id, 'textColor', { r, g, b, a })
end
function WarMenu.SetMenuSubTextColor(id, r, g, b, a)
setStyleProperty(id, 'subTextColor', { r, g, b, a })
end
function WarMenu.SetMenuFocusColor(id, r, g, b, a)
setStyleProperty(id, 'focusColor', { r, g, b, a })
end
function WarMenu.SetMenuFocusTextColor(id, r, g, b, a)
setStyleProperty(id, 'focusTextColor', { r, g, b, a })
end
function WarMenu.SetMenuButtonPressedSound(id, name, set)
setStyleProperty(id, 'buttonPressedSound', { name = name, set = set })
end
end

View File

@@ -1,162 +1,17 @@
-- Phone Mails
--- Sends a phone mail using the detected phone system.
---
--- This function detects the active phone resource (e.g., gksphone, yflip-phone, qb-phone, etc.)
--- and sends a mail using the appropriate method for that phone system.
---
--- @param data table A table containing the mail data.
--- - **subject** (`string`): The subject of the email.
--- - **sender** (`string`): The sender of the email.
--- - **message** (`string`): The body content of the email.
--- - **actions** (`table|nil`): (Optional) Action buttons associated with the email.
---
--- @usage
--- ```lua
--- sendPhoneMail({
--- subject = "Welcome!",
--- sender = "Admin",
--- message = "Thank you for joining our server.",
--- actions = {
--- { label = "Reply", action = replyFunction }
--- }
--- })
--- ```
function sendPhoneMail(data) local phoneResource = ""
if isStarted("gksphone") then phoneResource = "gksphone"
exports["gksphone"]:SendNewMail(data)
elseif isStarted("yflip-phone") then phoneResource = "yflip-phone"
TriggerServerEvent(getScript()..":yflip:SendMail", data)
elseif isStarted("qs-smartphone") then phoneResource = "qs-smartphone"
TriggerServerEvent('qs-smartphone:server:sendNewMail', data)
elseif isStarted("qs-smartphone-pro") then phoneResource = "qs-smartphone-pro"
TriggerServerEvent('phone:sendNewMail', data)
elseif isStarted("roadphone") then phoneResource = "roadphone"
data.message = data.message:gsub("%<br>", "\n")
exports['roadphone']:sendMail(data)
elseif isStarted("lb-phone") then phoneResource = "lb-phone"
data.message = data.message:gsub("%<br>", "\n")
TriggerServerEvent(getScript()..":lbphone:SendMail", data)
elseif isStarted("qb-phone") then phoneResource = "qb-phone"
TriggerServerEvent('qb-phone:server:sendNewMail', data)
elseif isStarted("jpr-phonesystem") then phoneResource = "jpr-phonesystem"
TriggerServerEvent(getScript()..":jpr:SendMail", data)
end
if phoneResource ~= "" then debugPrint("^6Bridge^7[^3"..phoneResource.."^7]: ^2Sending mail to player")
else print("^6Bridge^7: ^1ERROR ^2Sending mail to player ^7 - ^2No supported phone found") end
end
--- Handles sending mail for lb-phone.
---
--- This event listens for the `lbphone:SendMail` event and sends an email using lb-phone's API.
---
--- @event
--- @param data table The mail data.
--- - **subject** (`string`): The subject of the email.
--- - **message** (`string`): The body content of the email.
--- - **buttons** (`table|nil`): (Optional) Action buttons associated with the email.
---
--- @usage
--- ```
--- -- Server-side:
--- TriggerClientEvent(getScript()..":lbphone:SendMail", data)
--- ```
RegisterNetEvent(getScript()..":lbphone:SendMail", function(data)
local src = source
local phoneNumber = exports["lb-phone"]:GetEquippedPhoneNumber(src)
local emailAddress = exports["lb-phone"]:GetEmailAddress(phoneNumber)
if data.actions then data.buttons = data.actions end
exports["lb-phone"]:SendMail({
to = emailAddress,
subject = data.subject,
message = data.message,
actions = data.buttons,
})
end)
--- Handles sending mail for yflip-phone.
---
--- This event listens for the `yflip:SendMail` event and sends an email using yflip-phone's API.
---
--- @event
--- @param data table The mail data.
--- - **subject** (`string`): The subject of the email.
--- - **sender** (`string`): The sender of the email.
--- - **message** (`string`): The body content of the email.
--- - **buttons** (`table|nil`): (Optional) Action buttons associated with the email.
---
--- @usage
--- ```lua
--- -- Server-side:
--- TriggerClientEvent(getScript()..":yflip:SendMail", data)
--- ```
RegisterNetEvent(getScript()..":yflip:SendMail", function(data)
local src = source
exports["yflip-phone"]:SendMail({
title = data.subject,
sender = data.sender,
senderDisplayName = data.sender,
content = data.message,
actions = data.buttons,
}, 'source', src)
end)
--- Handles sending mail for jpr-phonesystem.
---
--- This event listens for the `jpr:SendMail` event and sends an email using jpr-phonesystem's API.
---
--- @event
--- @param data table The mail data.
--- - **subject** (`string`): The subject of the email.
--- - **sender** (`string`): The sender of the email.
--- - **message** (`string`): The body content of the email.
--- - **buttons** (`table|nil`): (Optional) Action buttons associated with the email.
---
--- @return void
---
--- @usage
--- ```lua
--- -- Server-side:
--- TriggerClientEvent(getScript()..":jpr:SendMail", data)
--- ```
RegisterNetEvent(getScript()..":jpr:SendMail", function(data)
local src = source
local Player = Core.Functions.GetPlayer(src)
TriggerEvent('jpr-phonesystem:server:sendEmail', {
Assunto = data.subject, -- Subject
Conteudo = data.message, -- Content
Enviado = data.sender, -- Submitted by
Destinatario = Player.PlayerData.citizenid, -- Target
Event = {}, -- Optional
})
end)
-- Server-Side Functions for Registering Commands, Stashes, and Shops
--- Registers a command with the active command system. --- Registers a command with the active command system.
--- --- This function supports multiple command systems (OXLib, qb-core, ESX Legacy).
--- This function detects whether the server is using OXLib or qb-core for command registration
--- and registers the command accordingly.
--- ---
--- @param command string The name of the command to register. --- @param command string The name of the command to register.
--- @param options table A table containing command options. --- @param options table A table containing command options.
--- - **help** (`string`): The help description for the command. --- - help (`string`): The help description for the command.
--- - **params** (`table`): A table of parameters for the command. --- - params (`table`): A table of parameters for the command.
--- - **callback** (`function`): The function to execute when the command is called. --- - callback (`function`): The function to execute when the command is called.
--- - **autocomplete** (`function|nil`): (Optional) A function for autocompletion. --- - autocomplete (`function|nil`): (Optional) A function for autocompletion.
--- - **restrictedGroup** (`string|nil`): (Optional) The user group required to execute the command. --- - restrictedGroup (`string|nil`): (Optional) The user group required to execute the command.
--- ---
--- @usage --- @usage
--- ````lua --- ```lua
--- -- Server Side:
--- registerCommand("greet", { --- registerCommand("greet", {
--- "Greets the player", --- "Greets the player",
--- { name = "name", help = "Name of the player to greet" }, --- { name = "name", help = "Name of the player to greet" },
@@ -166,95 +21,24 @@ end)
--- }) --- })
--- ``` --- ```
function registerCommand(command, options) function registerCommand(command, options)
if isStarted(OXLibExport) then if isStarted(OXLibExport) then
debugPrint("^6Bridge^7: ^2Registering ^3Command^2 with ^7"..OXLibExport, command) debugPrint("^6Bridge^7: ^2Registering ^3Command^2 with ^7"..OXLibExport, command)
lib.addCommand(command, { help = options[1], restricted = options[5] and "group."..options[5] or nil }, options[4]) lib.addCommand(command, { help = options[1], restricted = options[5] and "group."..options[5] or nil }, options[4])
elseif isStarted(QBExport) and not isStarted(QBXExport) then elseif isStarted(QBExport) and not isStarted(QBXExport) then
debugPrint("^6Bridge^7: ^2Registering ^3Command^2 with ^7"..QBExport, command) debugPrint("^6Bridge^7: ^2Registering ^3Command^2 with ^7"..QBExport, command)
Core.Commands.Add(command, options[1], options[2], options[3], options[4], options[5] and options[5] or nil) Core.Commands.Add(command, options[1], options[2], options[3], options[4], options[5] or nil)
end
end
--- Registers a stash with the active inventory system. elseif isStarted(RSGExport) then
--- debugPrint("^6Bridge^7: ^2Registering ^3Command^2 with ^7"..RSGExport, command)
--- This function detects whether the server is using OXInv or QSInv and registers the stash accordingly. Core.Commands.Add(command, options[1], options[2], options[3], options[4], options[5] or nil)
---
--- @param name string The unique identifier for the stash.
--- @param label string The display name for the stash.
--- @param slots number|nil (Optional) The number of slots in the stash. Defaults to 50.
--- @param weight number|nil (Optional) The maximum weight the stash can hold. Defaults to 4,000,000.
--- @param owner string|nil (Optional) The owner identifier for personal stashes.
--- @param coords table|nil (Optional) The coordinates for the stash location.
---
--- @usage
--- ```lua
--- registerStash("playerStash", "Player Stash", 100, 8000000, "player123", { x = 100.0, y = 200.0, z = 30.0 })
--- ```
function registerStash(name, label, slots, weight, owner, coords)
if isStarted(OXInv) then
debugPrint("^6Bridge^7: ^2Registering ^3OX ^2Stash^7:", name, label, owner or nil)
exports[OXInv]:RegisterStash(name, label, slots or 50, weight or 4000000, owner or nil)
elseif isStarted(QSInv) then
debugPrint("^6Bridge^7: ^2Registering ^3QS ^2Stash^7:", name, label)
exports[QSInv]:RegisterStash(name, slots or 50, weight or 4000000)
end
end
--- Registers a shop with the active inventory system. elseif isStarted(ESXExport) then
--- debugPrint("^6Bridge^7: ^2Registering ^3Command^2 with ^7ESX Legacy", command)
--- This function detects whether the server is using OXInv or QBInv and registers the shop accordingly. ESX.RegisterCommand(command, options[5] or 'admin', function(xPlayer, args, showError)
--- options[4](xPlayer.source, args, showError)
--- @param name string The unique identifier for the shop. end, false, { help = options[1] })
--- @param label string The display name for the shop.
--- @param items table The list of items available in the shop.
--- @param society string|nil (Optional) The society identifier for shared shops.
---
--- @usage
--- ```lua
--- registerShop("weaponShop", "Weapon Shop", weaponItems, "society_weapons")
--- ```
function registerShop(name, label, items, society)
if isStarted(OXInv) then
debugPrint("^6Bridge^7: ^2Registering ^3OX ^2Store^7:", name, label)
exports[OXInv]:RegisterShop(
name, {
name = label,
inventory = items,
society = society,
}
)
elseif isStarted(QBInv) and QBInvNew then
debugPrint("^6Bridge^7: ^2Registering ^3QB ^2Store^7:", name, label)
print(json.encode(items, {indent = true}))
exports[QBInv]:CreateShop({
name = name,
label = label,
slots = #items,
items = items,
society = society,
})
end
end
-- Server-Side Event Registration end
if isServer() then
--- Registers an event to create an OX stash from the server.
---
--- @event
--- @param name string The unique identifier for the stash.
--- @param label string The display name for the stash.
--- @param slots number|nil (Optional) The number of slots in the stash.
--- @param weight number|nil (Optional) The maximum weight the stash can hold.
--- @param owner string|nil (Optional) The owner identifier for personal stashes.
--- @param coords table|nil (Optional) The coordinates for the stash location.
---
--- @usage
--- ```lua
--- -- Server-side:
--- TriggerEvent(getScript()..":server:makeOXStash", name, label, slots, weight, owner, coords)
--- ```
RegisterNetEvent(getScript()..":server:makeOXStash", function(name, label, slots, weight, owner, coords)
registerStash(name, label, slots, weight, owner, coords)
end)
end end

View File

@@ -1,3 +1,5 @@
gameName = not IsDuplicityVersion() and GetCurrentGameName()
Exports = { Exports = {
QBExport = "qb-core", QBExport = "qb-core",
QBXExport = "qbx_core", QBXExport = "qbx_core",
@@ -11,13 +13,19 @@ Exports = {
CoreInv = "core_inventory", CoreInv = "core_inventory",
CodeMInv = "codem-inventory", CodeMInv = "codem-inventory",
OrigenInv = "origen_inventory", OrigenInv = "origen_inventory",
TgiannInv = "tgiann-inventory",
JPRInv = "jpr-inventory",
OXLibExport = "ox_lib", OXLibExport = "ox_lib",
QBMenuExport = "qb-menu", QBMenuExport = "qb-menu",
QBTargetExport = "qb-target", QBTargetExport = "qb-target",
OXTargetExport = "ox_target" OXTargetExport = "ox_target",
-- REDM
RSGExport = "rsg-core",
RSGInv = "rsg-inventory"
} }
-- Required variables -- Required variables
@@ -27,18 +35,103 @@ QBInvNew = true
InventoryWeight = 120000 InventoryWeight = 120000
-- [[ Server.Cfg Convar Check ]]--
-- Check server convars for hard set defaults, otherwise it uses per script configurations
if Config and Config.System then
if Config.System.Debug then
if GetConvar("jim_DisableDebug", "false") == "true" then
debugMode = false
end
if GetConvar("jim_DisableEventDebug", "false") == "true" then
Config.System.EventDebug = false
end
end
Config.System.Menu = GetConvar("jim_menuScript", Config.System.Menu)
Config.System.Notify = GetConvar("jim_notifyScript", Config.System.Notify or "gta")
Config.System.ProgressBar = GetConvar("jim_progressBarScript", Config.System.ProgressBar or "gta")
Config.System.drawText = GetConvar("jim_drawTextScript", Config.System.drawText or "gta")
Config.System.skillCheck = GetConvar("jim_skillCheckScript", Config.System.skillCheck or "gta")
if GetConvar("jim_dontUseTarget", "false") == "true" then
Config.System.DontUseTarget = true
end
end
-- Load the core files here instead of in fxmanifests
-- Forcefully loads the files and quietly, compared to fxmanifest complaining if they don't exist when you don't need them all
local filesToLoad = {
Shared = {
[Exports.OXLibExport] = { "init.lua" },
[Exports.OXCoreExport] = { "lib/init.lua" },
[Exports.ESXExport] = { "imports.lua" },
[Exports.QBXExport] = { "modules/playerdata.lua" },
},
Client = {
["PolyZone"] = { "client.lua", "BoxZone.lua", "EntityZone.lua", "CircleZone.lua", "ComboZone.lua" },
["warmenu"] = { "warmenu.lua", },
},
}
-- Shared framework file loader
for Type, ScriptTable in pairs(filesToLoad) do
if Type == "Client" and IsDuplicityVersion() then
goto continue
else
for scriptName, files in pairs(ScriptTable) do
local state = GetResourceState(scriptName)
-- if the resource is started, load the file
if state == "started" then
if scriptName == Exports.OXLibExport and GetResourceState(Exports.OXCoreExport):find("start") then
if debugMode then print("OX_Core found, skipping OX_Lib loading") end
goto skip
end
-- Force items into a table if they are not
if type(files) == "string" then
files = { files }
end
for _, file in pairs(files) do
--print("^5CoreLoader^7: '"..scriptName.."/"..file.."' ^2into ^7'"..GetCurrentResourceName().."' ...")
local fileLoader = assert(load(LoadResourceFile(scriptName, (file)), ('@@'..scriptName..'/'..file)))
fileLoader()
if debugMode then
print("^5CoreLoader^7: ^2loaded ^1Core ^2file^7: ^3"..scriptName.."^7/^3"..(file):gsub("/", "^7/^3"):gsub("%.lua", "^7.lua").." ^2into ^7'"..GetCurrentResourceName().."'")
end
end
::skip::
end
-- if script is in server, but not started warn the user
if state == "uninitialized" or state == "stopped" then
print("^5CoreLoader^7: ^3"..scriptName.." ^1 found but it wasn't started^7.")
print("^1Check your ^3server^7.^3cfg ^1load order^7")
end
-- debugging only, if the script is missing, warn the user
if state == "missing" then
if debugMode then
print("^5CoreLoader^7: ^3"..scriptName.." ^2not found^7, ^2skipping")
end
end
end
end
::continue::
end
-- Load files here into the invoking script -- Load files here into the invoking script
for _, v in pairs({ -- This is a specific load order for _, v in pairs({ -- This is a specific load order
'helpers.lua', -- needs to be first 'helpers.lua', -- needs to be first
'_loaders.lua', '_loaders.lua',
'_eventDebug.lua', '_eventDebug.lua',
'coreloader.lua', -- needs to be second to load all core related stuff before everything else
'callback.lua', 'callback.lua',
'coreloader.lua',
'duifunctions.lua', 'duifunctions.lua',
-- Native Scaleforms -- Native Scaleforms
'scaleforms/scaleform_basic.lua',
'scaleforms/bigMessageInstance.lua', 'scaleforms/bigMessageInstance.lua',
'scaleforms/countDownHandler.lua', 'scaleforms/countDownHandler.lua',
'scaleforms/debugScaleform.lua', 'scaleforms/debugScaleform.lua',
@@ -56,9 +149,13 @@ for _, v in pairs({ -- This is a specific load order
'wrapperfunctions.lua', 'wrapperfunctions.lua',
'polyZone.lua', 'polyZone.lua',
'inventories.lua',
'itemcontrol.lua', 'itemcontrol.lua',
'playerfunctions.lua', 'playerfunctions.lua',
'metaHandlers.lua',
'jobfunctions.lua', 'jobfunctions.lua',
'societybank.lua',
'phones.lua',
-- Interactions -- Interactions
'targets.lua', 'targets.lua',
@@ -66,9 +163,11 @@ for _, v in pairs({ -- This is a specific load order
'input.lua', 'input.lua',
'notify.lua', 'notify.lua',
'drawText.lua', 'drawText.lua',
'skillcheck.lua',
-- Crafting / Shops / Stashes -- Crafting / Shops / Stashes
'crafting.lua', 'crafting.lua',
'shops.lua',
'stashcontrol.lua', 'stashcontrol.lua',
-- Kind of "other" -- Kind of "other"
@@ -76,14 +175,32 @@ for _, v in pairs({ -- This is a specific load order
'scaleEntity.lua', 'scaleEntity.lua',
'vehicles.lua', 'vehicles.lua',
'effects.lua', 'effects.lua',
'versioncheck.lua'
--'warmenu.lua',
-- Do version check last
'_scriptversioncheck.lua'
}) do }) do
if debugMode then if debugMode then
print("^5Loading^7: 'jim_bridge/shared/"..v.."' ^2into ^7'"..GetCurrentResourceName().."' ...") --print("^5Loading^7: 'jim_bridge/shared/"..v.."' ^2into ^7'"..GetCurrentResourceName().."' ...")
end end
local fileLoader = assert(load(LoadResourceFile('jim_bridge', ('shared/'..v)), ('@@jim_bridge/shared/'..v))) local fileLoader = assert(load(LoadResourceFile('jim_bridge', ('shared/'..v)), ('@@jim_bridge/shared/'..v)))
fileLoader() fileLoader()
if debugMode then if debugMode then
print("^5Success^7: ^2loaded file^7: 'jim_bridge/shared/"..v.."'!") print("^5CoreLoader^7: ^2loaded file^7: ^3"..(v):gsub("/", "^7/^3"):gsub("%.lua", "^7.lua").."^7")
end
end
if isStarted(QBInv) then
if not checkExportExists(QBInv, "HasItem") then
print("^6Bridge^7: ^2Can^7'^2t ^2find new QBInv export^7, ^2forcing ^1QBInvNew ^2to ^1false^7")
QBInvNew = false
end
end
if isStarted(PSInv) then
if not checkExportExists(PSInv, "HasItem") then
print("^6Bridge^7: ^2Can^7't ^2find new PSInv export^7, ^2forcing ^1QBInvNew ^2to ^1false^7")
QBInvNew = false
end end
end end

View File

@@ -0,0 +1,120 @@
local notifications = {}
local spacing = 60 -- vertical spacing between notifications
local activeDrawing = false -- flag for drawing loop state
if not HasStreamedTextureDictLoaded("timerbars") then
while not HasStreamedTextureDictLoaded("timerbars") do
RequestStreamedTextureDict("timerbars")
Wait(5)
end
end
local notifTypes = {
success = "✔️",
error = "",
warning = "⚠️",
police = "🚓",
ambulance = "🚑",
}
function gtaNotify(title, message, emoji, src)
local notif = {
title = title,
message = message,
emoji = notifTypes[emoji] or "",
state = "enter",
startTime = GetGameTimer(),
progress = 0,
holdTime = 8000,
slideDuration = 100,
currentOffset = 0,
}
table.insert(notifications, notif)
-- Activate drawing loop if not already running
-- This allows it to be silent until the first notifcation is called, then the loop starts
if not activeDrawing then
activeDrawing = true
StartDrawingLoop()
end
end
-- Drawing loop as a separate controlled thread
function StartDrawingLoop()
CreateThread(function()
while #notifications > 0 do
local currentTime = GetGameTimer()
-- Update notifications vertical offset
for i, notif in ipairs(notifications) do
local target = (#notifications - i) * spacing
notif.currentOffset += (target - notif.currentOffset) * 0.1
end
for i = #notifications, 1, -1 do
local notif = notifications[i]
if notif.state == "enter" then
local elapsed = currentTime - notif.startTime
notif.progress = math.min(elapsed / notif.slideDuration, 1.0)
if notif.progress >= 1.0 then
notif.state = "hold"
notif.holdStart = currentTime
end
elseif notif.state == "hold" then
if currentTime - notif.holdStart >= notif.holdTime then
notif.state = "exit"
notif.exitStart = currentTime
end
elseif notif.state == "exit" then
local elapsed = currentTime - notif.exitStart
notif.progress = 1.0 - math.min(elapsed / notif.slideDuration, 1.0)
if notif.progress <= 0 then
table.remove(notifications, i)
goto continue
end
end
local startX, targetX = 1.0, 0.8
local posX = startX - (startX - targetX) * notif.progress
local posY = 0.05 + (notif.currentOffset / 1080)
-- Background sprite
DrawSprite("timerbars", "all_black_bg", posX + 0.11, posY + 0.025, 0.2, 0.053, 0.0, 255, 255, 255, 255)
-- Title text
local moveMessage = false
if not notif.title or notif.title == "" then
moveMessage = true
else
drawNotiText(8, 0.4, vec2(0.75, 0.975), notif.title, vec2(posX, posY))
end
-- Message text
drawNotiText(4, 0.3, vec2(0.75, 0.975), notif.message, vec2(posX, posY + (moveMessage and 0.015 or 0.03)))
-- Emoji
drawNotiText(0, 0.3, vec2(0.75, 0.995), notif.emoji, vec2(posX, posY + 0.015))
::continue::
end
Wait(0)
end
activeDrawing = false -- No notifications left, pause drawing
end)
end
function drawNotiText(font, scale, wrap, string, pos)
SetTextFont(font)
SetTextScale(scale, scale)
SetTextWrap(wrap.x, wrap.y)
SetTextJustification(2)
SetTextColour(255, 255, 255, 255)
SetTextOutline()
SetTextEntry("STRING")
AddTextComponentString(string)
DrawText(pos.x, pos.y)
end
RegisterNetEvent("jim-bridge:Notify", gtaNotify)
exports("Notify", gtaNotify)

121
ui_modules/skillcheck.lua Normal file
View File

@@ -0,0 +1,121 @@
local activeSkillCheck = false
function gtaSkillCheck()
if activeSkillCheck then return end
local result = false
local successes = 0
local barsRequired = 3
for bar = 1, barsRequired do
activeSkillCheck = true
local width, height = 0.2, 0.01
local x, y = 0.5, 0.8
-- Random highlighted zone
local highlightSize = math.random(10, 20) / 100
local highlightStart = math.random(10, 50) / 100
local highlightEnd = highlightStart + highlightSize
local highlightAlpha = 0
local cursorPos = 0.0
local cursorSpeed = 0.025
local movingRight = true
while activeSkillCheck do
Wait(0)
createScaleBars(x, y, width, height)
local pulse = (math.sin(GetGameTimer() / 250) + 1) / 2 -- Creates a pulsing effect
highlightAlpha = math.floor(150 + (pulse * 105)) -- Pulsing between 150 and 255 alpha
-- Draw highlighted zone (success area) with pulsing effect
DrawRect(x - width / 2 + (highlightStart + highlightSize / 2) * width, y, highlightSize * width, height+0.001, 93, 182, 229, highlightAlpha )
-- Draw moving cursor
DrawRect(x - width / 2 + cursorPos * width, y, 0.002, height + 0.01, 255, 255, 255, 255)
-- Move cursor
if movingRight then
cursorPos += cursorSpeed
if cursorPos >= 1.0 then movingRight = false end
else
cursorPos -= cursorSpeed
if cursorPos <= 0.0 then movingRight = true end
end
if IsControlJustPressed(0, 177) then -- Backspace to cancel
local displayTime = GetGameTimer() + 2000
PlaySoundFrontend(-1, 'Highlight_Cancel', 'DLC_HEIST_PLANNING_BOARD_SOUNDS', 1)
while GetGameTimer() < displayTime do
Wait(0)
createScaleBars(x, y, width, height)
DrawRect(x - width / 2 + (highlightStart + highlightSize / 2) * width, y, highlightSize * width, height+0.001, 228, 52, 52, 255)
DrawRect(x - width / 2 + cursorPos * width, y, 0.002, height + 0.01, 255, 255, 255, 255)
drawSuccessText(x, y, "Failed", 228, 52, 52)
end
return false
end
-- Check for keypress (E)
if IsControlJustPressed(0, 38) then
activeSkillCheck = false
result = cursorPos >= highlightStart and cursorPos <= highlightEnd
if result then
PlaySoundFrontend(-1, "YES", "HUD_FRONTEND_DEFAULT_SOUNDSET", true)
else
PlaySoundFrontend(-1, 'Highlight_Cancel', 'DLC_HEIST_PLANNING_BOARD_SOUNDS', 1)
end
local displayTime = GetGameTimer() + 2000
while GetGameTimer() < displayTime do
Wait(0)
createScaleBars(x, y, width, height)
-- Draw highlighted zone
DrawRect(x - width / 2 + (highlightStart + highlightSize / 2) * width, y, highlightSize * width, height+0.001, result and 93 or 228, result and 182 or 52, result and 229 or 52, 180)
-- Draw stationary cursor at result position
DrawRect(x - width / 2 + cursorPos * width, y, 0.002, height + 0.01, 255, 255, 255, 255)
-- Display result text
drawSuccessText(x, y, result and "Success" or "Failed", result and 114 or 228, result and 204 or 52, result and 144 or 52)
end
if result then
successes += 1
else
return false
end
end
end
end
activeSkillCheck = false
print("^5GTAUI^7: ^2Skill Check Result^7: ^3" .. successes .. "^7/^3" .. barsRequired.."^7")
return successes == barsRequired
end
function drawSuccessText(x, y, text, r, g, b)
SetTextFont(8)
SetTextScale(0.45, 0.45)
SetTextColour(r, g, b, 255)
SetTextDropshadow(0, 0, 0, 0, 255)
SetTextEdge(2, 0, 0, 0, 150)
SetTextDropShadow()
SetTextOutline()
SetTextCentre(true)
SetTextEntry("STRING")
SetTextCentre(true)
SetTextEntry("STRING")
AddTextComponentString(text)
DrawText(x, y + 0.03)
end
function createScaleBars(x, y, width, height)
-- Draw background box
DrawSprite("timerbars", "all_black_bg", x - (width / 4) - 0.006, y, (width / 2) + 0.08, height + 0.04, 0.0, 255, 255, 255, 255)
DrawSprite("timerbars", "all_black_bg", x + (width / 4) + 0.006, y, (width / 2) + 0.08, height + 0.04, 180.0, 255, 255, 255, 255)
-- Draw full bar (dark background)
DrawRect(x, y, width, height, 100, 100, 100, 255)
end
exports("skillCheck", gtaSkillCheck)

318
ui_modules/target.lua Normal file
View File

@@ -0,0 +1,318 @@
-- Global Key Table, defined once.
---
local KEY_TABLE = { 38, 29, 47, 23, 45, 159, 162, 163 }
-- Mapping of key codes to human-readable key names.
local Keys = {
[322] = "ESC", [288] = "F1", [289] = "F2", [170] = "F3", [166] = "F5",
[167] = "F6", [168] = "F7", [169] = "F8", [56] = "F9", [57] = "F10",
[243] = "~", [157] = "1", [158] = "2", [160] = "3", [164] = "4", [165] = "5",
[159] = "6", [161] = "7", [162] = "8", [163] = "9", [84] = "-", [83] = "=",
[177] = "BACKSPACE", [37] = "TAB",
[44] = "Q", [32] = "W", [38] = "E", [45] = "R", [245] = "T", [246] = "Y",
[303] = "U", [199] = "P",
[39] = "[", [40] = "]", [18] = "ENTER", [137] = "CAPS",
[34] = "A", [8] = "S", [9] = "D", [23] = "F", [47] = "G",
[74] = "H", [311] = "K", [182] = "L", [21] = "LEFTSHIFT",
[20] = "Z", [73] = "X", [26] = "C", [0] = "V", [29] = "B", [249] = "N",
[244] = "M", [82] = ",", [81] = "."
}
-- Tables for storing created targets.
local TextTargets = {} -- For fallback DrawText3D targets.
local targetEntities = {} -- For entity targets.
function createEntityTarget(entity, opts, dist)
startTargetLoop()
targetEntities[#targetEntities + 1] = entity
local entityCoords = GetEntityCoords(entity)
local existingTarget = nil
for _, target in pairs(TextTargets) do
if #(target.coords - entityCoords) < 0.01 then
existingTarget = target
break
end
end
if existingTarget then
for i = 1, #opts do
local key = KEY_TABLE[#existingTarget.options + i]
opts[i].key = key
existingTarget.buttontext[#existingTarget.buttontext + 1] = " ~b~[~w~" .. Keys[key] .. "~b~] ~w~" .. opts[i].label
existingTarget.options[#existingTarget.options + 1] = opts[i]
end
updateCachedText(existingTarget)
else
local tempText = {}
for i = 1, #opts do
opts[i].key = KEY_TABLE[i]
tempText[#tempText + 1] = " ~b~[~w~" .. Keys[opts[i].key] .. "~b~] ~w~" .. opts[i].label
end
TextTargets[entity] = {
coords = vec3(entityCoords.x, entityCoords.y, entityCoords.z),
buttontext = tempText,
options = opts,
dist = dist,
text = table.concat(tempText, "\n")
}
end
end
function createZoneTarget(data, opts, dist)
startTargetLoop()
local existingTarget = nil
for _, target in pairs(TextTargets) do
if #(target.coords - data[2]) < 0.01 then
existingTarget = target
break
end
end
if existingTarget then
for i = 1, #opts do
local key = KEY_TABLE[#existingTarget.options + i]
opts[i].key = key
existingTarget.buttontext[#existingTarget.buttontext + 1] = " ~b~[~w~" .. Keys[key] .. "~b~] ~w~" .. opts[i].label
existingTarget.options[#existingTarget.options + 1] = opts[i]
end
updateCachedText(existingTarget)
else
local tempText = {}
for i = 1, #opts do
opts[i].key = KEY_TABLE[i]
tempText[#tempText + 1] = " ~b~[~w~" .. Keys[opts[i].key] .. "~b~] ~w~" .. opts[i].label
end
TextTargets[data[1]] = {
coords = data[2],
buttontext = tempText,
options = opts,
dist = dist,
text = table.concat(tempText, "\n")
}
end
return data[1]
end
function createModelTarget(models, opts, dist)
startTargetLoop()
if type(models) ~= "table" then
models = { models }
end
local tempText = {}
for i = 1, #opts do
opts[i].key = KEY_TABLE[i]
tempText[#tempText + 1] = " ~b~[~w~" .. Keys[opts[i].key] .. "~b~] ~w~" .. opts[i].label
end
local keyStr = ""
for i, m in ipairs(models) do
keyStr = keyStr .. tostring(m) .. (i < #models and "_" or "")
end
local targetKey = "model_" .. keyStr
TextTargets[targetKey] = {
models = models,
buttontext = tempText,
options = opts,
dist = dist,
coords = vec3(0, 0, 0),
text = table.concat(tempText, "\n")
}
return targetKey
end
function removeEntityTarget(entity)
TextTargets[entity] = nil
end
function removeZoneTarget(target)
TextTargets[target] = nil
end
function removeModelTarget(model)
TextTargets[model] = nil
end
exports("createEntityTarget", createEntityTarget)
exports("createZoneTarget", createZoneTarget)
exports("createModelTarget", createModelTarget)
exports("removeEntityTarget", removeEntityTarget)
exports("removeZoneTarget", removeZoneTarget)
exports("removeModelTarget", removeModelTarget)
-------------------------------------------------------------
-- Fallback: DrawText3D Targets (Experimental)
-------------------------------------------------------------
local started = false
function startTargetLoop()
if started then return end
Config = {
System = {
}
}
started = true
local fileLoader = assert(load(LoadResourceFile("jim_bridge", ('starter.lua')), ('@@jim_bridge/starter.lua')))
fileLoader()
-- Model Entity Refresher
CreateThread(function()
while true do
local pedCoords = GetEntityCoords(PlayerPedId())
for _, target in pairs(TextTargets) do
if target.models then
for _, model in ipairs(target.models) do
local entity = GetClosestObjectOfType(pedCoords.x, pedCoords.y, pedCoords.z, target.dist, model, false, false, false)
if entity and entity ~= 0 then
target.entity = entity
target.coords = GetEntityCoords(entity)
break
end
end
end
end
Wait(3000) -- Refresh every 3s
end
end)
-- Main Target Loop
CreateThread(function()
while true do
local ped = PlayerPedId()
local pedCoords = GetEntityCoords(ped)
local camCoords = GetGameplayCamCoord()
local camRot = GetGameplayCamRot(2)
local camForward = RotationToDirection(camRot)
local closestTarget, closestDist, targetEntity = nil, math.huge, nil
for _, target in pairs(TextTargets) do
local coords = target.coords
if coords then
local dist = #(pedCoords - coords)
if dist <= target.dist then
local normVec = normalizeVector(coords - camCoords)
local dot = camForward.x * normVec.x + camForward.y * normVec.y + camForward.z * normVec.z
if dot > 0.5 and dist < closestDist then
closestTarget = target
closestDist = dist
targetEntity = target.entity
end
end
end
end
for _, target in pairs(TextTargets) do
if not target.coords then goto continue end
local dist = #(pedCoords - target.coords)
if dist > target.dist then goto continue end
local isClosest = (target == closestTarget)
for i, opt in ipairs(target.options) do
if IsControlJustPressed(0, opt.key) and isClosest then
if (not target.canInteract or target.canInteract()) and
(not opt.item or hasItem(opt.item)) and
(not opt.job or hasJob(opt.job, nil)) then
if opt.onSelect then opt.onSelect(targetEntity) end
if opt.action then opt.action(targetEntity) end
end
end
end
local baseZ, lineHeight = target.coords.z + 1.0, -0.16
local lineOffset = 0
for i, opt in ipairs(target.options) do
if (not target.canInteract or target.canInteract()) and
(not opt.item or hasItem(opt.item)) and
(not opt.job or hasJob(opt.job, nil)) then
DrawText3D(vec3(target.coords.x, target.coords.y, baseZ + lineHeight * lineOffset), target.buttontext[i], isClosest)
lineOffset = lineOffset + 1
end
end
::continue::
end
Wait(1) -- Throttled
end
end)
end
function DrawText3D(coord, text, highlight)
SetTextScale(0.30, 0.30)
SetTextFont(0)
SetTextProportional(1)
SetTextColour(255, 255, 255, 215)
SetTextEntry("STRING")
SetTextCentre(true)
local totalLength = string.len(text)
local textMaxLength = 99 -- max 99
local text = totalLength > textMaxLength and text:sub(1, totalLength - (totalLength - textMaxLength)) or text
AddTextComponentString(highlight and text:gsub("%~w~", "~y~") or text)
SetDrawOrigin(coord.x, coord.y, coord.z, 0)
DrawText(0.0, 0.0)
local count, length = GetLineCountAndMaxLength(text)
local padding = 0.005
local heightFactor = (count / 43) + padding
local weightFactor = (length / 150) + padding
local height = (heightFactor / 2) - padding / 1
local width = (weightFactor / 2) - padding / 1
DrawRect(0.0, height, width, heightFactor, 0, 0, 0, 150)
ClearDrawOrigin()
end
--- Calculates the number of lines and the maximum line length from the given text.
---
--- @param text string The text to analyze.
--- @return number, number The line count and maximum line length.
---
--- @usage
--- ```lua
--- local count, maxLen = GetLineCountAndMaxLength("Hello World")
--- ```
function GetLineCountAndMaxLength(text)
local lineCount, maxLength = 0, 0
for line in text:gmatch("[^\n]+") do
lineCount += 1
local lineLength = string.len(line)
if lineLength > maxLength then
maxLength = lineLength
end
end
if lineCount == 0 then lineCount = 1 end
return lineCount, maxLength
end
function RotationToDirection(rot)
local adjust = math.pi / 180
return vec3(
-math.sin(adjust * rot.z) * math.abs(math.cos(adjust * rot.x)),
math.cos(adjust * rot.z) * math.abs(math.cos(adjust * rot.x)),
math.sin(adjust * rot.x)
)
end
function normalizeVector(vec)
local len = math.sqrt(vec.x^2 + vec.y^2 + vec.z^2)
if len ~= 0 then
return vec3(vec.x / len, vec.y / len, vec.z / len)
else
return vec3(0, 0, 0)
end
end
-- Helper to update cached text.
function updateCachedText(target)
target.text = table.concat(target.buttontext, "\n")
end

View File

@@ -1 +1,6 @@
1.2 2.0.17
- Fix progressbars getting stuck on ox_lib
- #BlameMcklean for this one
https://github.com/jimathy/jim_bridge