This commit is contained in:
Luke committed 2023-06-04 15:15:21 +02:00
1 parent 3cebaf7fa5
commit b5eba8423f
229 files changed
+6238 -10690

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
import '../index.css';
export default function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />;
}
+11
View File
@@ -0,0 +1,11 @@
{
"index": "Introduction",
"guides": "Guides",
"oxmysql": "OxMySQL",
"ox_lib": "Ox Lib",
"support": {
"title": "Support Us",
"type": "page",
"href": "https://overextended.vercel.app/#support-our-team"
}
}
+6
View File
@@ -0,0 +1,6 @@
Git is a version control system, allowing changes to be effectively tracked, merged, and reverted.
As our resources are hosted on GitHub, it can be incredibly useful to learn how to create your own repository to track changes and keep up-to-date. If you plan on making your own changes to our resources, this will allow you to keep your own changes and prevent loss of data.
- Refer to [GitHub's guide to setting up Git](https://docs.github.com/en/get-started/quickstart/set-up-git#setting-up-git).
- You can use a Git GUI client like [GitKraken](https://www.gitkraken.com/) to improve your workflow and more easily maintain changes.
+9
View File
@@ -0,0 +1,9 @@
---
title: Node.js
---
Node.js is a JavaScript runtime and is used for building applications. In the context of FiveM it is necessary to bundle resources into a single package that can be ran on both the server and client.
- [Download](https://nodejs.org) and install the LTS version of Node.js.
- Open a command-line terminal (e.g. Terminal, Command Prompt).
- Enter `node --version` to confirm successful installation.
+24
View File
@@ -0,0 +1,24 @@
---
title: pnpm
---
pnpm is a fast and disk space efficient package manager, serving as an alternative to npm and yarn.
- Ensure you have [installed Node.js](./nodejs).
- Open a command-line terminal (e.g. Terminal, Command Prompt).
- Enter `npm install -g pnpm` to globally install the package.
- You can install dependencies with pnpm using `pnpm i`.
You can reference `package.json` files for available scripts, i.e.
```json
"scripts": {
"start": "vite",
"watch": "vite build --watch",
"build": "tsc && vite build",
"preview": "vite preview",
"format": "prettier --write \"./src/**/*.{ts,tsx,css}\""
},
```
Using the example above `pnpm build` will run the build script for the given package.
+20
View File
@@ -0,0 +1,20 @@
---
title: Introduction
---
import DonateLink from '@components/DonateLink';
Here you can find all of the official documentation for resources developed by the Overextended team.
If you feel like the documentation is lacking in some department then feel free to go onto that page and click the "Edit this page" at the bottom and submit a Pull Request.
## Support our team
Our projects will always remain free and open-source, with our core developers working voluntarily.
If you love what we do and want to help us continue, why not show your appreciation with a donation?
<div className="mt-2 flex flex-wrap justify-evenly gap-4">
<DonateLink image="https://avatars.githubusercontent.com/u/65407488?v=4" name="Linden" kofiName="thelindat" />
<DonateLink image="https://avatars.githubusercontent.com/u/39926192?v=4" name="Luke" kofiName="lukewastaken" />
<DonateLink image="https://avatars.githubusercontent.com/u/31368547?v=4" name="DokaDoka" kofiName="dokadoka" />
</div>
+123
View File
@@ -0,0 +1,123 @@
import { Steps, Tabs, Tab } from 'nextra-theme-docs';
import { Callout } from 'nextra/components';
import ResourceLinks from '@components/resource-links';
import { NpmButton } from '@components/button';
<ResourceLinks repo="https://github.com/overextended/ox_core" />
An experimental framework for FiveM. Limited support and breaking changes guaranteed.
<Callout type="warning">
This resource does not have a stable (v1.0) release; breaking changes are likely.
Documentation may not be kept updated in some cases.
</Callout>
## Installation
<Callout type="info">
We **strongly** recommend referring to [Guides](../guides) for setting up Git, Node.js, and pnpm.
</Callout>
<Steps>
### Install all resource dependencies.
- [oxmysql](../oxmysql)
- [ox_lib](../ox_lib/)
- [fivem-appearance](https://github.com/pedr0fontoura/fivem-appearance)
- [ox_appearance](https://github.com/overextended/ox_appearance)
### Download a [release](https://github.com/overextended/ox_core/releases) or build the source code.
```bash
git clone https://github.com/overextended/ox_core.git
cd ox_core/web
pnpm i
pnpm build
```
### Install optional dependencies.
These resources aren't required but provide additional functionality.
- [ox_inventory](../ox_inventory/)
- [npwd](https://github.com/project-error/npwd)
- [pefcl](https://github.com/project-error/pefcl)
### (Optional) Configure pefcl
If using it with ox_inventory, open `pefcl/config.json` and enable framework integration.
```json
"frameworkIntegration": {
"enabled": true,
"resource": "ox_inventory",
"syncInitialBankBalance": false
},
```
</Steps>
## Importing into resources
### Lua
Lua imports can be defined as part of fxmanifest, or loaded with the load function.
<Tabs items={['fxmanifest', 'load']}>
<Tab>
```lua
client_scripts {
'@ox_core/imports/client.lua',
'client/main.lua',
}
server_scripts {
'@oxmysql/lib/MySQL.lua',
'@ox_core/imports/server.lua',
'server/main.lua',
}
```
</Tab>
<Tab>
```lua
local file = ('imports/%s.lua'):format(IsDuplicityVersion() and 'server' or 'client')
local import = LoadResourceFile('ox_core', file)
local chunk = assert(load(import, ('@@ox_core/%s'):format(file)))
chunk()
```
</Tab>
</Tabs>
### JavaScript
To use ox_core with your JS/TS resources you'll need to use our npm package, allowing you to import core functions with full type and intellisense support.
<NpmButton link="https://www.npmjs.com/package/@overextended/ox_core" />
## Config
Resource configuration is handled using [convars](https://docs.fivem.net/docs/scripting-reference/convars/).
```bash
# Players must have a valid identifier to join the server. Used to fetch userid from the database.
set ox:primaryIdentifier "fivem"
# Set the number of active characters a user can have registered.
setr ox:characterSlots 5
# Enables debug and development features. Should only be used in a development environment.
setr ox:debug 0
# Disable death system handle by core.
setr ox:deathSystem 0
# Disable the spawn selection.
setr ox:spawnSelect 0
```
+17
View File
@@ -0,0 +1,17 @@
When ox_core is imported into a resource it will create the `player` global.
If `player` is nil, then the client has not yet selected a character and spawned.
**Example:**
```lua
print(json.encode(player, { indent = true }))
```
- player?: `table`
- name: `string`
- firstname: `string`
- lastname: `string`
- userid: `number`
- charid: `number`
- groups: `table`
- gender: `string`
+38
View File
@@ -0,0 +1,38 @@
---
title: Callbacks
---
### ox:getStatus
```lua
lib.callback.await('ox:getStatus', delay, targetId, statusName)
```
- delay: `number`
- targetId: `number`
- The server id for the player to get statuses for.
- statusName?: `string`
- The name of the status (i.e. hunger). Can be omitted to return all statuses.
### ox:getLicense
```lua
lib.callback.await('ox:getLicense', delay, licenseName, targetId)
```
- delay: `number`
- licenseName: `string`
- The name of the license to get data for. Can be omitted to return all licenses.
- targetId?: `number`
- The server id to get license data for, defaulting to the current player.
### ox:getNearbyVehicles
```lua
lib.callback.register('ox:getNearbyVehicles', function(radius)
```
Returns an array of vehicle netids within a given radius of the player's location.
- radius?: `number`
- The radius from the player's location to return vehicles.
+55
View File
@@ -0,0 +1,55 @@
---
title: Events
---
## Client events
### ox:playerLoaded
Triggered once the player has selected a character and spawned.
```lua
AddEventHandler('ox:playerLoaded', function(data) end)
```
### ox:playerLogout
Triggered when the player enters character selection if they were previously playing a character.
```lua
AddEventHandler('ox:playerLogout', function() end)
```
### ox:statusTick
Triggered every 1000ms interval, when status values are updated internally.
```lua
AddEventHandler('ox:statusTick', function(statuses) end)
```
## Networked events
### ox:setGroup
Triggered when the player's grade in a group is modified on the server with `player.setGroup`.
```lua
RegisterNetEvent('ox:setGroup', function(group, grade) end)
```
### ox:licenseAdded
Triggered when the player has been granted a license.
```lua
RegisterNetEvent('ox:licenseAdded', function(name) end)
```
### ox:licenseRemoved
Triggered when the player's license is revoked.
```lua
RegisterNetEvent('ox:licenseRemoved', function(name) end)
```
+89
View File
@@ -0,0 +1,89 @@
import { Tabs, Tab } from 'nextra-theme-docs';
## Ox.GetPlayer
Return an instance of OxPlayer for the given player source.
<Tabs items={['Lua', 'JS']}>
<Tab>
```lua
local player = Ox.GetPlayer(source)
print(json.encode(player, { indent = true }))
```
</Tab>
<Tab>
```ts
import { GetPlayer } from '@overextended/ox_core/server';
const player = GetPlayer(source);
console.log(JSON.stringify(player));
```
</Tab>
</Tabs>
## Ox.GetPlayerByFilter
Return the first OxPlayer that matches the filter properties.
<Tabs items={['Lua', 'JS']}>
<Tab>
```lua
local filter = { phoneNumber = '556-560-6609' }
local player = Ox.GetPlayerByFilter(filter)
print(json.encode(player, { indent = true }))
```
</Tab>
<Tab>
```ts
import { GetPlayerByFilter } from '@overextended/ox_core/server';
const filter = { phoneNumber: '556-560-6609' };
const player = GetPlayerByFilter(filter);
console.log(JSON.stringify(player));
```
</Tab>
</Tabs>
## Ox.GetPlayers
Returns an array containing all players. Methods will not be applied if the first argument is false.
Players can be filtered to only return players that match the given properties, or groups.
<Tabs items={['Lua', 'JS']}>
<Tab>
```lua
-- Get an array containing all players in the police or sheriff groups, with grade 3 or higher.
local filter = { groups = {['sheriff'] = 3, ['police'] = 3} })
local players = Ox.GetPlayers(usemetatable, filter)
for i = 1, #players do
local player = players[i]
print(json.encode(player, { indent = true }))
end
```
</Tab>
<Tab>
```ts
import { GetPlayers } from '@overextended/ox_core/server';
// Get an array containing all players in the police or sheriff groups, with grade 3 or higher.
const filter = { groups: { sheriff: 3, police: 3 } })
const players = GetPlayers(useclass, filter);
for (let i = 0; i < players.length; i++) {
const player = players[i];
console.log(JSON.stringify(player));
}
```
</Tab>
</Tabs>
+71
View File
@@ -0,0 +1,71 @@
---
title: Events
---
## Server events
### ox:playerLoaded
Triggered after a player has selected a character.
```lua
AddEventHandler('ox:playerLoaded', function(source, userid, charid) end)
```
### ox:setGroup
Triggered when a player's grade in a group is modified with `player.setGroup`.
```lua
AddEventHandler('ox:setGroup', function(source, group, grade) end)
```
### ox:playerLogout
Triggered when a player logs out from their current character or disconnects from the server.
```lua
AddEventHandler('ox:playerLogout', function(source, userid, charid) end)
```
### ox:characterDeleted
Triggered when a player has deleted a character.
```lua
AddEventHandler('ox:characterDeleted', function(source, userid, charid) end)
```
### ox:licenseAdded
Triggered when a player has been granted a license.
```lua
AddEventHandler('ox:licenseAdded', function(source, name) end)
```
### ox:licenseRemoved
Triggered when a player's license is revoked.
```lua
AddEventHandler('ox:licenseRemoved', function(source, name) end)
```
## Networked events
### ox:playerDeath
Triggered on player death and revival.
```lua
RegisterNetEvent('ox:playerDeath', function(isDead) end)
```
### ox:setPlayerInService
Can be triggered to set a player as "in service" for a specific group they are a member of.
```lua
RegisterNetEvent('ox:setPlayerInService', function(group) end)
```
+181
View File
@@ -0,0 +1,181 @@
---
title: Methods
---
import { Tabs, Tab } from 'nextra-theme-docs';
These functions are inherited from the [Player class](../Server/).
## player.set
Update the player's metadata, optionally syncing it with the client.
```lua
player.set(key, value, replicated)
```
- key: `string`
- value: `any`
- replicated?: `boolean`
## player.get
Get a value from the player's metadata, or omit the argument to get all metadata.
```lua
player.get(key)
```
- key?: `string`
## player.getState
Return the player's statebag.
```lua
player.getState()
```
## player.getCoords
Return the player's position.
```lua
player.getCoords()
```
## player.setGroup
Updates the player's grade for the given group. Any value below 1 will remove the group from the player.
```lua
player.setGroup(group, grade)
```
- group: `string`
- grade?: `number`
## player.getGroup
Returns the player's current grade for a given group.
```lua
player.getGroup()
```
## player.getGroups
Returns an object of all groups the player is in, with the current grade as the value.
```lua
player.getGroups()
```
## player.hasGroup
Check if the player is a member of a given group, and returns the matching group name and grade.
The filter can be a string, array, or object where key is the group, and value is the minimum grade.
```lua
player.hasGroup(filter)
```
- filter: `string | string[] | { [string]: number }`
## player.setStatus
Set the current value for a status (i.e. hunger, thirst).
```lua
player.setStatus(name, value)
```
- name: string
- value: number
## player.addStatus
Add the given amount to the total value for a status (i.e. hunger, thirst).
```lua
player.addStatus(name, value)
```
- name: string
- value: number
## player.removeStatus
Remove the given amount from the total value for a status (i.e. hunger, thirst).
```lua
player.removeStatus(name, value)
```
- name: string
- value: number
## player.getLicenses
Get all licenses for the player.
```lua
player.getLicenses()
```
## player.getLicense
Get the license of the given name for the player, as an object containing license information.
```lua
player.getLicense(name)
```
- name: string
## player.addLicense
Grants a license to the player and triggers 'ox:licenseAdded' on the server and client.
```lua
player.addLicense(name)
```
- name: string
## player.removeLicense
Revokes a license from the player and triggers 'ox:licenseRemoved' on the server and client.
```lua
player.removeLicense(name)
```
- name: string
## player.getPlayersInScope
Return an array of all player id's inside the player's scope.
```lua
player.getPlayersInScope()
```
## player.isPlayerInScope
Check if the given source is inside the player's scope.
```lua
player.isPlayerInScope(target)
```
- target: `number`
## player.triggerScopedEvent
```lua
player.triggerScopedEvent(eventName, ...)
```
- eventName: `string`
- ...?: `any[]`
+54
View File
@@ -0,0 +1,54 @@
---
title: Server
sidebar_position: 1
---
## Ox.GetVehicle
Return an instance of OxVehicle for the given entity.
```lua
local vehicle = Ox.GetVehicle(entity)
print(json.encode(vehicle, { indent = true }))
```
## Ox.GetVehicles
Returns an array containing all vehicles. Methods will not be applied if the first argument is false.
```lua
local vehicles = Ox.GetVehicles(usemetatable)
for i = 1, #vehicles do
local vehicle = vehicles[i]
print(json.encode(vehicle, { indent = true }))
end
```
## Ox.CreateVehicle
Spawns a vehicle and returns the instance of OxVehicle.
If the first argument is a number, it will attempt to spawn a vehicle from the database with a matching id.
```lua
local vehicleId = MySQL.scalar.await('SELECT id FROM vehicles WHERE owner = ? LIMIT 1', { player.charid })
if vehicleId then
local coords = player.getCoords()
local vehicle = Ox.CreateVehicle(vehicleId, vector3(coords.x, coords.y + 1.0, coords.z) , GetEntityHeading(player.ped))
if vehicle then
print(json.encode(vehicle, { indent = true }))
end
end
```
If the first argument is a table and the owner property is a number, or nil, the vehicle will be added to the database.
Setting the owner as false creates a non-persistent vehicle.
```lua
local vehicle = Ox.CreateVehicle({
model = 'sultanrs',
owner = player.charid,
}, player.getCoords(), GetEntityHeading(player.ped))
```
@@ -0,0 +1,14 @@
---
title: Callbacks
---
### ox:getNearbyVehicles
Get all vehicles within range of the target player.
```lua
lib.callback.await('ox:getNearbyVehicles', playerId, radius)
```
- playerId: `number`
- radius?: `number`
+96
View File
@@ -0,0 +1,96 @@
---
title: Methods
---
These functions are inherited from the [Vehicle class](../Server/).
## vehicle.set
Sets the vehicle's metadata for key to the given value.
```lua
vehicle.set(key, value)
```
- key: `string`
- value: `any`
## vehicle.get
Get a value from the vehicles's metadata, or omit the argument to get all metadata.
```lua
vehicle.get(key)
```
- key?: `string`
## vehicle.getState
Return the vehicle's statebag.
```lua
vehicle.getState()
```
## vehicle.getCoords
Return the vehicle's position.
```lua
vehicle.getCoords()
```
## vehicle.despawn
Despawns the vehicle but doesn't save it or update the stored value.
## vehicle.delete
Remove the vehicle from the database and despawns the entity.
```lua
vehicle.delete()
```
## vehicle.setStored
Updates the vehicle's "stored" value and optionally despawns it.
```lua
vehicle.setStored(value, despawn)
```
- value?: `string`
- despawn?: `boolean`
## vehicle.setOwner
Sets the vehicle's owner, matching a charid or nil to set it as unowned.
```lua
vehicle.setOwner(owner)
```
- owner?: `number`
## vehicle.setGroup
Sets the vehicle's group, which can be used for garage restrictions, unowned group vehicles, etc.
```lua
vehicle.setGroup(group)
```
- group?: `string`
## vehicle.setPlate
Sets the vehicle's plate, used in the database to ensure uniqueness. Does not necessarily match the plate property (i.e. fake plates).
Plate is always formatted to 8 characters.
```lua
vehicle.setPlate(plate)
```
- plate: `string`
+7
View File
@@ -0,0 +1,7 @@
label: Ox Core
collapsible: true
collapsed: true
link:
type: generated-index
description: An experimental framework for FiveM. Limited support and breaking changes guaranteed.
position: 4
+46
View File
@@ -0,0 +1,46 @@
# Concepts
We'll try to explain some technical but core concepts used in ox_core here.
## Classes
Lua doesn't have support for true classes, but rather prototype-based inheritance.
A prototype can hold its own variables and methods, which another object (an instance) can reference or call.
```lua
-- OxPlayer will hold all inherited variables and methods for instances of it.
local OxPlayer = {}
-- Sets the "index metamethod" of OxPlayer to reference itself.
-- This is how instances will know to look up the table.
OxPlayer.__index = OxPlayer
-- Set a new metatable on the table passed to the function.
-- The important code here is { __index = OxPlayer }.
function OxPlayer.new(player)
return setmetatable(player, OxPlayer)
end
-- Using the `:` syntax will pass the object as the first parameter.
function OxPlayer:getUsername()
return self.username
end
-- Create our instance of OxPlayer.
local player = OxPlayer.new({
username = 'Bob the Builder'
})
-- This is the same as OxPlayer.getUsername(player).
local username = player:getUsername()
-- 'Bob the Builder'
print(username)
```
When using the imported classes in your resources you can treat the methods as if you are calling a regular function.
```lua
local player = Ox.GetPlayer(playerId)
print(player.getUsername())
```
+53
View File
@@ -0,0 +1,53 @@
import { Steps } from 'nextra-theme-docs';
import { Callout } from 'nextra/components';
import ResourceLinks from '@components/resource-links';
<ResourceLinks repo="https://github.com/overextended/ox_doorlock" />
A door management resource that can be used standalone or alongside ox_core, qb-core, and es_extended.
## Installation
<Callout type="info">
We **strongly** recommend referring to [Guides](../guides) for setting up Git, Node.js, and pnpm.
</Callout>
<Steps>
### Install all resource dependencies.
- [oxmysql](../oxmysql)
- [ox_lib](../ox_lib/)
### Download a [release](https://github.com/overextended/ox_doorlock/releases) or build the source code.
```bash
git clone https://github.com/overextended/ox_doorlock.git
cd ox_doorlock/web
pnpm i
pnpm build
```
### Install optional dependencies.
These resources aren't required but provide additional functionality.
- [ox_target](../ox_target/) or [qb-target](https://github.com/qbcore-framework/qb-target)
</Steps>
## Opening the UI
If you have installed and started the resource, you can use `/doorlock` to open the UI.
- If the cursor is displayed but not the UI then you have not built it.
- You may not be authorised to use the command.
- Enter `test_ace player.1 command.doorlock` in the server console (replace 1 with your server id).
## Convert doors
Door configuration files written for nui_doorlock (and its fork, qb-doorlock) can be automatically added to your MySQL database.
- Any files with the `.lua` extension placed in the `ox_doorlock/convert` directory will be read on resource start.
- Conversion cannot be guaranteed, especially if the config was not written for nui_doorlock.
+15
View File
@@ -0,0 +1,15 @@
## pickClosestDoor
Attempt to pick the lock of the closest door. Dependant on server-side checks and may fail.
```lua
exports.ox_doorlock:pickClosestDoor()
```
## useClosestDoor
Interact with the closest door. Dependant on server-side checks and may fail.
```lua
exports.ox_doorlock:useClosestDoor()
```
+31
View File
@@ -0,0 +1,31 @@
# Triggers
These events are safe to trigger and handle in other scripts.
## ox_doorlock:setState
Can be triggered to lock or unlock a door.
```
TriggerEvent('ox_doorlock:setState', doorId, state)
```
- doorId: `number`
- state: `0` or `1`
# Handlers
These events shouldn't be triggered by any other scripts.
## ox_doorlock:stateChanged
Triggered when a doors state is updated.
```lua
AddEventHandler('ox_doorlock:stateChanged', function(source, doorId, state, usedItem) end)
```
- source: `number` or `nil`
- doorId: `number`
- state: `0` or `1`
- usedItem: `string` or `false`
+31
View File
@@ -0,0 +1,31 @@
Gets data for a door with the given id, matching the id for the database entry.
## getDoor
```lua
exports.ox_doorlock:getDoor(id)
```
### Parameters
- id: `number`
### Returns
- `table`
Gets data for a door with the given name, matching the name for the database entry.
## getDoorFromName
```lua
exports.ox_doorlock:getDoorFromName(name)
```
### Parameters
- name: `string`
### Returns
- `table`
+54
View File
@@ -0,0 +1,54 @@
---
title: Door settings
---
## General
- Door name
- Used to easily identify the door.
- Passcode
- Door can be unlocked by anybody by using the code or phrase.
- Autolock interval
- Door will be locked after x seconds.
- Interact distance
- Door can only be used when within x metres.
- Door rate
- Door movement speed for sliding/garage/automatic doors, or swinging doors when locked.
- Locked
- Sets the door as locked by default.
- Double
- Door is a set of two doors, controlled together.
- Automatic
- Sliding/garage/automatic door.
- Lockpick
- Door can be lockpicked when interacting with a targeting resource.
- Hide UI
- No indicators (i.e. icon, text) will display on the door.
## Characters
- Character Id
- Character identifier used by a framework (i.e. player.charid, xPlayer.identifier, Player.CitizenId).
## Groups
- Group
- Framework dependent, referring to jobs, gangs, etc.
- Grade
- The minimum grade to allow access for the group (0 to allow all).
## Items
- Item
- Name of the item.
- Metadata type
- Requires metadata support (i.e. ox_inventory) to check slot.metadata.type
## Lockpick
- Difficulty
- Sets the skillcheck difficulty (see [docs](https://overextended.github.io/docs/ox_lib/Interface/Client/skillcheck)).
- Area size
- Custom difficulty area size.
- Speed multiplier
- Custom difficulty idicator speed.
+39
View File
@@ -0,0 +1,39 @@
import { Steps } from 'nextra-theme-docs';
import ResourceLinks from '@components/resource-links';
<ResourceLinks repo="https://github.com/overextended/ox_fuel" />
A simple fuel resource meant to replace LegacyFuel or serve as a showcase for using petrol cans as an item.
## Installation
<Steps>
### Install all resource dependencies.
- [ox_lib](../ox_lib/)
- [ox_inventory](../ox_inventory/)
### Download a [release](https://github.com/overextended/ox_fuel/releases) or clone the source code.
```bash
git clone https://github.com/overextended/ox_fuel.git
```
### Install optional dependencies.
These resources aren't required but provide additional functionality.
- [ox_target](../ox_target/)
</Steps>
## Get vehicle fuel amount
```lua
local fuel = Entity(vehicleId).state.fuel
```
## Set vehicle fuel amount
```lua
Entity(vehicleId).state.fuel = fuelAmount
```
+27
View File
@@ -0,0 +1,27 @@
## setMoneyCheck
Override the built-in money check.
```lua
exports.ox_fuel:setMoneyCheck(method)
```
### Parameters
- method: `function(): number`
### Example
```lua
exports.ox_fuel:setMoneyCheck(function()
local accounts = ESX.GetPlayerData().accounts
for i = 1, #accounts do
if accounts[i].name == 'bank' then
return accounts[i].money
end
end
return 0
end)
```
+30
View File
@@ -0,0 +1,30 @@
## setPaymentMethod
Override the built-in payment method.
```lua
exports.ox_fuel:setPaymentMethod(method)
```
### Parameters
- method: `function(): boolean?`
### Example
```lua
exports.ox_fuel:setPaymentMethod(function(playerId, amount)
local xPlayer = ESX.GetPlayerFromId(playerId)
local bankAmount = xPlayer.getAccount('bank').money
if bankAmount >= amount then
xPlayer.removeAccountMoney('bank', amount)
return true
end
TriggerClientEvent('ox_lib:notify', source, {
type = 'error',
description = locale('not_enough_money', amount - bankAmount)
})
end)
```
+239
View File
@@ -0,0 +1,239 @@
import ResourceLinks from '@components/resource-links';
import { Steps, Tabs, Tab } from 'nextra-theme-docs';
import { Callout } from 'nextra/components';
<ResourceLinks repo="https://github.com/overextended/ox_inventory" />
A slot-based inventory with item metadata for "item uniqueness".
<Callout type="warning">
If you are replacing a built-in framework inventory there will be compatibility errors.
If you are unwilling or incapable of resolving incompatibilities, do not install this resource.
</Callout>
## Installation
<Callout type="info">
We **strongly** recommend referring to [Guides](../guides) for setting up Git, Node.js, and pnpm.
</Callout>
<Steps>
### Install all resource dependencies
- [oxmysql](../oxmysql)
- [ox_lib](../ox_lib/)
### Download a [release](https://github.com/overextended/ox_inventory/releases) or build the source code.
```bash
git clone https://github.com/overextended/ox_inventory.git
cd ox_inventory/web
pnpm i
pnpm build
```
### Install optional dependencies
These resources aren't required but provide additional functionality.
- [ox_target](../ox_target/)
### Resource start order
It's important for your resources to start in a logical order to prevent errors from missing dependencies.
```bash
start oxmysql # this should be one of the first resources
start ox_lib
start framework # the name of your framework (i.e. ox_core, es_extended, qb-core)
start ox_target
start ox_inventory
```
### Config
Resource configuration is handled using [convars](https://docs.fivem.net/docs/scripting-reference/convars/).
```bash
### Shared
# Activate specific event handlers and functions (supported: ox, esx, qb, nd)
setr inventory:framework "esx"
# Number of slots for player inventories
setr inventory:slots 50
# Maximum carry capacity for players, in grams (frameworks may override this)
setr inventory:weight 30000
# Integrated support for qtarget/ox_target stashes, shops, etc
# Note: qtarget is deprecated, a future update may drop support (ox_target only, or gated features)
setr inventory:target false
# Jobs with access to police armoury, evidence lockers, etc
setr inventory:police ["police", "sheriff"]
### Client
# The URL to load item images from
setr inventory:imagepath "nui://ox_inventory/web/images"
# Weapons will reload after reaching 0 ammo
setr inventory:autoreload false
# Blur the screen while accessing the inventory
setr inventory:screenblur true
# Default hotkeys to access primary and secondary inventories, and hotbar
setr inventory:keys ["F2", "K", "TAB"]
# Enable control action when inventory is open
setr inventory:enablekeys [249]
# Weapons must be aimed before shooting
setr inventory:aimedfiring false
# Show a list of all nearby players when giving items
setr inventory:giveplayerlist false
# Toggle weapon draw/holster animations
setr inventory:weaponanims true
# Toggle item notifications (add/remove)
setr inventory:itemnotify true
# Disable drop markers and spawn a prop instead
setr inventory:dropprops true
# Set the default model used for drop props
setr inventory:dropmodel "prop_med_bag_01b"
# Disarm the player if an unexpected weapon is in use (i.e. did not use the weapon item)
setr inventory:weaponmismatch true
# Ignore weapon mismatch checks for the given weapon type (e.g. ['WEAPON_SHOVEL', 'WEAPON_HANDCUFFS'])
setr inventory:ignoreweapons []
# Suppress weapon and ammo pickups
setr inventory:suppresspickups 1
### Server
# Compare current version to latest release on GitHub
set inventory:versioncheck true
# Stashes will be wiped after remaining unchanged for the given time
set inventory:clearstashes "6 MONTH"
# Discord webhook url, used for imageurl metadata content moderation (image embeds)
set inventory:webhook ""
# Logging via ox_lib (0: Disable, 1: Standard, 2: Include AddItem/RemoveItem, and all shop purchases)
set inventory:loglevel 1
# Item prices fluctuate in shops
set inventory:randomprices true
# Loot will randomly generate inside unowned vehicles and dumpsters
set inventory:randomloot true
# Minimum job grade to remove items from evidence lockers
set inventory:evidencegrade 2
# Trim whitespace from vehicle plates when checking owned vehicles
setr inventory:trimplate true
# Set the contents of randomly generated inventories
# [item name, minimum, maximum, loot chance]
set inventory:vehicleloot [
["cola", 1, 1],
["water", 1, 1],
["garbage", 1, 2, 50],
["panties", 1, 1, 5],
["money", 1, 50],
["money", 200, 400, 5],
["bandage", 1, 1]
]
set inventory:dumpsterloot [
["mustard", 1, 1],
["garbage", 1, 3],
["money", 1, 10],
["burger", 1, 1]
]
```
</Steps>
## Framework incompatibilities
- Any frameworks with their own built-in inventory, item, or weapon systems are expected to have compatibility issues.
- Money as an item may conflict with banking/account systems.
- You can sync these values with [server.syncInventory](https://github.com/overextended/ox_inventory/blob/aff8ef9e9ee3f93f177ce03b3f37895ff5781800/modules/bridge/nd/server.lua#L64-L77).
Refer to issue [#1297](https://github.com/overextended/ox_inventory/issues/1297) for known compatibility issues.
## Using an unsupported framework
If your framework does not have official support you'll have to implement it yourself.
If you're replacing an existing/built-in inventory system this may be complicated, but is a fairly simple task otherwise.
This setup is highly opinionated and rigid, so it's up to your own ability as a developer to make it work.
<Steps>
### Setup a bridge submodule
You'll want to set the target framework first - this could be the name, an acronym, or just "custom".
```bash
setr inventory:framework "custom"
```
Copy the `ox` directory from the [bridge](https://github.com/overextended/ox_inventory/tree/main/modules/bridge) directory and give it the name you used above.
The bare minimum functions and event handlers are added here, but you'll need to change them to match your framework; we can't provide any help here. You can refer to the other framework bridges if you need inspiration.
### Setup database references
Take a look at the [mysql](https://github.com/overextended/ox_inventory/blob/main/modules/mysql/server.lua) module. You'll need to reference your player/vehicle tables and id columns.
```lua
elseif shared.framework == 'custom' then
playerTable = 'characters' -- table storing player / character data
playerColumn = 'charid' -- primary key for identifying the character (i.e. identifier, citizenid, id)
vehicleTable = 'vehicles' -- table storing owned vehicle data
vehicleColumn = 'id' -- primary key for identifying the vehicle (i.e. plate, vin, id)
end
```
</Steps>
## ESX
- You will need a [compatible version of ESX Legacy](https://github.com/esx-framework/esx_core) (1.6.0 or higher).
- You can convert player inventories with `convertinventory esx`.
- All items in the database will be migrated to the internal item data.
- Always restart the resource when items are migrated!
## QBCore
<Callout type="warning">Support for QBCore is extremely limited, highly incompatible, and unlikely to improve.</Callout>
- You can use any "version" of qb-core that supports `QBCore.Functions.AddPlayerMethod`.
- You can convert player and vehicle inventories with `convertinventory qb`.
- All QB.Shared.Items will be migrated to the internal item data.
- Always restart the resource when items are migrated!
### Qbox Project
- [Qbox Project GitHub](https://github.com/Qbox-project/)
- [Qbox txAdmin Recipe](https://github.com/Qbox-project/txAdminRecipe)
Qbox is a fork of QBCore developed by former team members and contributors to QBCore.
- Improved security and performance of qb resources.
- Integrated support for ox_inventory, with improved compatibility.
- Support for ox_lib and ox_target.
+49
View File
@@ -0,0 +1,49 @@
# Client events
This is not a comprehensive list of events and is missing events intended for internal use only.
## Triggers
These events are safe to trigger and handle in other scripts.
### ox_inventory:disarm
Can be triggered to force the player to disarm.
```lua
TriggerClientEvent('ox_inventory:disarm', playerId, noAnim)
```
## Handlers
These events shouldn't be triggered by any other scripts.
### ox_inventory:updateInventory
Triggered after inventory slots have been updated, included on load.
Changes is a table containing all updated slot data indexed by slotId. Empty slots are "false".
```lua
AddEventHandler('ox_inventory:updateInventory', function(changes) end)
```
- changes: `table<number, table | false>`
### ox_inventory:currentWeapon
Triggered when a weapon is equipped or its metadata is altered.
```lua
AddEventHandler('ox_inventory:currentWeapon', function(weapon) end)
```
- weapon?: `table`
### ox_inventory:itemCount
Triggered when the amount of an item in the player's inventory is changed.
_Note: Not available for ESX, use esx:addInventoryItem or esx:removeInventoryItem._
```lua
AddEventHandler('ox_inventory:itemCount', function(itemName, totalCount) end)
```
+26
View File
@@ -0,0 +1,26 @@
# Server events
This is not a comprehensive list of events and is missing events intended for internal use only.
## Handlers
These events shouldn't be triggered by any other scripts.
### ox_inventory:openedInventory
Triggered after an inventory is opened by a player.
```lua
AddEventHandler('ox_inventory:openedInventory', function(playerId, inventoryId) end)
```
- playerId: `number`
- inventoryId: `string`
### ox_inventory:closeInventory
Triggered after an inventory is closed by a player.
```lua
AddEventHandler('ox_inventory:closeInventory', function(playerId, inventoryId) end)
```
+74
View File
@@ -0,0 +1,74 @@
---
title: ESX
---
import { Tabs, Tab } from 'nextra-theme-docs';
## Compatibility
Ox Inventory is a complete replacement for existing item, inventory, and weapon systems; it is inherently incompatible with ESX and any resources that rely on default behaviour.
- Loadouts do not exist and weapons are treated as items.
- Standard shops and stashes (i.e. esx_shops, esx_weaponshop, and esx_policejob).
- Resources that alter the default esx inventory or provide a ui (i.e. esx_trunkinventory, esx_inventoryhud).
## Installation
- Use a compatible version of [ESX Legacy](https://github.com/esx-framework/esx-legacy) (1.6.0+).
- Modify your `server.cfg`, starting ox_inventory immediately after es_extended.
```yaml
start oxmysql
start ox_lib
start es_extended
start qtarget
start ox_inventory
```
## Convert ESX inventory data
- Start the server and type `convertinventory esx` into the server console.
- Optionally, type `convertinventory esxproperty` into the server console.
- Restart the server once conversion is complete.
## Optional optimisation
All item related functions from xPlayer, such as `xPlayer.getInventoryItem`, have been modified for compatibility purposes; however they are considered deprecated.
The reasoning is fairly simple - there's now additional function references and overhead to consider. Fortunately, the new Inventory functions can be used directly and offer a great deal of improvements over the old ones.
You should read through the functions section for further information, but the following should give you a decent idea.
<Tabs items={["ESX", "Ox Inventory"]}>
<Tab>
```lua
if xPlayer.getInventoryItem('acetone').count > 2 and xPlayer.getInventoryItem('antifreeze').count > 4 and xPlayer.getInventoryItem('sudo').count > 9 then
xPlayer.removeInventoryItem("acetone", 3)
xPlayer.removeInventoryItem("antifreeze", 5)
xPlayer.removeInventoryItem("sudo", 10)
end
```
</Tab>
<Tab>
Add the following code somewhere in your resource to cache the exports metatable.
```lua
local ox_inventory = exports.ox_inventory
```
You will be able to reference any functions exposed through the export.
```lua
local items = ox_inventory:Search(source, 'count', {'acetone', 'antifreeze', 'sudo'})
if items and items.acetone > 2 and items.antifreeze > 4 and items.sudo > 9 then
ox_inventory:RemoveItem(source, 'acetone', 3)
ox_inventory:RemoveItem(source, 'antifreeze', 5)
ox_inventory:RemoveItem(source, 'sudo', 10)
end
```
</Tab>
</Tabs>
+89
View File
@@ -0,0 +1,89 @@
---
title: QBCore
---
import { Callout } from 'nextra/components';
import { Tabs, Tab } from 'nextra-theme-docs';
<Callout type="warning">
QBCore support is experimental and cannot work as a "drag and drop" solution due to many incompatibilities.
</Callout>
## Compatibility
Ox Inventory provides a complete suite of tools to replace the built-in items and inventory system from QBCore, and is not intended to be used with resources designed around it.
- Stashes used by qb-inventory and its forks do not work, but can _possibly_ be converted.
- Remove `qb-inventory` (or similar), or qb-core will not function properly.
- Remove `qb-shops` and `qb-weapons`, as they depend on `qb-inventory` and conflict.
- Weapon holstering and draw animations (like in `qb-smallresources`) may break our own methods.
## Qbox Project
Qbox is a fork of QBCore being developed by a team of former contributors and developers on QBCore. The team is focused on improving performance and security, as well as converting resources to support our resources (mainly ox_lib and ox_inventory).
We _strongly_ advise using Qbox as an alternative to QBCore.
- [Qbox Project GitHub](https://github.com/Qbox-project/)
- [Qbox Project Discord](https://discord.gg/AtbwBuJHN5)
## Installation
- Setup [qb-core](https://github.com/qbcore-framework) or [qbox](https://github.com/Qbox-project/qb-core).
- Edit your `server.cfg`.
- Add `setr inventory:framework "qb"` before starting your resources.
- Start ox_inventory immediately after qb-core.
### Convert QBCore
If you have existing player data, you will need to convert it to a compatible format.
- Start the server and type `convertinventory qb` into the server console.
- Restart the server once conversion is complete.
## Optional optimisation
All item related functions from Player, such as `Player.Functions.GetItemByName`, have been modified for compatibility purposes; however they are considered deprecated.
The reasoning is fairly simple - there's now additional function references and overhead to consider. Fortunately, the new Inventory functions can be used directly and offer a great deal of improvements over the old ones.
You should read through the functions section for further information, but the following should give you a decent idea.
<Tabs items={["QBCore", "Ox Inventory"]}>
<Tab>
```lua
local acetone = Player.Functions.GetItemByName('acetone')
local antifreeze = Player.Functions.GetItemByName('antifreeze')
local sudo = Player.Functions.GetItemByName('sudo')
if acetone?.amount > 2 and antifreeze?.amount > 4 and sudo?.amount > 9 then
Player.Functions.RemoveItem("acetone", 3)
Player.Functions.RemoveItem("antifreeze", 5)
Player.Functions.RemoveItem("sudo", 10)
end
```
</Tab>
<Tab>
Add the following code somewhere in your resource to cache the exports metatable.
```lua
local ox_inventory = exports.ox_inventory
```
You will be able to reference any functions exposed through the export.
```lua
local items = ox_inventory:Search(source, 'count', {'acetone', 'antifreeze', 'sudo'})
if items and items.acetone > 2 and items.antifreeze > 4 and items.sudo > 9 then
ox_inventory:RemoveItem(source, 'acetone', 3)
ox_inventory:RemoveItem(source, 'antifreeze', 5)
ox_inventory:RemoveItem(source, 'sudo', 10)
end
```
</Tab>
</Tabs>
@@ -0,0 +1,16 @@
---
keywords: ['hasitem']
---
Get the total item count for all items in the player's inventory with the given name and metadata.
```lua
exports.ox_inventory:GetItemCount(itemName, metadata, strict)
```
- itemName: `string`
- metadata?: `table`
- strict?: `boolean`
- Strictly match metadata properties, otherwise use partial matching.
**Returns:** `number?`
@@ -0,0 +1,7 @@
Get all items in the player's inventory.
```lua
exports.ox_inventory:GetPlayerItems()
```
**Returns:** `table`
@@ -0,0 +1,7 @@
Get the maximum carry weight of the player's inventory.
```lua
exports.ox_inventory:GetPlayerMaxWeight()
```
**Returns:** `number`
@@ -0,0 +1,7 @@
Get the total weight of all items in the player's inventory.
```lua
exports.ox_inventory:GetPlayerWeight()
```
**Returns:** `number`
@@ -0,0 +1,12 @@
Get a slot id in the player's inventory matching the given name and metadata.
```lua
exports.ox_inventory:GetSlotIdWithItem(itemName, metadata, strict)
```
- itemName: `string`
- metadata?: `table`
- strict?: `boolean`
- Strictly match metadata properties, otherwise use partial matching.
**Returns:** `number?`
@@ -0,0 +1,12 @@
Get all slot ids in the player's inventory matching the given name and metadata.
```lua
exports.ox_inventory:GetSlotIdsWithItem(itemName, metadata, strict)
```
- itemName: `string`
- metadata?: `table`
- strict?: `boolean`
- Strictly match metadata properties, otherwise use partial matching.
**Returns:** `number[]?`
@@ -0,0 +1,12 @@
Get data for a slot in the player's inventory matching the given name and metadata.
```lua
exports.ox_inventory:GetSlotWithItem(itemName, metadata, strict)
```
- itemName: `string`
- metadata?: `table`
- strict?: `boolean`
- Strictly match metadata properties, otherwise use partial matching.
**Returns:** `table?`
@@ -0,0 +1,12 @@
Get data all slots in the player's inventory matching the given name and metadata.
```lua
exports.ox_inventory:GetSlotsWithItem(itemName, metadata, strict)
```
- itemName: `string`
- metadata?: `table`
- strict?: `boolean`
- Strictly match metadata properties, otherwise use partial matching.
**Returns:** `table[]?`
@@ -0,0 +1,84 @@
---
keywords: ['hasitem']
---
import { Tabs, Tab } from 'nextra-theme-docs';
Searches the inventory for an item, or list of items, with the result varying based on the first argument.
```lua
exports.ox_inventory:Search(search, item, metadata)
```
* search: `'slots'` or `'count'`
* `'slots'` returns a table of slots where the item was found at.
* `'count'` returns the count of the specified item in player's inventory. If searching for multiple items
returns key-value pairs of itemName = count.
* item: `table` or `string`
* Can be a single item name or array of item names.
* metadata?: `table` or `string`
* If metadata is provided as a string it will search the item's `metadata.type` property.
### Count
<Tabs items={["Single item", "Multiple items"]}>
<Tab>
```lua
local count = exports.ox_inventory:Search('count', 'water')
print('You have '..count.. ' water')
```
</Tab>
<Tab>
```lua
local inventory = exports.ox_inventory:Search('count', {'meat', 'skin'}, {grade="1"})
if inventory then
for name, count in pairs(inventory) do
print('You have '..count..' '..name)
end
end
```
</Tab>
</Tabs>
### Slots
<Tabs items={["Single item", "Multiple items"]}>
<Tab>
```lua
local water = exports.ox_inventory:Search('slots', 'water')
local count = 0
for _, v in pairs(water) do
print(v.slot..' contains '..v.count..' water '..json.encode(v.metadata))
count = count + v.count
end
print('You have '..count..' water')
```
</Tab>
<Tab>
```lua
local items = exports.ox_inventory:Search('slots', {'meat', 'skin'}, 'deer')
if items then
for name, data in pairs(items) do
local count = 0
for _, v in pairs(data) do
if v.slot then
print(v.slot..' contains '..v.count..' '..name..' '..json.encode(v.metadata))
count = count + v.count
end
end
print('You have '..count..' '..name)
end
end
```
</Tab>
</Tabs>
@@ -0,0 +1,15 @@
Returns a table of all registered items. The format is as defined in [data/items.lua](https://github.com/overextended/ox_inventory/blob/main/data/items.lua).
```lua
exports.ox_inventory:Items()
```
The following snippet can be used in crafting resources such as okokCrafting or core_crafting, rather than retrieving information from the server.
```lua
local itemNames = {}
for item, data in pairs(exports.ox_inventory:Items()) do
itemNames[item] = data.label
end
```
@@ -0,0 +1,17 @@
---
title: invBusy
---
Returns whether the player's inventory is currently running an action (i.e. using an item)
* invBusy: `boolean`
```lua
local isInventoryBusy = LocalPlayer.state.invBusy
if isInventoryBusy then
-- Do stuff when busy
else
-- Do stuff when not busy
end
```
@@ -0,0 +1,15 @@
---
title: invHotkeys
---
Allows you to enable/disable a player's access to inventory hotkeys.
* invHotkeys: `boolean`
```lua
LocalPlayer.state.invHotkeys = false
```
```lua
LocalPlayer.state.invHotkeys = true
```
@@ -0,0 +1,16 @@
---
title: invOpen
---
Returns whether the player's inventory is currently open or not.
* invOpen: `boolean`
```lua
local isInventoryOpen = LocalPlayer.state.invOpen
if isInventoryOpen then
-- Do stuff when open
else
-- Do stuff when closed
end
@@ -0,0 +1,9 @@
Enables the weapon wheel, but disables the use of inventory items.
Mostly used for weaponised vehicles, though could be called for "minigames"
```lua
local exports.ox_inventory:weaponWheel(state)
```
* state: `boolean`
@@ -0,0 +1,5 @@
Closes the player's inventory.
```lua
exports.ox_inventory:closeInventory()
```
@@ -0,0 +1,24 @@
Sets a metadata property to display in the tooltip.
```lua
exports.ox_inventory:displayMetadata(metadata, value)
```
* metadata: `table` or `string`
* If metadata is a string then it's the metadata property you want to display, value is **not** optional then.
* Can be a table of key-value pairs, key being the metadata property and value being the label for that property.
* value?: `string`
* Label for the string metadata property to be displayed.
**Example:**
```lua
exports.ox_inventory:displayMetadata('mustard', 'Mustard')
```
```lua
exports.ox_inventory:displayMetadata({
mustard = 'Mustard',
ketchup = 'Ketchup'
})
```
@@ -0,0 +1,28 @@
Get data for the currently equipped weapon.
```lua
exports.ox_inventory:getCurrentWeapon()
```
You can also listen for changes to the current weapon using an event handler.
```lua
AddEventHandler('ox_inventory:currentWeapon', function(currentWeapon)
CurrentWeapon = currentWeapon
end)
```
- currentWeapon?: `table`
- ammo?: `string` Name of the item used as ammo.
- hash: `number`
- label: `string`
- melee: `boolean`
- metadata: `table`
- ammo?: `number` Amount of ammo loaded into the weapon.
- components?: `table` Array of component item names, used to apply weapon components.
- durability?: `number`
- registered?: `string` Name of the player that bought the weapon at a shop.
- serial?: `string`
- name: `string` Name of the item.
- slot: `number`
- weight: `number`
@@ -0,0 +1,61 @@
import { Tabs, Tab } from 'nextra-theme-docs';
Opens an inventory using the passed data.
```lua
exports.ox_inventory:openInventory(invType, data)
```
* invType: `string`
* `'player'`
* `'shop'`
* `'stash'`
* `'crafting'`
* `'container'`
* `'drop'`
* `'glovebox'`
* `'trunk'`
* `'dumpster'`
* data: `number` or `string` or `table`
<Tabs items={['Player', 'Shop', 'Stash']}>
<Tab>
**Open the target player's inventory.**
```lua
exports.ox_inventory:openInventory('player', 3)
```
</Tab>
<Tab>
**Open the fourth "General Store" [location](https://github.com/overextended/ox_inventory/blob/main/data/shops.lua#L14).**
```lua
exports.ox_inventory:openInventory('shop', { type = 'General', id = 4 })
```
</Tab>
<Tab>
**Open the first stash in [data/stashes](https://github.com/overextended/ox_inventory/blob/main/data/stashes.lua#L2-L19).**
```lua
exports.ox_inventory:openInventory('stash', 1)
```
**Open a custom stash (created on the server with RegisterStash).**
```lua
exports.ox_inventory:openInventory('stash', 'society_police')
```
**Open a stash with a specific owner.**
```lua
exports.ox_inventory:openInventory('stash', { id = 'police_locker', owner = 'license:xxxxxxxx' })
```
</Tab>
</Tabs>
@@ -0,0 +1,9 @@
If possible opens the nearby player's inventory.
The player trying to open the inventory must be able to open their own and
if the player does not have a police job, the target player must be fatally injured or
playing one of the death anims.
```lua
exports.ox_inventory:openNearbyInventory()
```
@@ -0,0 +1,15 @@
Forces the secondary-inventory key to open the passed inventory. Can be useful to enable inventory access while standing inside a marker.
```lua
exports.ox_inventory:setStashTarget(id, owner)
```
* id: `string` or `number`
* Stash id.
* owner?: `string` or `number`
**Example:**
```lua
exports.ox_inventory:setStashTarget('motel5', 'bobsmith')
```
@@ -0,0 +1,32 @@
Uses the passed item, then triggers the callback function.
Should be calling during item callbacks to utilise the builtin methods (server checks, progress bar, etc.).
```lua
exports.ox_inventory:useItem(data, cb)
```
* data: `table`
* cb?: `function`
```lua
exports('bandage', function(data, slot)
local playerPed = PlayerPedId()
local maxHealth = GetEntityMaxHealth(playerPed)
local health = GetEntityHealth(playerPed)
-- Does the ped need to heal?
if health < maxHealth then
-- Use the bandage
exports.ox_inventory:useItem(data, function(data)
-- The item has been used, so trigger the effects
if data then
SetEntityHealth(playerPed, math.min(maxHealth, math.floor(health + maxHealth / 16)))
lib.notify({description = 'You feel better already'})
end
end)
else
-- Don't use the item
lib.notify({type = 'error', description = 'You don\'t need a bandage right now'})
end
end)
```
@@ -0,0 +1,7 @@
Uses the item in the given inventory slot.
```lua
exports.ox_inventory:useSlot(slot)
```
* slot: `number`
@@ -0,0 +1,199 @@
# Event Hooks
Event hooks allow 3rd party resources to define new behaviour without modifying the inventory code directly.
## registerHook
```lua
exports.ox_inventory:registerHook(eventName, function(payload) end, options)
```
- eventName: `string`
- payload: `table`
- options?: `table`
- print?: `boolean`
- Print to the console when triggering the event.
- itemFilter?: `{ [string]: true }`
- The event will only trigger for items defined as keys in a set.
- inventoryFilter?: `string[]`
- The event will only trigger for inventories that match one of the [patterns](<http://www.easyuo.com/openeuo/wiki/index.php/Lua_Patterns_and_Captures_(Regular_Expressions)>) in the array.
- typeFilter?: `{ [string]: true }`
- The event will only trigger for inventories with one of the provided types (e.g. 'player', 'stash')
Return:
- hookId: `number`
### swapItems
Triggered when moving any item from one slot to another, or when "giving" an item.
By returning `false`, you can cancel the action and revert the inventory state.
**Payload:**
- source: `number`
- action: `'move'` or `'stack'` or `'swap'` or `'give'`
- fromInventory: `table` or `string` or `number`
- toInventory: `table` or `string` or `number`
- fromType: `string`
- toType: `string`
- fromSlot: `table`
- toSlot?: `table` or `number`
- count: `number`
**Example:**
```lua
local hookId = exports.ox_inventory:registerHook('swapItems', function(payload)
print(json.encode(payload, { indent = true }))
return false
end, {
print = true,
itemFilter = {
water = true,
},
inventoryFilter = {
'^glove[%w]+',
'^trunk[%w]+',
}
})
```
Blacklists "water" from being moved into or from gloveboxes and trunks.
### openInventory
**Payload:**
- source: `number`
- inventoryId: `number` or `string`
- inventoryType: `string`
Triggered when a player tries to open a secondary inventory.
By returning `false`, you can cancel the action and keep the player's inventory closed.
**Example:**
```lua
local hookId = exports.ox_inventory:registerHook('openInventory', function(payload)
print(json.encode(payload, { indent = true }))
return false
end, {
print = true,
inventoryFilter = {
'^glove[%w]+',
'^trunk[%w]+',
}
})
```
Disables gloveboxes and trunks.
### createItem
**Payload:**
- inventoryId?: `number` or `string`
- metadata: `table`
- item: `table`
- count: `number`
Triggered when an item is created, either by buying it, using AddItem, or when converting inventory data.
By returning a table you can modify or replace the metadata given to an item.
**Example:**
```lua
local hookId = exports.ox_inventory:registerHook('createItem', function(payload)
print(json.encode(payload, { indent = true }))
local metadata = payload.metadata
metadata.label = 'Mineral Water'
return metadata
end, {
print = true,
itemFilter = {
water = true
}
})
```
Sets the label for "water" to "Mineral Water".
### buyItem
**Payload:**
- source: `number`
- shopType: `string`
- shopId: `number`
- toInventory: `number`
- toSlot: `number`
- itemName: `string`
- metadata: `table`
- count: `number`
- price: `number`
- totalPrice: `number`
- currency?: `string`
Triggered when an item is about to be purchased and can return `false` to prevent the transaction.
**Example:**
```lua
local hookId = exports.ox_inventory:registerHook('buyItem', function(payload)
print(json.encode(payload, { indent = true, sort_keys = true }))
return false
end, {
print = true,
itemFilter = {
water = true
},
})
```
Prevents players from purchasing items at General stores.
### craftItem
**Payload:**
- source: `number`
- benchId: `number`
- benchIndex: `number`
- recipe: `table`
- count: `number`
- duration: `number`
- ingredients: `table<string, number>`
- name: `string`
- slot: `number`
- weight: `number`
- toInventory: `number`
- toSlot: `number`
**Example:**
```lua
local hookId = exports.ox_inventory:registerHook('craftItem', function(payload)
print(json.encode(payload, { indent = true, sort_keys = true }))
return false
end, {
print = true,
itemFilter = {
lockpick = true
},
})
```
Prevent lockpicks from being crafted by players.
## removeHooks
```lua
exports.ox_inventory:removeHooks(id)
```
- id?: `number`
Removes a hook created by the invoking resource with the the specified id.
If no id is specified then all hooks registered by the resource are removed.
@@ -0,0 +1,57 @@
Adds an item into the specified inventory.
Should be used alongside [CanCarryItem](./CanCarryItem.md) otherwise, the maximum weight may be exceeded.
```lua
exports.ox_inventory:AddItem(inv, item, count, metadata, slot, cb)
```
- inv: `table` or `string` or `number`
- The inventory's unique id, or a table with the id and owner.
- playerId: `1`
- inventoryId: `gloveVGH283`
- `{ id = 'personallocker', owner = 'license:xxxxxx'}`
- item: `string`
- The name of the item to add to the target.
- count: `number`
- The number of items to add.
- metadata?: `table` or `string`
- A table of unique data to attach to the item object. A string will create a table with the "type" field.
- slot?: `number`
- A specific slot to add the item to. If the slot is invalid, the first available slot will be used instead.
- cb?: function(success: `boolean`, response?: `string`)
If used for glovebox, trunk or stash you must first check the inventory is loaded with [GetInventory](./GetInventory.md)
Returns `success, response` if cb is undefined, otherwise they are used in the callback only.
**Example:**
```lua
local success, response = exports.ox_inventory:AddItem('gloveVGH283', 'bread', 4)
if not success then
-- if no slots are available, the value will be "inventory_full"
return print(response)
end
print(json.encode(response, {indent=true}))
--[[
{
"metadata": [],
"label": "Bread",
"slot": 1,
"stack": true,
"close": true,
"name": "bread",
"count": 1,
"weight": 150
}
]]
```
**Possible value of the "response" argument, on failure:**
- "invalid_item": the item doesn't exist
- "invalid_inventory": the inventory doesn't exist
- "inventory_full": no free slots
@@ -0,0 +1,18 @@
Returns the amount a player can hold based on available weight.
```lua
exports.ox_inventory:CanCarryAmount(inv, item)
```
* inv: `table` or `string` or `number`
* item: `table` or `string`
* Can be array to check multiple items.
Example:
```lua
-- Checks how much you can carry
amountToAdd = exports.ox_inventory:CanCarryAmount(inv, 'stone')
-- Adds the amount
exports.ox_inventory:AddItem(inv, 'stone', amountToAdd)
```
@@ -0,0 +1,25 @@
Returns true or false depending if the inventory can carry the specified item.
The function checks for inventory weight and available slots.
```lua
exports.ox_inventory:CanCarryItem(inv, item, count, metadata)
```
* inv: `table` or `string` or `number`
* item `table` or `string`
* Can be array of items.
* count: `number`
* metadata?: `table` or `string`
* If metadata is passed as string then `metadata.type` will be checked.
**Example:**
```lua
-- Checks if the player calling the event can carry 3 water items
if exports.ox_inventory:CanCarryItem(source, 'water', 3) then
-- Do stuff if can carry
else
-- Do stuff if can't carry
end
```
@@ -0,0 +1,26 @@
Returns if inventory can carry specified weight and free inventory weight.
```lua
exports.ox_inventory:CanCarryWeight(inv, weight)
```
* inv: `table` or `string` or `number`
* weight: `number`
Example:
```lua
-- Checks if player can carry 1000 grams.
local fillAmount = 1000
local canCarryWeight, freeWeight = ox_inventory:CanCarryWeight(playerId, fillAmount)
if freeWeight == 0 then
-- Player can't carry weight.
return
elseif not canCarryWeight then
-- Modify fillAmount, because inventory can't carry specified weight
fillAmount = freeWeight
end
-- Do something
```
@@ -0,0 +1,11 @@
Returns true if the item swap is possible based on inventory weight.
```lua
exports.ox_inventory:CanSwapItem(inv, firstItem, firstItemCount, testItem, testItemCount)
```
* inv: `table` or `string` or `number`
* firstItem: `string`
* firstItemCount: `number`
* testItem: `string`
* testItemCount: `number`
@@ -0,0 +1,8 @@
Clears the specified inventory. The `keep` argument is either a string or an array of strings containing the name(s) of the item(s) to keep in the inventory after clearing.
```lua
exports.ox_inventory:ClearInventory(inv, keep)
```
* inv: `table` or `string` or `number`
* keep?: `string` or `string[]`
@@ -0,0 +1,10 @@
Clears a player's inventory and saves it to a stash.
Use [ReturnInventory](./ReturnInventory.md) to return the confiscated inventory back to
the player.
```lua
exports.ox_inventory:ConfiscateInventory(source)
```
* source: `number`
@@ -0,0 +1,16 @@
Takes traditional item data and updates it to support ox_inventory.
```lua
exports.ox_inventory:ConvertItems(playerId, items)
```
* playerId: `number`
* items: `table`
Data conversion example:
```lua
Old: [{"cola":1, "bread":3}]
New: [{"slot":1,"name":"cola","count":1},
{"slot":2,"name":"bread","count":3}]
```
@@ -0,0 +1,18 @@
# CreateDropFromPlayer
Creates a new drop with the contents of a player's inventory.
```lua
exports.ox_inventory:CreateDropFromPlayer(playerId)
```
- playerId: `number`
Return:
- dropId: `string`
**Example**
```lua
local dropId = exports.ox_inventory:CreateDropFromPlayer(1)
```
@@ -0,0 +1,43 @@
# CreateTemporaryStash
Creates a temporary stash which will be removed after some time.
```lua
exports.ox_inventory:CreateTemporaryStash(properties)
```
- properties: `table`
- label: `string`
- slots: `number`
- maxWeight: `number`
- owner?: `string` `number` or `boolean`
- `string`: Can only access the stash linked to the owner.
- `true`: Each player has a unique stash but can request other player's stashes.
- The inventory is always shared if `false` or `nil`.
- groups?: `table<string, number>`
- Table of group names (e.g. jobs) where the numeric value is the minimum grade required.
- `{['police'] = 0, ['ambulance'] = 2}`
- coords?: `vector3`
- Stash can only be accessed while nearby.
- items?: `{ [number]: string, [number]: number, [number]?: table }[]`
- An array of tables, containing a sequence of itemName, count, metadata.
Return:
- inventoryId: `string`
**Example**
```lua
local mystash = exports.ox_inventory:CreateTemporaryStash({
label = 'mystash',
slots = 5,
maxWeight = 5000,
items = {
{ 'WEAPON_MINISMG', 1 },
{ 'ammo-9', 69 },
{ 'water', 2, { label = 'Mineral water' } }
}
})
TriggerClientEvent('ox_inventory:openInventory', 1, 'stash', mystash)
```
@@ -0,0 +1,30 @@
Drops can be created from other resources, containing a variety of items and utilising a custom label (instead of 'Drop 32648').
```lua
exports.ox_inventory:CustomDrop(prefix, items, coords, slots, maxWeight, instance, model)
```
- prefix: `string`
- items: `table`
- name: `string`
- count: `number`
- metadata?: `table`
- coords: `vector3`
- slots?: `number`
- maxWeight?: `number`
- instance?: `string` or `number`
- model?: `number`
```lua
-- Create a generic drop with a marker
exports.ox_inventory:CustomDrop('Carcass', {
{'meat', 5, { grade = 2, type = 'deer' }},
{'hide', 5, { grade = 2, type = 'deer' }}
}, coords)
-- Create a drop with an entity
exports.ox_inventory:CustomDrop('SMG', {
{ 'WEAPON_MINISMG', 1 },
{ 'ammo-9', 69 },
}, GetEntityCoords(GetPlayerPed(1)), 5, 10000, nil, `w_sb_minismg`)
```
@@ -0,0 +1,10 @@
Returns the inventory associated with the container linked in the slot of the given inventory.
```lua
exports.ox_inventory:GetContainerFromSlot(inv, slotId)
```
- inv: `table` or `string` or `number`
- slotId: `number`
**Returns:** `table?`
@@ -0,0 +1,8 @@
Returns the player's currently equipped weapon as a table.
```lua
-- inv: string or number
exports.ox_inventory:GetCurrentWeapon(inv)
```
* inv: `table` or `string` or `number`
@@ -0,0 +1,9 @@
Get the first available empty slot in an inventory.
```lua
exports.ox_inventory:GetEmptySlot(inv)
```
- inv: `table` or `string` or `number`
**Returns:** `number?`
@@ -0,0 +1,27 @@
Returns the inventory associated with the ID (and owner if defined). Otherwise returns null.
```lua
exports.ox_inventory:GetInventory(inv, owner)
```
* inv: `number` or `table`
* owner?: `string` or `boolean`
**Example:**
```lua
local inventory = exports.ox_inventory:GetInventory('example_stash', false)
print(json.encode(inventory, {indent = true}))
--[[
{
"id": "example_stash,
"label": "Police Stash",
"type": "stash,
"slots": 50,
"weight": 0,
"maxWeight": 100000,
"owner": false,
...
}
]]
```
@@ -0,0 +1,14 @@
Returns all slots with items in a inventory.
```lua
exports.ox_inventory:GetInventoryItems(inv, owner)
```
* inv: `number` or `table`
* owner?: `string` or `boolean`
**Example:**
```lua
local playerItems = exports.ox_inventory:GetInventoryItems(source)
```
@@ -0,0 +1,36 @@
Returns _generic_ item data from the specified inventory, with the total count.
```lua
exports.ox_inventory:GetItem(inv, item, metadata, returnsCount)
```
* inv: `table` or `string` or `number`
* item: `table` or `string`
* Can be items array.
* metadata?: `any`
* Only returns the count of items that strictly match the given metadata.
* returnsCount?: `boolean`
If `returnsCount` is set to true, the returned value will be the `count` based on
how many times the item was found.
Otherwise returns the data related to the item _and_ its total count found in the inventory.
**Example**:
```lua
local item = ox_inventory:GetItem(source, 'water', nil, false)
print(json.encode(item, {indent=true}))
--[[
{
"consume": 1,
"count": 15,
"stack": true,
"name": "water",
"weight": 500,
"label": "Water",
"close": true
}
]]
```
@@ -0,0 +1,13 @@
Get the total item count for all items in an inventory with the given name and metadata.
```lua
exports.ox_inventory:GetItemCount(inv, itemName, metadata, strict)
```
- inv: `table` or `string` or `number`
- itemName: `string`
- metadata?: `table`
- strict?: `boolean`
- Strictly match metadata properties, otherwise use partial matching.
**Returns:** `number?`
@@ -0,0 +1,9 @@
Returns the number of slots the specified item is in, the item's total count and the remaining empty slots.
```lua
exports.ox_inventory:GetItemSlots(inv, item, metadata)
```
* inv: `table` or `string` or `number`
* item: `table` or `string`
* metadata?: `table`
@@ -0,0 +1,29 @@
Returns the specified slot data as a table.
```lua
exports.ox_inventory:GetSlot(inv, slot)
```
* inv: `table` or `string` or `number`
* slot: `number`
**Example:**
```lua
local slot = exports.ox_inventory:GetSlot(source, 1)
print(json.encode(slot, {indent=true}))
--[[
{
"weight": 2000,
"name": "water",
"metadata": [],
"slot": 1,
"label": "Water",
"close": true,
"stack": true,
"count: 4
}
]]
```
@@ -0,0 +1,11 @@
Get the slot id of an existing item matching the given data, or an empty slot.
```lua
exports.ox_inventory:GetSlotForItem(inv, itemName, metadata)
```
- inv: `table` or `string` or `number`
- itemName: `string`
- metadata: `table?`
**Returns:** `number?`
@@ -0,0 +1,13 @@
Get a slot id in an inventory matching the given name and metadata.
```lua
exports.ox_inventory:GetSlotIdWithItem(inv, itemName, metadata, strict)
```
- inv: `table` or `string` or `number`
- itemName: `string`
- metadata?: `table`
- strict?: `boolean`
- Strictly match metadata properties, otherwise use partial matching.
**Returns:** `number?`
@@ -0,0 +1,13 @@
Get all slot ids in an inventory matching the given name and metadata.
```lua
exports.ox_inventory:GetSlotIdsWithItem(inv, itemName, metadata, strict)
```
- inv: `table` or `string` or `number`
- itemName: `string`
- metadata?: `table`
- strict?: `boolean`
- Strictly match metadata properties, otherwise use partial matching.
**Returns:** `number[]?`
@@ -0,0 +1,13 @@
Get data for a slot in an inventory matching the given name and metadata.
```lua
exports.ox_inventory:GetSlotWithItem(inv, itemName, metadata, strict)
```
- inv: `table` or `string` or `number`
- itemName: `string`
- metadata?: `table`
- strict?: `boolean`
- Strictly match metadata properties, otherwise use partial matching.
**Returns:** `table?`
@@ -0,0 +1,13 @@
Get data all slots in an inventory matching the given name and metadata.
```lua
exports.ox_inventory:GetSlotsWithItem(inv, itemName, metadata, strict)
```
- inv: `table` or `string` or `number`
- itemName: `string`
- metadata?: `table`
- strict?: `boolean`
- Strictly match metadata properties, otherwise use partial matching.
**Returns:** `table[]?`
@@ -0,0 +1,33 @@
import { Callout } from 'nextra/components';
Creates a new custom stash.
```lua
exports.ox_inventory:RegisterStash(id, label, slots, maxWeight, owner, groups, coords)
```
- id: `string` or `number`
- Stash identifier when loading from the database.
- label: `string`
- Display name when inventory is open.
- slots: `number`
- maxWeight: `number`
- owner: `string` or `boolean` or `nil`
- `string`: Can only access the stash linked to the owner.
- `true`: Each player has a unique stash but can request other player's stashes.
- `nil`: Always shared.
- groups: `table`
- Table of player groups (jobs) able to access the stash.
- Table of group names where the numeric value is the minimum grade required.
- `{['police'] = 0, ['ambulance'] = 2}`
- coords?: `vector3` or `vector3[]`
<Callout>
This function needs to be triggered before a player can open the stash.
</Callout>
**Example:**
For a use case example on this function check out the written [Guide](../../../Guides/stashes.md) for it.
@@ -0,0 +1,35 @@
Removes the specified item from the specified inventory.
```lua
exports.ox_inventory:RemoveItem(inv, item, count, metadata, slot)
```
- inv: `table` or `string` or `number`
- The inventory's unique id, or a table with the id and owner.
- playerId: `1`
- inventoryId: `gloveVGH283`
- `{ id = 'personallocker', owner = 'license:xxxxxx'}`
- item: `string`
- The name of the item to remove from the target.
- count: `number`
- The number of items to remove.
- metadata?: `table` or `string`
- Only remove items with matching metadata properties.
- slot?: `number`
- A specific slot to remove the item from. If the slot is invalid, the first available slot will be used instead.
- cb?: function(success: `boolean`, response?: `string`)
Returns success: `boolean`, response: `string?`.
**Possible value of "response" on failure:**
- "invalid_item": the item doesn't exist
- "invalid_inventory": the inventory doesn't exist
- "not_enough_items": inventory did not contain enough of the given item
**Example:**
```lua
-- Removes 2 water from the glovebox for the given plate.
local success = exports.ox_inventory:RemoveItem('gloveVGH283', 'water', 2)
```
@@ -0,0 +1,9 @@
Returns the confiscated inventory back to the player.
Use it alongside [ConfiscateInventory](./ConfiscateInventory.md).
```lua
exports.ox_inventory:ReturnInventory(source)
```
* source: `number`
@@ -0,0 +1,13 @@
Searches an inventory for a specified item.
```lua
exports.ox_inventory:Search(inv, search, item, metadata)
```
* inv: `table` or `string` or `number`
* search: `string`
* item: `table` or `string`
* metadata?: `table` or `string`
`search` can be either `'slots'` or `'count'`, where slots will return a table of data
and count will return the found amount of the specified item.
@@ -0,0 +1,27 @@
Sets durability onto the specified slot.
Can be used for repairing weapons.
```lua
exports.ox_inventory:SetDurability(inv, slot, durability)
```
* inv: `table` or `string` or `number`
* slot: `number`
* durability: `number`
**Example:**
```lua
local ox_inventory = exports.ox_inventory
-- Set the durability of the item in slot 3 of source player's inventory to 100
ox_inventory:SetDurability(source, 3, 100)
-- Set the durability of the source player's current weapon to 100
local weapon = ox_inventory:GetCurrentWeapon(source)
if weapon then
ox_inventory:SetDurability(source, weapon.slot, 100)
end
```
@@ -0,0 +1,17 @@
Sets the maximum weight available for an inventory.
```lua
exports.ox_inventory:SetMaxWeight(inv, maxWeight)
```
* inv: `table` or `string` or `number`
* maxWeight: `number`
**Example:**
```lua
local ox_inventory = exports.ox_inventory
-- Set the max weight for player 1's inventory to 20kg.
ox_inventory:SetMaxWeight(1, 20000)
```
@@ -0,0 +1,27 @@
Sets metadata on the specified slot.
```lua
ox_inventory:SetMetadata(inv, slot, metadata)
```
* inv: `table` or `string` or `number`
* slot: `number`
* metadata: `table`
**Example:**
```lua
local ox_inventory = exports.ox_inventory
local water = ox_inventory:Search(source, 1, 'water')
for k, v in pairs(water) do
print('\n______________'..'\n- index '..k)
print(v.name, 'slot: '..v.slot, 'metadata: '..json.encode(v.metadata))
water = v
break
end
water.metadata.type = 'clean'
ox_inventory:SetMetadata(source, water.slot, water.metadata)
print(('modified %sx water in slot %s with new metadata'):format(water.count, water.slot))
```
@@ -0,0 +1,17 @@
Sets the number of slots available for an inventory.
```lua
exports.ox_inventory:SetSlotCount(inv, slots)
```
* inv: `table` or `string` or `number`
* slots: `number`
**Example:**
```lua
local ox_inventory = exports.ox_inventory
-- Set the slot count for player 1's inventory to 10.
ox_inventory:SetSlotCount(1, 10)
```
@@ -0,0 +1,10 @@
Swaps slots in specified inventories.
```lua
exports.ox_inventory:SwapSlots(fromInventory, toInventory, slot1, slot2)
```
* fromInventory: `table` or `string` or `number`
* toInventory: `table` or `string` or `number`
* slot1: `number`
* slot2: `number`
@@ -0,0 +1,20 @@
Returns a table of all registered items. The format is as defined in [data/items.lua](https://github.com/overextended/ox_inventory/blob/main/data/items.lua).
```lua
exports.ox_inventory:Items()
```
The following snippet can be used in crafting resources such as okokCrafting or core_crafting, rather than querying the database.
```lua
local itemNames
ESX.RegisterServerCallback('crafting:itemNames', function(source, cb)
if not itemNames then
itemNames = {}
for item, data in pairs(exports.ox_inventory:Items()) do
itemNames[item] = data.label
end
end
cb(itemNames)
end)
```
@@ -0,0 +1,10 @@
# UpdateVehicle
Update the internal reference to vehicle stashes, without triggering a save or updating the database.
```lua
exports.ox_inventory:UpdateVehicle(oldPlate, newPlate)
```
* oldPlate: `string`
* newPlate: `string`
@@ -0,0 +1,60 @@
import { Tabs, Tab } from 'nextra-theme-docs';
Opens an inventory using the passed data.
Forces a player to open an inventory, without usual security checks (groups, coords).
```lua
exports.ox_inventory:forceOpenInventory(playerId, invType, data)
```
- playerId: `number`
- invType: `string`
- `'player'`
- `'stash'`
- `'container'`
- `'drop'`
- `'glovebox'`
- `'trunk'`
- `'dumpster'`
- data: `number` or `string` or `table`
<Tabs items={["Player", "Stash"]}>
<Tab>
**Open the target player's inventory.**
```lua
exports.ox_inventory:forceOpenInventory(1, 'player', 3)
```
**Admin command to open a player's inventory.**
```lua
RegisterCommand('openplayerinv', function(source, args)
exports.ox_inventory:forceOpenInventory(source, 'player', tonumber(args[1]))
end, true)
```
</Tab>
<Tab>
**Open the first stash in [data/stashes](https://github.com/overextended/ox_inventory/blob/main/data/stashes.lua#L2-L19).**
```lua
exports.ox_inventory:forceOpenInventory(1, 'stash', 'apartment420')
```
**Open a custom stash (created on the server with RegisterStash).**
```lua
exports.ox_inventory:forceOpenInventory(1, 'stash', 'society_police')
```
**Open a stash with a specific owner.**
```lua
exports.ox_inventory:forceOpenInventory(1, 'stash', { id = 'police_locker', owner = 'license:xxxxxxxx' })
```
</Tab>
</Tabs>
@@ -0,0 +1,15 @@
Creates and sets the player's inventory.
```lua
exports.ox_inventory:setPlayerInventory(player, data)
```
* player: `table`
* source: `number`
* identifier: `string`
* name: `string`
* groups?: `table`
* sex?: `string`
* dateofbirth?: `string`
* data?: `table`
* If not provided will load player's inventory data from the db.
+74
View File
@@ -0,0 +1,74 @@
---
title: Creating crafting points
---
Crafting locations, items and their ingredients are defined in [data/crafting.lua](https://github.com/overextended/ox_inventory/blob/main/data/crafting.lua).
## Crafting definition
```lua
{
items = {
{
name = 'lockpick',
ingredients = {
garbage = 3,
WEAPON_HAMMER = 0.1
},
duration = 5000,
count = 3,
metadata = { durability = 20 }
},
{
name = 'garbage',
ingredients = {
cola = 1
},
metadata = { description = 'An empty soda can.', weight = 20, image = 'trash_can' }
},
},
points = {
vec3(-1147.083008, -2002.662109, 13.180260),
},
zones = {
{
coords = vec3(-1146.2, -2002.05, 13.2),
size = vec3(3.8, 1.05, 0.15),
distance = 1.5,
rotation = 315.0,
},
},
blip = { id = 566, colour = 31, scale = 0.8 },
},
```
* items: `table`
* name: `string`
* ingredients: `table`
* Item ingredients can be seen in the item tooltip.
* Key-value pairs of item name and consume count
* key - Item name.
* value - If 1 or above it's the consume count, if below 1 and above 0 it's the durability consume amount, if
set to 0 then the item is required but not consumed.
* duration: `number`
* Crafting duration in milliseconds.
* count: `number`
* Item amount received upon crafting.
* metadata: `table`
* Metadata applied to the item being crafted.
* points: `vector3[]`
* Interaction locations that will open the crafting inventory.
* groups: `table`
* Key-value pairs of job name and minimum grade to access the crafting location.
* `{["police"] = 0, ["ambulance"] = 2}`
* zones: `table`
* ox_lib targeting zones used for ox_target.
* coords: `vector3`
* size: `vector3`
* distance: `number`
* rotation: `number`
* blip: `table`
* id: `number`
* Blip sprite number.
* colour: `number`
* scale: `number`
+265
View File
@@ -0,0 +1,265 @@
---
title: Creating items
---
import { Tabs, Tab } from 'nextra-theme-docs';
## Defining item data
Before being able to see or use an item in game it **must** first be defined.
All of the items are defined in the `/data/items.lua` file with key, value pairs.
Key is the name (not the label) of an item and the value is a table containing the
options for the item.
**Item options:**
* label: `string`
* weight?: `number`
* stack?: `boolean`
* If set to false will not allow the item to be stacked.
* degrade?: `number`
* Amount of time in minutes the item will degrade after.
* close?: `boolean`
* If set to false does not close the inventory on item use.
* description?: `string`
* Item description that will be shown in the tooltip
* consume?: `number`
* Item count needed and removed use.
* Default: 1
* If set to a decimal will consume durability instead (0.2 = 20%).
* allowArmed?: `boolean`
* If set to true will allow use of item while armed with a weapon.
* server?: `table`
* export?: `string`
* client?: `table`
* export?: `string`
* Export to be triggered after item use.
* event?: `string`
* Event to be triggered after item use.
* status?: `table`
* Adjust esx_status values after use.
* anim?: `table`
* Animation that will be played during the progress bar.
* dict: `string`
* clip: `string`
* prop?: `table`
* Attached prop that will be displayed during the progress bar.
* model: `string` or `hash`
* pos: `table` (x, y, z)
* rot: `table` (x, y, z)
* disable?: `table`
* Actions to be disabled during the progress bar
* move?: `boolean`
* car?: `boolean`
* combat?: `boolean`
* mouse?: `boolean`
* usetime?: `number`
* cancel?: `boolean`
* If set to true the player canc cancel item use.
* add?: `function`(total: `number`)
* Function that triggers when receiving an item
* Returns total item count as `total`
* remove?: `function`(total: `number`)
* Function that triggers when removing an item
* Returns total item count as `total`
* buttons?: `table`
* label: `string`
* action: `function`(slot: `number`)
* Callback function when button is clicked in context menu, returns item slot.
**Examples:**
<Tabs items={["Burger", "Burger with description", "Burger with notification"]}>
<Tab>
```lua
['burger'] = {
label = 'Burger',
weight = 220,
stack = true,
close = true,
client = {
status = { hunger = 200000 },
anim = { dict = 'mp_player_inteat@burger', clip = 'mp_player_int_eat_burger_fp' },
prop = {
model = 'prop_cs_burger_01',
pos = { x = 0.02, y = 0.02, y = -0.02},
rot = { x = 0.0, y = 0.0, y = 0.0}
},
usetime = 2500,
}
}
```
</Tab>
<Tab>
A modified burger item which includes a description.
```lua
['burger'] = {
label = 'Burger',
description = 'Just what is the secret formula?'
weight = 220,
stack = true,
close = true,
client = {
status = { hunger = 200000 },
anim = { dict = 'mp_player_inteat@burger', clip = 'mp_player_int_eat_burger_fp' },
prop = {
model = 'prop_cs_burger_01',
pos = { x = 0.02, y = 0.02, y = -0.02},
rot = { x = 0.0, y = 0.0, y = 0.0}
},
usetime = 2500,
}
}
```
</Tab>
<Tab>
A modified burger item, which gives you notifications on add and remove arguments.
```lua
['burger'] = {
label = 'Burger',
weight = 220,
stack = true,
consume = 0,
client = {
add = function(total)
if total > 0 then
lib.notify({description = 'Nice burger you got there!'})
end
end,
remove = function(total)
if total < 1 then
lib.notify({description = 'You lost all of your burgers!'})
end
end
}
}
```
</Tab>
</Tabs>
## Making the item usable
* If you are using ESX, you can continue using `ESX.RegisterUsableItem`.
* If you are using QBCore, you can continue using `QBCore.Functions.CreateUseableItem`.
Using the built-in system is more secure and provides much more functionality.
### Client callbacks
Item callbacks can be added by defining an export (recommended), or by adding it to [items/client.lua](https://github.com/overextended/ox_inventory/blob/main/modules/items/client.lua#L33).
When defining [item data](https://github.com/overextended/ox_inventory/blob/main/data/items.lua#L11), adding client.export will trigger an event on item use.
The correct formatting is `export = resourceName.exportName`.
```lua
exports('bandage', function(data, slot)
local playerPed = PlayerPedId()
local maxHealth = GetEntityMaxHealth(playerPed)
local health = GetEntityHealth(playerPed)
-- Does the ped need to heal? We can cancel the item from being used.
if health < maxHealth then
-- Triggers internal-code to correctly use items.
-- This adds security, removes the item on use, adds progressbar support, and is necessary for server callbacks.
exports.ox_inventory:useItem(data, function(data)
-- The server has verified the item can be used.
if data then
SetEntityHealth(playerPed, math.min(maxHealth, math.floor(health + maxHealth / 16)))
lib.notify({description = 'You feel better already'})
end
end)
else
-- Don't use the item
lib.notify({type = 'error', description = 'You don\'t need a bandage right now'})
end
end)
```
### Server callbacks
A callback function can be defined on the server to handle several events (usingItem, usedItem, buyItem).
This can either be an export (recommended), or added to the bottom of [items/server.lua](https://github.com/overextended/ox_inventory/blob/main/modules/items/server.lua).
When defining [item data](https://github.com/overextended/ox_inventory/blob/main/data/items.lua#L14), adding server.export will trigger an event for the actions above.
The correct formatting is `export = resourceName.exportName`.
```lua
exports('bandage', function(event, item, inventory, slot, data)
-- Player is attempting to use the item.
if event == 'usingItem' then
local playerPed = GetPlayerPed(inventory.id)
local maxHealth = GetEntityMaxHealth(playerPed)
local health = GetEntityHealth(playerPed)
-- Check if the player needs to be healed.
if health >= maxHealth then
TriggerClientEvent('ox_lib:notify', inventory.id, {type = 'error', description = 'You don\'t need a bandage right now'})
-- Returning 'false' will prevent the item from being used
return false
end
return
end
-- Player has finished using the item.
if event == 'usedItem' then
return TriggerClientEvent('ox_lib:notify', inventory.id, {description = 'You feel better already'})
end
-- Player is attempting to purchase the item.
if event == 'buying' then
return TriggerClientEvent('ox_lib:notify', inventory.id, {type = 'success', description = 'You bought a bandage'})
end
end)
```
## Creating container items
Like with other items the item must first be registered.
**Example:**
```lua
['paperbag'] = {
label = 'Paper Bag',
weight = 1,
stack = false,
close = false,
consume = 0
},
```
When registered you can define the item as a container in `/modules/items/containers.lua`
The key for the container is the `name` you gave it when registering the item.
You can also define the number of slots, the maximum weight, blacklist and whitelist items.
* itemName:
* slots: number
* The number represents the amount of slots
* maxWeight: number
* The number represents the maximum weight within the container
* blacklist:
* Supports single and multiple items
* `{ 'testburger', 'testburger2' }`
* whitelist:
* Supports single and multiple items
* `{ 'testburger', 'testburger2' }`
**Example:**
```lua
setContainerProperties('paperbag', {
slots = 5,
maxWeight = 1000,
blacklist = { 'testburger' }
})
```
+104
View File
@@ -0,0 +1,104 @@
---
title: Creating shops
---
Builtin shops are defined in [data/shops.lua](https://github.com/overextended/ox_inventory/blob/main/data/shops.lua), and more can be added here to benefit from the built-in markers or zones support.
## Shop definition
```lua
{
General = {
name = 'Shop',
blip = {
id = 59,
colour = 69,
scale = 0.8
},
inventory = {
{ name = 'burger', price = 10 },
{ name = 'water', price = 10 },
{ name = 'cola', price = 10 },
},
locations = {
vec3(25.7, -1347.3, 29.49),
},
targets = {
-- Shop using a BoxZone
{
loc = vec3(25.06, -1347.32, 29.5),
length = 0.7,
width = 0.5,
heading = 0.0,
minZ = 29.5,
maxZ = 29.9,
distance = 1.5
},
-- Shop using a ped
{
ped = `mp_m_shopkeep_01`,
scenario = 'WORLD_HUMAN_AA_COFFEE',
loc = vec3(24.407, -1347.283, 28.497),
heading = 270.311,
},
}
}
}
```
- name: `string`
- The label to display when the shop is open.
- blip?: `table`
- Creates a blip with the given settings. Leave it undefined for no blip to be created.
- id: `number`
- colour: `number`
- scale: `number`
- groups?: `table`
- Key-value pairs of job name and minimum grade to access the shop.
- `{["police"] = 0, ["ambulance"] = 2}`
- inventory: `table`
- name: `string`
- price: `number`
- currency?: `string`
- Item to be used as currency.
- count?: `number`
- Amount of the item in the stock.
- license?: `string`
- License required to purchase the item.
- metadata?: `table`
- grade?: `number` | `number[]`
- Grade required to purchase the item.
- locations?: `vector3[]`
- An array of coordinates to create unique instances of the shop archetype at, using markers.
- targets?: `table[]`
- An array of target settings to create unique instances of the shop archetype at, using peds or BoxZones (PolyZone data structure).
- model?: `number[]`
- An array of models that can be targetted to open a shop. Used for vending machines.
Targets and model are only available when using a targeting resource like ox_target.
## Register during runtime
Shops can be added using `exports.ox_inventory:RegisterShop` on the server, however they cannot utilise any client-only features.
- Blips, markers, and zones will not be created.
- Must use "locations" and not "targets" to define each shop using the archetype.
**Example:**
```lua
exports.ox_inventory:RegisterShop('TestShop', {
name = 'Test shop',
inventory = {
{ name = 'burger', price = 10 },
{ name = 'water', price = 10 },
{ name = 'cola', price = 10 },
},
locations = {
vec3(223.832962, -792.619751, 30.695190),
},
groups = {
police = 0
},
})
```
+88
View File
@@ -0,0 +1,88 @@
---
title: Creating custom stashes
---
import { GhButton } from '@components/button';
We can set up custom stashes from outside the resource utilising the exported RegisterStash function.
Firstly, we need to define the stashes properties.
### Stash properties
- id: `string`
- Unique name to identify the stash in the database.
- label: `string`
- Display name when viewing the stash.
- slots: `number`
- Number of slots the stash will have.
- weight: `number`
- Maximum weight of the stash inventory.
- owner?: `string` or `boolean`
- `true`: Each player has their own unique stash, but can request to open the stash of another player
- `false`: Only a single stash exists and is shared between all players
- `string`: The stash explicitly belongs to the given owner, usually a player identifier
- groups?: `table`
- Key-value pairs of job name and minimum grade to be able to access the stash. (`{["police"] = 0, ["ambulance"] = 2}`)
- name: `string`
- grade: `number`
- coords?: `vector3` or `table`
- You can set the stash coordinates to prevent the stash from being opened if the player isn't close enough.
- Vector or table containing the coordinates of the stash.
## Example
Below the value is hardset, but it could be loaded from the database (especially if there are unknown fields, i.e. owner)
```lua
-- Server
local stash = {
id = '42wallabyway',
label = '42 Wallaby Way',
slots = 50,
weight = 100000,
owner = 'char1:license'
}
AddEventHandler('onServerResourceStart', function(resourceName)
if resourceName == 'ox_inventory' or resourceName == GetCurrentResourceName() then
exports.ox_inventory:RegisterStash(stash.id, stash.label, stash.slots, stash.weight, stash.owner)
end
end)
-- Client
exports.ox_inventory:openInventory('stash', {id='42wallabyway', owner=property.owner})
```
The following sample is based on esx_property's db data.
```lua
-- Server
local properties
MySQL.query('SELECT * FROM `properties`', {}, function(result)
properties = result
end
RegisterNetEvent('ox:loadStashes', function(id)
local stash = properties[id]
if stash then
-- id: 1, name: WhispymoundDrive, label: 2677 Whispymound Drive, coords: {"x":118.748,"y":566.573,"z":175.697}
ox_inventory:RegisterStash(stash.name, stash.label, 50, 100000, true, false, json.encode(stash.room_menu))
end
end)
-- Client
local ox_inventory = exports.ox_inventory
if ox_inventory:openInventory('stash', property.id) == false then
TriggerServerEvent('ox:loadStashes')
ox_inventory:openInventory('stash', property.id)
end
```
## Example resource
We put together an example resource showcasing how to properly utilise the stash API:
<GhButton link="https://www.github.com/overextended/ox_inventory_examples" />
+6
View File
@@ -0,0 +1,6 @@
label: Ox Inventory
collapsible: true
collapsed: true
link:
type: generated-index
description: An slot-based inventory with item metadata for "item uniqueness".
+29
View File
@@ -0,0 +1,29 @@
---
title: Common issues
---
## UI has not been built
Because the UI for inventory is written in React it can't run natively under FiveM so it must first be bundled into html/css/js.
We provide an easy way for you to do this by downloading a pre-bundled release, which you can get from [here](https://github.com/overextended/ox_inventory/releases/latest).
Make sure you download the `ox_inventory.zip` file as that one contains the bundled files and others are raw source code.
If in case you wanted to edit the inventory UI you would have to build these files yourself.
To do so please read our [_Building inventory UI_](../Guides/inventory_ui.md) guide.
## No such export * in resource ox_inventory
There are several likely causes for this "issue".
- An error occurred while starting ox_inventory or one of its dependencies (e.g. ox_lib).
- The resource trying to use the export (e.g. esx_addoninventory) is being started _before_ ox_inventory.
- You're literally trying to call an export that does not exist, which is a you issue.
## Stashes / trunks are not saved at server restart
Stopping a server or "restarting" it does not trigger any events or allow for saving.
- Inventories are saved at a 5 minute interval.
- txAdmin scheduled restarts and shutdowns will trigger a save.
- The `saveinv` command can be used manually or triggered in the console.
- All inventories are saved when the number of online players hits 0.
+157
View File
@@ -0,0 +1,157 @@
import { Callout } from 'nextra/components';
import { Tabs, Tab, Steps } from 'nextra-theme-docs';
import ResourceLinks from '@components/resource-links';
A standalone library for providing easily reusable code as importable modules and exports.
<ResourceLinks repo="https://github.com/overextended/ox_lib" />
## Installation
<Callout type="info">
We **strongly** recommend referring to [Guides](../guides) for setting up Git, Node.js, and pnpm.
</Callout>
<Steps>
### Download a [release](https://github.com/overextended/ox_lib/releases) or build the source code.
```bash
git clone https://github.com/overextended/ox_lib.git
cd ox_lib/web
pnpm i
pnpm build
```
### Config
Resource configuration is handled using [convars](https://docs.fivem.net/docs/scripting-reference/convars/).
```bash
# https://mantine.dev/theming/colors/#default-colors
setr ox:primaryColor blue
setr ox:primaryShade 8
```
You'll also need to grant ace permissions to the resource.
```bash
add_ace resource.ox_lib command.add_ace allow
add_ace resource.ox_lib command.remove_ace allow
add_ace resource.ox_lib command.add_principal allow
add_ace resource.ox_lib command.remove_principal allow
```
</Steps>
## Usage
<Tabs items={["Lua", "JS"]}>
<Tab>
To enable the library inside of your resource just add `@ox_lib/init.lua` to `shared_scripts` or
a `shared_script` in your `fxmanifest.lua` file.
```lua
shared_scripts {
'@ox_lib/init.lua'
}
```
Or if the library is the only shared script you use you can do:
```lua
shared_script '@ox_lib/init.lua'
```
</Tab>
<Tab>
<Callout>
Npm package for the lib does **not** support all the functions that are available for Lua.
All supported functions are located inside the `resource` folder in the lib.
</Callout>
You can get the npm package [here](https://npmjs.com/package/@overextended/ox_lib).
**Usage:**
You can either import the whole library object which contains all the functions for that scope (client/server/shared) or you can deconstruct it and import the functions you find needed at the time.
```ts
import lib from '@overextended/ox_lib/server';
```
```ts
import { versionCheck } from '@overextended/ox_lib/server';
```
</Tab>
</Tabs>
That's it!
You can now use the library functions inside of your resource, check the rest of the documentation to see how to utilise them.
## Using icons for interface functions
The icon library used is Font Awesome 6.0, if for the icon you define only a string the default icon type will be `solid`.
If you want to use a different icon type, i.e apple as a brand, you need to define icon as a table (`array`) with the first value being the icon type (`fas`, `far`, `fab`) as a string, and the second being the icon name.
<Tabs items={["Lua", "JS"]}>
<Tab>
```lua
icon = {'fab', 'apple'}
```
</Tab>
<Tab>
```ts
icon: ['fab', 'apple'];
```
</Tab>
</Tabs>
## Building the UI
If you wish to edit any of the UI elements you will need to download the _source_ code, edit what you need and then compile it.
<Callout type="warning">
**DO NOT** de-bundle and un-minify the release CSS and JS files to edit them.
</Callout>
**Requirements:**
- [Node.js (LTS)](https://nodejs.org/)
- pnpm
**Installing Node.js:**
- Download the LTS version of Node.js.
- Go through the install and make sure you install all of the features.
- Run node --version in cmd and make sure that it gives you the version number. If it doesn't then you didn't install it correctly.
**Installing pnpm:**
- After installing NodeJS you can install pnpm by running `npm install -g pnpm`.
**Building the UI:**
- cd into the web directory.
- run `pnpm i` to install the dependencies.
- run `pnpm build` to build the source files.
<Callout type="info">
When working in the browser you can run `pnpm start`, which supports hot reloads meaning that
you will see your changes after saving your file.
If you want to work in game you can run `pnpm start:game` which writes changes to disk, so
the only thing you have to do is restart the resource for it take affect.
</Callout>
+126
View File
@@ -0,0 +1,126 @@
Wrapper around the built-in ACL system. Handles lib.addCommand and ox_groups permissions.
Refer to [Basic Aces & Principals overview/guide](https://forum.cfx.re/t/basic-aces-principals-overview-guide/90917) for more information.
import { Tabs, Tab } from 'nextra-theme-docs';
### lib.addAce
Assigns the ace permission to a principal. Third parameter defaults to 'allow', while false sets the permission to 'deny'.
<Tabs items={["Lua", "JS"]}>
<Tab>
```lua
lib.addAce(principal, ace, allow)
lib.addAce('group.admin', 'command.say')
```
</Tab>
<Tab>
```ts
import lib from '@overextended/ox_lib/server'
lib.addAce(principal, ace, allow)
lib.addAce('group.admin', 'command.say')
```
</Tab>
</Tabs>
* principal: `string`
* ace: `string`
* allow: `boolean`
### lib.removeAce
Removes the ace permission from a principal. Third parameter defaults to 'allow', while false sets the permission to 'deny'.
<Tabs items={["Lua", "JS"]}>
<Tab>
```lua
lib.removeAce(principal, ace, allow)
lib.removeAce('group.admin', 'command.say')
```
</Tab>
<Tab>
```ts
import lib from '@overextended/ox_lib/server'
lib.removeAce(principal, ace, allow)
lib.removeAce('group.admin', 'command.say')
```
</Tab>
</Tabs>
* principal: `string`
* ace: `string`
* allow: `boolean`
### lib.addPrincipal
Assigns a principal to a parent principal. Children inherit permissions from the parent.
<Tabs items={["Lua", "JS"]}>
<Tab>
```lua
lib.addPrincipal(child, parent)
lib.addPrincipal('player.1', 'group.moderator')
```
</Tab>
<Tab>
```ts
import lib from '@overextended/ox_lib/server'
lib.addPrincipal(child, parent)
lib.addPrincipal('player.1', 'group.moderator')
```
</Tab>
</Tabs>
* child: `string`
* parent: `string`
### lib.removePrincipal
Removes a principal from a parent principal.
<Tabs items={["Lua", "JS"]}>
<Tab>
```lua
lib.removePrincipal(child, parent)
lib.removePrincipal('player.1', 'group.moderator')
```
</Tab>
<Tab>
```ts
import lib from '@overextended/ox_lib/server'
lib.removePrincipal(child, parent)
lib.removePrincipal('player.1', 'group.moderator')
```
</Tab>
</Tabs>
* child: `string`
* parent: `string`
Loaded 100 of 229 files, more files were not shown because too many files have changed in this diff. Show more