Início › Documentação › Instalação · origen_inventory

Instalação · origen_inventory

Segue os passos abaixo para instalar origen_inventory no teu servidor.


1. Adiciona o recurso ao teu servidor

Copia a pasta origen_inventory para o teu diretório de recursos e adiciona-a ao teu server.cfg.

A ordem dos ensure é importante: todas as dependências têm de estar a correr antes de origen_inventory.

cfg
# server.cfg
 
ensure oxmysql
ensure ox_lib
ensure qb-core            # or es_extended / qbx_core
 
# Optional integrations
ensure qs-smartphone-pro  # or lb-phone
ensure origen_clothing    # only if you use Clothes-As-Item
 
ensure origen_inventory

Nunca arranques origen_inventory antes de oxmysql e do núcleo da tua framework. Sem eles, o driver da base de dados e a camada de bridge não serão inicializados e os inventários não vão carregar.


2. Substitui o teu inventário anterior

Se estás a migrar de outro recurso de inventário, tens de o remover (ou desativar) antes de arrancares origen_inventory. Só pode existir um fornecedor de inventário ativo de cada vez.

Se outros scripts teus dependerem dos exports de qb-inventory ou ox_inventory, abre fxmanifest.lua e retira o comentário da linha provide correspondente para que essas chamadas a exports sejam resolvidas em origen_inventory:

lua
-- Uncomment if you have old scripts that use qb-inventory
-- provide 'qb-inventory'
 
-- Uncomment if you have qbx_core installed
-- provide 'ox_inventory'

3. Importa o esquema SQL

Importa o ficheiro origen_inventory.sql para a tua base de dados. Cria as quatro tabelas necessárias ao recurso: gloveboxitems, stashitems, trunkitems, origen_customitems e origen_inventory_equipped_clothes.

sql
CREATE TABLE IF NOT EXISTS `gloveboxitems` (
    `id` INT(11) NOT NULL AUTO_INCREMENT,
    `plate` VARCHAR(255) NOT NULL COLLATE 'latin1_swedish_ci',
    `items` LONGTEXT NULL DEFAULT NULL COLLATE 'utf8mb4_bin',
    `label` VARCHAR(100) NULL DEFAULT NULL COLLATE 'latin1_swedish_ci',
    `slots` INT(11) NULL DEFAULT NULL,
    `personal` VARCHAR(255) NULL DEFAULT NULL COLLATE 'latin1_swedish_ci',
    `weight` INT(11) NULL DEFAULT NULL,
    `job` VARCHAR(100) NULL DEFAULT NULL COLLATE 'latin1_swedish_ci',
    PRIMARY KEY (`plate`) USING BTREE,
    INDEX `id` (`id`) USING BTREE
)
COLLATE='latin1_swedish_ci'
ENGINE=InnoDB
AUTO_INCREMENT=152;
 
CREATE TABLE IF NOT EXISTS `stashitems` (
    `id` INT(11) NOT NULL AUTO_INCREMENT,
    `stash` VARCHAR(255) NOT NULL COLLATE 'latin1_swedish_ci',
    `items` LONGTEXT NULL DEFAULT NULL COLLATE 'utf8mb4_bin',
    `label` VARCHAR(100) NULL DEFAULT NULL COLLATE 'latin1_swedish_ci',
    `slots` INT(11) NULL DEFAULT NULL,
    `job` VARCHAR(100) NULL DEFAULT NULL COLLATE 'latin1_swedish_ci',
    `personal` VARCHAR(255) NULL DEFAULT NULL COLLATE 'latin1_swedish_ci',
    `weight` INT(11) NULL DEFAULT NULL,
    PRIMARY KEY (`stash`) USING BTREE,
    INDEX `id` (`id`) USING BTREE
)
COLLATE='latin1_swedish_ci'
ENGINE=InnoDB
AUTO_INCREMENT=1;
 
CREATE TABLE IF NOT EXISTS `trunkitems` (
    `id` INT(11) NOT NULL AUTO_INCREMENT,
    `plate` VARCHAR(255) NOT NULL COLLATE 'latin1_swedish_ci',
    `items` LONGTEXT NULL DEFAULT NULL COLLATE 'utf8mb4_bin',
    `label` VARCHAR(100) NULL DEFAULT NULL COLLATE 'latin1_swedish_ci',
    `personal` VARCHAR(255) NULL DEFAULT NULL COLLATE 'latin1_swedish_ci',
    `weight` INT(11) NULL DEFAULT NULL,
    `slots` INT(11) NULL DEFAULT NULL,
    `job` VARCHAR(100) NULL DEFAULT NULL COLLATE 'latin1_swedish_ci',
    PRIMARY KEY (`plate`) USING BTREE,
    INDEX `id` (`id`) USING BTREE
)
COLLATE='latin1_swedish_ci'
ENGINE=InnoDB
AUTO_INCREMENT=1;
 
DROP TABLE IF EXISTS `origen_customitems`;
CREATE TABLE `origen_customitems` (
    `name` VARCHAR(100) NOT NULL COLLATE 'utf8mb4_unicode_ci',
    `label` VARCHAR(255) NOT NULL COLLATE 'utf8mb4_unicode_ci',
    `weight` INT(11) NOT NULL DEFAULT '0',
    `type` VARCHAR(50) NOT NULL DEFAULT 'item' COLLATE 'utf8mb4_unicode_ci',
    `image` VARCHAR(255) NULL DEFAULT NULL COLLATE 'utf8mb4_unicode_ci',
    `description` TEXT NULL DEFAULT NULL COLLATE 'utf8mb4_unicode_ci',
    `unique` TINYINT(1) NOT NULL DEFAULT '0',
    `rarity` VARCHAR(50) NULL DEFAULT NULL COLLATE 'utf8mb4_unicode_ci',
    `stack` TINYINT(1) NOT NULL DEFAULT '0',
    `close` TINYINT(1) NOT NULL DEFAULT '1',
    `server` LONGTEXT NULL DEFAULT NULL COLLATE 'utf8mb4_bin',
    `client` LONGTEXT NULL DEFAULT NULL COLLATE 'utf8mb4_bin',
    `decay` INT(11) NULL DEFAULT NULL,
    `buttons` LONGTEXT NULL DEFAULT NULL COLLATE 'utf8mb4_bin',
    PRIMARY KEY (`name`) USING BTREE,
    CONSTRAINT `server` CHECK (json_valid(`server`)),
    CONSTRAINT `client` CHECK (json_valid(`client`)),
    CONSTRAINT `buttons` CHECK (json_valid(`buttons`))
)
COLLATE='utf8mb4_unicode_ci'
ENGINE=InnoDB
;
 
CREATE TABLE IF NOT EXISTS `origen_inventory_equipped_clothes` (
    `identifier` VARCHAR(50) NOT NULL COLLATE 'utf8mb4_unicode_ci',
    `data` LONGTEXT NULL DEFAULT NULL COLLATE 'utf8mb4_bin',
    `last_updated` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    PRIMARY KEY (`identifier`) USING BTREE,
    CONSTRAINT `data_json` CHECK (json_valid(`data`))
)
COLLATE='utf8mb4_unicode_ci'
ENGINE=InnoDB
;

O ficheiro de importação elimina e volta a criar origen_customitems. Se já tiveres itens personalizados registados, faz uma cópia de segurança antes de voltares a executar o SQL.


4. Itens

origen_inventory inclui o seu próprio dicionário de itens (config/items.lua e config/weapons.lua). Ao substituíres o teu inventário anterior:


5. Configuração da bridge do ESX

Este passo só é necessário se usares ESX (es_extended). Os utilizadores de QBCore e QBX podem saltar para o passo 6.

origen_inventory inclui dois ficheiros de override que têm de ser colocados dentro de es_extended para que a framework delegue todas as chamadas de inventário em origen_inventory em vez de no seu inventário integrado.

Onde colocar os ficheiros

Copia os dois ficheiros da pasta bridge/esx/overrides/ de origen_inventory para o teu recurso es_extended:

Ficheiro de origem (dentro de origen_inventory) Destino (dentro de es_extended)
bridge/esx/overrides/origeninventory.lua es_extended/overrides/origeninventory.lua
bridge/esx/overrides/origeninventory_player.lua es_extended/overrides/origeninventory_player.lua

Depois, garante que ambos os ficheiros estão declarados em es_extended/fxmanifest.lua dentro de server_scripts:

lua
-- es_extended/fxmanifest.lua
server_scripts {
  -- ... existing entries ...
  'overrides/origeninventory.lua',
  'overrides/origeninventory_player.lua',
}

O que faz cada ficheiro

origeninventory.lua — substitui as funções de itens e de itens utilizáveis do ESX para que as chamadas a ESX.GetItemLabel, ESX.RegisterUsableItem e ESX.UseItem sejam encaminhadas para origen_inventory em vez do dicionário do ESX por omissão. Trata também do dinheiro inicial das contas e dos itens iniciais do inventário das personagens novas.

lua
if Config.CustomInventory ~= "origen_inventory" then return end
 
MySQL.ready(function()
    TriggerEvent("__cfx_export_origen_inventory_Items", function(ref)
        if ref then
            ESX.Items = exports.origen_inventory:Items()
        end
    end)
end)
 
---@diagnostic disable-next-line: duplicate-set-field
ESX.GetItemLabel = function(itemName)
    local item = exports.origen_inventory:Items(itemName)
    if item then
        return item.label
    end
 
    print(('[^3WARNING^7] Attemting to get invalid Item -> ^5%s^7'):format(itemName))
end
 
---@diagnostic disable-next-line: duplicate-set-field
function ESX.RegisterUsableItem(item, cb)
    Core.UsableItemsCallbacks[item] = cb
    exports.origen_inventory:CreateUseableItem(item, cb)
end
 
---@diagnostic disable-next-line: duplicate-set-field
function ESX.UseItem(source, item, ...)
    local src, itm = source, item
    if type(src) == 'string' then item = src source = itm end
 
    if ESX.Items[item] then
        return exports['origen_inventory']:UseItem(item, source, ...)
    else
        print(('[^3WARNING^7] Item ^5"%s"^7 was used but does not exist!'):format(item))
    end
end
 
exports("GetUseablesItems", function()
    return Core.UsableItemsCallbacks
end)
 
function setPlayerInventory(playerId, xPlayer, inventory, isNew)
    if isNew then
        local shared = json.decode(GetConvar("inventory:accounts", '"money"'))
 
        for i = 1, #shared do
            local name = shared[i]
            local account = Config.StartingAccountMoney[name]
            if account then
                exports.origen_inventory:AddItem(playerId, name, account)
            end
        end
 
        if Config.StartingInventoryItems and type(Config.StartingInventoryItems) == "table" then
            for item, count in pairs(Config.StartingInventoryItems) do
                exports.origen_inventory:AddItem(playerId, item, count)
            end
        end
    end
end

origeninventory_player.lua — injeta Core.PlayerFunctionOverrides.OrigenInventory, que substitui os métodos de inventário do jogador por omissão (getInventory, addInventoryItem, removeInventoryItem, hasItem, addWeapon, canCarryItem, etc.) pelos equivalentes de origen_inventory. Assim garante-se que qualquer chamada interna do ESX que toque no inventário do jogador passa por origen_inventory.

lua
------ Dont touch this file unless you know what you are doing
------ This file is used to override the inventory functions
---
---
---- Origen_File_Version - 4
---
---
if Config.CustomInventory ~= "origen_inventory" then return end
 
Core.PlayerFunctionOverrides.OrigenInventory = {
  getInventory = function(self)
    return function(minimal)
      local inventory = exports.origen_inventory:GetPlayerInventory(self.source)
      return inventory
    end
  end,
 
  getLoadout = function(self)
    return function()
      return {}
    end
  end,
 
  getInventoryItem = function(self)
    return function(name, metadata)
      local item = exports.origen_inventory:getItem(self.source, name)
      if not item then
        return {
          count = 0,
        }
      end
      return item
    end
  end,
 
  addInventoryItem = function(self)
    return function(name, count, metadata, slot)
      return exports.origen_inventory:AddItem(self.source, name, count or 1, metadata, slot, true)
    end
  end,
 
  removeInventoryItem = function(self)
    return function(name, count, metadata, slot)
      return exports.origen_inventory:RemoveItem(self.source, name, count or 1, metadata, slot, false)
    end
  end,
 
  setInventoryItem = function(self)
    return function(name, count, metadata)
      return exports.origen_inventory:SetInventoryItems(self.source, name, count, metadata)
    end
  end,
 
  save = function(self)
    return function(inventory)
      Core.SavePlayer(self)
    end
  end,
 
  canCarryItem = function(self)
    return function(name, count, metadata)
      return exports['origen_inventory']:CanCarryItem(self.source, name, count)
    end
  end,
 
  canSwapItem = function(self)
    return function(firstItem, firstItemCount, testItem, testItemCount)
      return true
    end
  end,
 
  setMaxWeight = function(self)
    return function() end
  end,
 
  addWeapon = function(self)
    ---@param weaponName item weapon
    ---@param ammo amount
    return function(weaponName, ammo)
      return exports['origen_inventory']:GiveWeaponToPlayer(self.source, weaponName, ammo)
    end
  end,
 
  addWeaponComponent = function(self)
    return function() end
  end,
 
  addWeaponAmmo = function(self)
    return function() end
  end,
 
  updateWeaponAmmo = function(self)
    return function() end
  end,
 
  setWeaponTint = function(self)
    return function() end
  end,
 
  getWeaponTint = function(self)
    return function() end
  end,
 
  removeWeapon = function(self)
    return function() end
  end,
 
  removeWeaponComponent = function(self)
    return function() end
  end,
 
  removeWeaponAmmo = function(self)
    return function() end
  end,
 
  hasWeaponComponent = function(self)
    return function()
      return false
    end
  end,
 
  hasWeapon = function(self)
    return function()
      return false
    end
  end,
 
  hasItem = function(self)
    return function(name, metadata)
      return exports.origen_inventory:getItem(self.source, name, metadata)
    end
  end,
 
  getWeapon = function(self)
    return function() end
  end,
}

Ambos os ficheiros protegem-se com if Config.CustomInventory ~= "origen_inventory" then return end, por isso é seguro deixá-los no lugar se algum dia mudares de inventário: simplesmente não farão nada.


6. Configura o recurso

Abre config.lua, config_sv.lua e os ficheiros dentro de config/ e ajusta-os ao teu servidor. Consulta a página de Configuração para ver a lista completa de opções.

O mínimo que deves rever antes de entrares em produção:


7. Verifica a instalação

Depois de arrancares o servidor, entra com um jogador e confirma que: