All resources

rsg-weaponcomp – Technical Docs (v3.5.0)#

Weapon customisation for RSG Framework (RedM). Players place a portable gunsmith workbench, then use it to change parts, materials, engravings, tints and wraps on the weapon in their hands, with a live 3D preview. This document covers the architecture, data formats, every event, callback and command, configuration, security model and how to extend the script.

Contents#

  1. Overview and dependencies
  2. Files
  3. How it works
  4. Configuration
  5. Data formats
  6. Events, callbacks, commands and items
  7. Exports and helper APIs
  8. Integration examples
  9. Persistence and database
  10. Security model
  11. Discord logging
  12. Locales
  13. Server owner how-tos
  14. Troubleshooting

1. Overview and dependencies#

DependencyUsed for
rsg-corePlayer data, callbacks, notify, progress bar, DrawText, locales, commands, usable items
rsg-inventoryWeapon items (info data), CanAddItem, item box
rsg-weaponsweaponInHands() export (weapon hash → serial)
rsg-targetTarget option on placed workbenches
rsg-gizmoWorkbench placement (Place, Cancel, IsPlacementValid)
oxmysqlplayer_weapons and player_weapons_custom tables

There is no ox_lib or ox_target dependency. Optional: rsg-log (mirror of the Discord logs).


2. Files#

FileSidePurpose
fxmanifest.lua–Manifest; shared scripts, NUI page, dependencies
shared/config.luasharedWorkbench, items, camera, commands, prices, restrictions, all component lists, damage modifiers
shared/utils.luasharedWeaponComp helpers: factory categories, apply order, price calculation
client/client.luaclientWorkbench props and targets, customisation flow, orbit camera, NUI callbacks, setup / pack-up
client/inhands.luaclientRe-applies saved components when a weapon is drawn, scope commands
client/inspect.luaclientNative weapon inspection, cleaning with a repair kit
client/maintenance.luaclientGun oil (Maintenance helpers and the oilWeapon event)
client/propplace.luaclientWorkbench placement through rsg-gizmo
client/dataview.luaclientBuffer helper used for weapon stats natives
server/database.luaserverEnsureDatabase(): creates the tables and adds missing columns on start
server/server.luaserverPurchases, reset, whitelist, workbench persistence and access, admin commands, discount / skill / materials, presets, identity, repair, gun oil
server/config.luaserverDiscord webhooks (never sent to clients)
server/discord.luaserverDiscord.Log, Discord.Security, Discord.FormatComponents
server/versionchecker.luaserverGitHub version check
html/index.html, script.js, style.cssNUICustomisation menu
installation/database.sql–Database schema (manual install; identical to what database.lua creates)
locales/*.jsonshareden, de, el, es, fr, ja, nl, pl, pt-br, ro, ru

Load order (from fxmanifest.lua): shared/config.lua → shared/utils.lua → client/*.lua; on the server server/config.lua → server/discord.lua → server/database.lua → server/server.lua → server/versionchecker.lua.


3. How it works#

3.1 Placing a workbench#

  1. The player uses the gunsmith item. The server (CreateUseableItem) checks Config.RequiredJob and sends rsg-weaponcomp:client:createprop with { propmodel, item }.
  2. client/propplace.lua calls rsg-gizmo:
    local res = exports['rsg-gizmo']:Place(propmodel, {
        rotation = 'z',
        maxDistance = Config.PlaceDistance or 5.0,
    })
    if not res then return end -- cancelled or invalid
    TriggerEvent('rsg-weaponcomp:client:setupgunzone', res.coords, res.heading or res.rotation.z)
    Place blocks until the player confirms or cancels, so it runs in its own thread.
  3. setupgunzone (client) checks range, overlap with other workbenches (Config.gunZoneSize) and the player's workbench count (rsg-weaponcomp:server:countprop), then plays a cancellable progress bar (Config.SetupTime).
  4. When the bar completes the client sends rsg-weaponcomp:server:createnewprop(coords, heading). The server re-validates everything (section 10), takes the item, inserts the row and syncs Config.PlayerProps to every client.
  5. Clients spawn the prop when within the render distance and attach an rsg-target option to it.

3.2 Customising a weapon#

  1. The player holds a weapon and targets the workbench → Use Gunsmith (onUseGunsmith). The weapon must have a serial from rsg-weapons (bows and melee use the weapon hash as serial) and must not be in Config.WeaponRestriction.
  2. startCustomisation freezes and hides the ped, creates a weapon object on the workbench, starts the orbit camera and the camera prompts, and fetches the saved components with rsg-weaponcomp:server:getPlayerWeaponComponents.
  3. GetAvailableComponents(weaponName, wHash) merges the weapon's Config.Specific lists with its weapon-type Config.Shared lists (specific wins; shared categories are filtered by Config.SharedRequires). FRAME_VERTDATA is always excluded from the menu.
  4. The NUI receives an ordered category array (action = 'open'). Each pick sends the componentChanged NUI callback; the client applies it to the preview object and returns the new price (updatePrice).
  5. Purchase sends rsg-weaponcomp:server:purchase(serial, wHash, weaponName, comps). Reset sends rsg-weaponcomp:server:reset. The server whitelists the components, works out the price itself, charges and saves.
  6. When the weapon is drawn later, client/inhands.lua re-applies the saved components (section 3.3).

3.3 Re-applying components#

inhands.lua polls the held weapon every 500 ms. When it changes (or on /loadweapon) it triggers rsg-weaponcomp:client:reloadWeapon, which:

  1. fetches the saved components,
  2. removes every available component from the ped's weapon,
  3. builds the loadout: saved parts plus the factory part (first list entry) for every structural slot (BARREL, GRIP, SIGHT, CLIP, TUBE, MAG, STOCK) that was not modified,
  4. applies the loadout in WeaponComp.Priority order, then re-applies finishes three more times because they sometimes do not stick on the first pass.

3.4 Pricing#

WeaponComp.ChangePrice(current, new) (shared, so the NUI total and the server charge always agree):

  • a new or changed category costs Config.price[category],
  • removing a category back to factory costs Config.price[category] * Config.RemovePrice,
  • the total is rounded to cents,
  • the server charges from Config.PaymentType using RemoveMoney.

Factory structural parts (WeaponComp.FactoryCategories) are never stored and never charged.

3.5 Maintenance#

  • Repair kit (Config.RepairItem): rsg-weaponcomp:server:useRepairKit takes one kit and sets item.info.quality = 100. It refuses when the weapon is already at 100.
  • Gun oil (Config.GunOilItem): rsg-weaponcomp:server:useGunOil takes one oil; the client then clears dirt and soot (visual only, no condition change).
  • Both are available at the workbench (menu) and via the inspect command / gun oil item.

4. Configuration#

4.1 shared/config.lua#

OptionDefaultDescription
PlayerProps{}Runtime list of placed workbenches (filled from the database, do not edit)
PlaceDistance5.0Maximum placement range from the player (gizmo maxDistance and server check)
UseDistance6.0Server-checked distance to a workbench for purchase / reset
SetupTime10000ms of the cancellable set-up bar after placing
RepairItem'weapon_repair_kit'Repair kit item
GunOilItem'weapon_gun_oil'Gun oil item; nil disables gun oil
GunOilTime6000ms of the oiling animation
Gunsmithitem'gunsmith'Workbench item
RequiredJobnilJob name required to place a workbench (nil = anyone)
Gunsmithprop`p_gunsmithprops09x`Workbench model (hash)
MaxGunsites6Workbenches per player
PaymentType'cash'Account charged (cash, bank, ...)
animationSave10000Save animation time (ms)
AutoDatabasetrueCreate / upgrade the tables on start (false = import installation/database.sql yourself)
AllowPushToTalkWhileOpentrueKeep push-to-talk usable while the menu has focus
PushToTalkControls{ 0x4BC9DABB }Controls re-enabled while the menu is open
DefaultAccess'everyone'Who may use a new player workbench: everyone, owner, job, gang
WorkbenchExpireDays0Remove player workbenches unused for this many days (0 = never; public benches never expire)
AdminPermission'admin'Permission for the admin commands (RSGCore.Functions.HasPermission)
CommandAdminPlace / CommandAdminList / CommandAdminRemovecreateworkbench / listworkbenches / removeworkbenchAdmin command names
GunsmithJobs{ gunsmith = { discount = 0.25, requireDuty = true } }Discount on every purchase, reset and identity change for holders of the job (capped at 90%)
Skilltable, Enabled = falseMetaKey (player metadata), XPPerPurchase, XPJobBonus, Levels (XP for level 1..n), Unlocks (category → minimum level)
PartItems{}{ CATEGORY = { { item = 'steel', amount = 1 } } }: items taken for each part bought in that category
MaxPresets5Saved loadouts per player and weapon
IdentitytableEnabled, NamePrice, EngravePrice, MaxNameLength (24), MaxEngravingLength (40)
gunZoneActivefalseEnable the workbench name text when standing near one
gunZoneSize3.0Minimum distance between workbenches and the text zone radius
showTextZonefalseShow the workbench name with DrawText (needs gunZoneActive)
distBack0.7Camera distance as a multiple of the weapon length
distFov60.0Camera field of view
showStatstrueShow the native weapon stats during inspection
Commandinspect'w_inspect'Inspect / clean command
Commandloadweapon'loadweapon'Re-apply components command
Commandequipscope'scope'Equip scope command
Commanddesequipscope'unscope'Remove scope command
promptstableCamera controls: zoIn, zoOut, ranPos, re, rotLeft, rotRight (control hashes)
camRotateSpeed90.0Orbit speed in degrees per second
AutoFocusDefaulttrueDefault for the in-menu auto part focus (players can toggle it)
PartFocustablePer-category camera focus: at (0.0 stock end to 1.0 muzzle) and zoom
WeaponRestrictionlistWeapon names that cannot be customised
RemovePrice0.3Fraction of the price charged to remove a modification
pricetablePrice per category (see below)
SharedRequirestableRules for when weapon-type categories are offered
SharedtableComponent lists per weapon type: SHORTARM, LONGARM, SHOTGUN, MELEE_BLADE
SpecifictableComponent lists per weapon name

4.2 server/config.lua#

Discord settings only (DiscordConfig); see section 11. Never add this file to shared_scripts; it holds the webhook URLs.

4.3 Price table#

Config.price is keyed by category. Missing keys count as 0.0 (free).

Config.price = {
    ["BARREL"] = 1.00,
    ["SCOPE"] = 2.00,
    ["WRAP_TINT"] = 0.50,
    ["FRAME_ENGRAVING"] = 1.50,
    -- ...
}

A weapon that changes BARREL (1.00) and WRAP_TINT (0.50) and removes SCOPE (2.00) costs 1.00 + 0.50 + 2.00 * 0.3 = 2.10.

4.4 Specific and shared component lists#

-- Weapon-specific: the first entry of a structural category is the factory part
Config.Specific["WEAPON_REVOLVER_CATTLEMAN"] = {
    ["BARREL"] = {
        "COMPONENT_REVOLVER_CATTLEMAN_BARREL_SHORT",
        "COMPONENT_REVOLVER_CATTLEMAN_BARREL_LONG",
    },
    ["GRIP"] = { "COMPONENT_REVOLVER_CATTLEMAN_GRIP", "COMPONENT_REVOLVER_CATTLEMAN_GRIP_PEARL" },
}

-- Weapon-type shared lists (SHORTARM, LONGARM, SHOTGUN, MELEE_BLADE)
Config.Shared["SHORTARM"]["WRAP_TINT"] = { "COMPONENT_SHORTARM_WRAP_TINT_WHITE", ... }

-- Only offer a shared category when the weapon fits
Config.SharedRequires.CYLINDER_MATERIAL = { weapon = { 'REVOLVER' } }  -- weapon name contains 'REVOLVER'
Config.SharedRequires.WRAP_TINT         = { part = 'WRAP' }            -- weapon must define WRAP in Config.Specific

The component lists in shared/config.lua use two small helpers so long runs don't have to be typed out:

seq('COMPONENT_SHORTARM_BARREL_MATERIAL_', 1, 10)   -- 'COMPONENT_SHORTARM_BARREL_MATERIAL_1' ... '_10'
join({ 'COMPONENT_X_WHITE' }, seq('COMPONENT_X_A_', 1, 8))  -- one list, in order

Lists used by several weapons (for example LONGARM_WRAP_TINT) are defined once as a local above Config.Shared and referenced by name. They are shared references: don't modify them at runtime.

Weapon type comes from GetWeapontypeGroup: repeater / rifle / sniper → LONGARM, shotgun → SHOTGUN, pistol / revolver → SHORTARM, melee → MELEE_BLADE, bow → GROUP_BOW (specific lists only).


5. Data formats#

5.1 Weapon item data (item.info)#

Components are stored on the weapon item itself by rsg-inventory:

FieldTypeMeaning
seriestringWeapon serial (set by rsg-weapons)
componentshash{ [category] = componentName }The real modifications, e.g. { BARREL = 'COMPONENT_REVOLVER_CATTLEMAN_BARREL_LONG' }. nil when the weapon is at factory
components{ [category] = label }Display labels built from the locale of each component
qualitynumber 0–100Weapon condition (rsg-weapons); a repair kit sets it to 100
customnamestringCustom weapon name (identity); nil when unset
engravingstringEngraving text (identity); nil when unset
equippedScopebooleanWhether the saved SCOPE is currently mounted
-- Example componentshash
{
    BARREL = 'COMPONENT_REVOLVER_CATTLEMAN_BARREL_LONG',
    GRIP = 'COMPONENT_REVOLVER_CATTLEMAN_GRIP_PEARL',
    FRAME_ENGRAVING = 'COMPONENT_SHORTARM_FRAME_ENGRAVING_2',
}

Rules: keys are category strings, values are component names present in the config whitelist, at most 64 entries. Factory structural parts and FRAME_VERTDATA are never stored.

5.2 Workbench record (Config.PlayerProps[i], also the propdata JSON column)#

{
    gunsitename = 'Gunsmith',     -- localised display name
    gunsiteid   = 'CSID12345678', -- unique id (database primary key)
    propid      = 'PID87654321',  -- unique prop id (used by targets and pack-up)
    item        = 'gunsmith',     -- item returned on pack-up
    x = 0.0, y = 0.0, z = 0.0,    -- position
    h = 0.0,                      -- heading
    propmodel   = 1234567890,     -- model hash
    citizenid   = 'ABC12345',     -- owner
    buildttime  = 1700000000,     -- os.time() when placed
    lastused    = 1700000000,     -- last time someone used it (saved at most every 10 minutes)
    access      = { type = 'everyone' }, -- 'everyone' | 'owner' | 'job' | 'gang' (+ value = job / gang name)
    public      = true,           -- only on admin benches (citizenid = 'public'): usable by all, never expire, not counted in MaxGunsites
}

5.3 Component priority (WeaponComp.Priority)#

Components are applied in this order so tints and materials are not dropped by the game:

PriorityCategory
1–9BARREL, GRIP, STOCK, SIGHT, SCOPE, CLIP, MAG, TUBE
20*RIFLING
30 / 40 / 45*_MATERIAL / *_ENGRAVING / *_ENGRAVING_MATERIAL
50*_TINT
60 / 65 / 70WRAP / WRAP_MATERIAL / WRAP_TINT
35everything else

5.4 NUI messages#

Client → NUI (SendNUIMessage):

actionPayload
openweaponName, serial, components (ordered array of { category, label, items = { { name, hash, label } } }), prices, savedComponents, autoFocus, condition, features (discount, skill, locked, materials, identity, maxPresets, access), locales
close–
updatePriceprice (after discount), base, discount, changed, balance, canAfford (false turns the total red), materials ({ label, amount, have }[]), missing, canUndo, canRedo, comparing
selectionselected ({ category = component }): move every slider after undo / redo / compare / preset
presetslist ({ id, name, components }[])
identityidentity ({ name, engraving }) after a successful save
accessaccess ({ canManage, mode }) when the bench record changes
updateConditioncondition (quality, cleanliness, item counts)
notifynotification text (handled in the NUI)

NUI → client (RegisterNUICallback): closeUI, setAutoFocus, notify, componentChanged { category, component }, undo, redo, compare { on }, revert, purchase, resetWeapon, maintain { kind = 'oil' | 'repair' }, packup, listPresets, savePreset { name }, deletePreset { id }, loadPreset { id }, saveIdentity { name, engraving }, setAccess { mode }, inputFocus { focused } (the menu tells the game when a text box has focus so typed letters don't move the camera).

Push-to-talk: all NUI focus changes go through applyNuiFocus. While the menu is open the per-frame control block disables every control on groups 0, 1 and 2, then re-enables the camera keys and, when Config.AllowPushToTalkWhileOpen is true, the controls in Config.PushToTalkControls. While a text box has focus, SetNuiFocusKeepInput(false) is used so the keys go to the box.


6. Events, callbacks, commands and items#

6.1 Server events (client → server)#

All have a per-player cooldown and validate their arguments.

EventArgumentsCooldownPurpose
rsg-weaponcomp:server:purchaseserial, wHash, weaponName, comps3 sBuy the selected component set
rsg-weaponcomp:server:resetserial, wHash, weaponName3 s (shared with purchase)Strip back to factory (pays RemovePrice)
rsg-weaponcomp:server:createnewpropcoords (vector3), heading (number)5 sCreate a workbench after placement
rsg-weaponcomp:server:removegunsitepropspropid (string)3 sPack up a workbench (owner only)
rsg-weaponcomp:server:setaccesspropid, mode1 sOwner changes who can use the bench (everyone, owner, job, gang; job / gang use the owner's current one)
rsg-weaponcomp:server:adminplacecoords, heading2 sCreate a public workbench (requires Config.AdminPermission)

6.2 Server callbacks (RSGCore.Functions.TriggerCallback / AwaitCallback)#

CallbackArgumentsReturns
rsg-weaponcomp:server:getPlayerWeaponComponentsserial, weaponName{ components?, quality, discount, level?, xp?, identity = { name, engraving } } or nil
rsg-weaponcomp:server:setIdentityserial, weaponName, name, engravingok, identity (needs a usable bench; charges NamePrice / EngravePrice only for non-empty new text; clearing is free)
rsg-weaponcomp:server:listPresetsweaponName{ id, name, components }[]
rsg-weaponcomp:server:savePresetweaponName, name, compsboolean (components validated for that weapon, max MaxPresets)
rsg-weaponcomp:server:deletePresetidboolean (own presets only)
rsg-weaponcomp:server:equipScopeserialboolean
rsg-weaponcomp:server:unequipScopeserialboolean
rsg-weaponcomp:server:getProps–Config.PlayerProps
rsg-weaponcomp:server:countprop–Number of workbenches the caller owns
rsg-weaponcomp:server:useRepairKitserialboolean (kit taken, quality set to 100; 8 s cooldown)
rsg-weaponcomp:server:useGunOilserialboolean (oil taken; 5 s cooldown)

6.3 Client events#

EventArgumentsPurpose
rsg-weaponcomp:client:createprop{ propmodel, item }Start workbench placement with rsg-gizmo
rsg-weaponcomp:client:setupgunzonecoords, headingValidate and run the set-up bar, then ask the server to create the workbench
rsg-weaponcomp:client:confirmpackuppropidPack-up progress bar, then asks the server to remove the workbench
rsg-weaponcomp:client:updatePropDatapropsServer → client sync of Config.PlayerProps
rsg-weaponcomp:client:adminplace–Start gizmo placement of a public workbench (sent by /createworkbench)
rsg-weaponcomp:client:printlistlinesPrint the workbench list to the F8 console (sent by /listworkbenches)
rsg-weaponcomp:client:animationSavedwHashPlays the save animation and reloads the weapon
rsg-weaponcomp:client:reloadWeaponforce?Re-apply saved components (force = true re-applies even when nothing is saved)
rsg-weaponcomp:client:InspectionWeapon–Start the native inspection (cleaning with a repair kit)
rsg-weaponcomp:client:oilWeapon–Start the gun oil clean
rsg-weaponcomp:client:ExitCam–Leave the customisation camera

6.4 Commands#

Names come from the Config.Command* options. The first four (and the scope commands) are available to every player; the three workbench commands need Config.AdminPermission.

CommandRegistered withWhat it does
/w_inspectRSGCore.Commands.AddInspect the held weapon; clean it with a repair kit
/loadweaponRSGCore.Commands.AddRe-apply the saved components to the held weapon
/createworkbenchRSGCore.Commands.Add (AdminPermission)Place a public workbench with rsg-gizmo
/listworkbenchesRSGCore.Commands.Add (AdminPermission)List every workbench (id, owner, position, access) to F8, or the server console when run there
/removeworkbench [id]RSGCore.Commands.Add (AdminPermission)Remove a workbench by gunsiteid, or the nearest one within 5 m. The item is not returned
/scopeRegisterCommand (client)Mount the saved scope
/unscopeRegisterCommand (client)Remove the mounted scope

6.5 Items#

Add these to rsg-core/shared/items.lua (or change the config names):

ItemConfigUse
gunsmithGunsmithitemUsable; places a workbench; returned on pack-up
weapon_repair_kitRepairItemConsumed when cleaning / repairing a weapon below 100%
weapon_gun_oilGunOilItemUsable; consumed by a quick clean
gunsmith        = { name = 'gunsmith',        label = 'Gunsmith Workbench', weight = 5000, type = 'item', image = 'gunsmith.png',        unique = false, useable = true, shouldClose = true, description = 'A portable gunsmith workbench' },
weapon_gun_oil  = { name = 'weapon_gun_oil',  label = 'Gun Oil',            weight = 100,  type = 'item', image = 'weapon_gun_oil.png',  unique = false, useable = true, shouldClose = true, description = 'Cleans dirt and soot off a weapon' },

7. Exports and helper APIs#

Exports#

ExportSideSignatureReturns
GetWeaponRecordserverexports['rsg-weaponcomp']:GetWeaponRecord(serial){ serial, citizenid, components = { [category] = component }, customname, engraving } from player_weapons, or nil

Events for other resources#

rsg-weaponcomp:server:weaponCustomised is triggered on the server after a purchase, reset or identity change: (src, serial, itemName, components, identity) where identity = { name, engraving }. Listen with AddEventHandler (it is not a net event, so clients cannot fire it):

AddEventHandler('rsg-weaponcomp:server:weaponCustomised', function(src, serial, itemName, components, identity)
    -- e.g. log it in rsg-lawman's weapon registry
    print(('%s changed %s (%s): %s'):format(src, itemName, serial, identity.name))
end)

Globals inside the resource#

It also exposes these globals inside its own resource:

GlobalSideSignaturePurpose
WeaponComp.IsFactoryCategory(cat)shared→ booleanTrue for BARREL, GRIP, SIGHT, CLIP, TUBE, MAG, STOCK
WeaponComp.Priority(cat)shared→ numberApplication order of a category
WeaponComp.SortedKeys(comps)shared→ string[]Category keys in application order
WeaponComp.ChangePrice(current, new)shared→ price, changedPrice of going from one component set to another
WeaponComp.SharedCategoryAllowed(cat, weaponName, specific)shared→ booleanWhether a weapon-type category applies to a weapon (Config.SharedRequires); used by the menu and the server whitelist
GetWeaponType(hash)client→ 'SHORTARM' | 'LONGARM' | 'SHOTGUN' | 'MELEE_BLADE' | 'GROUP_BOW' | nilWeapon-type group
GetWeaponNameFromHash(hash)client→ stringWeapon name from hash
GetAvailableComponents(weaponName, wHash)client→ comps, orderMerged specific + shared lists
Maintenance.GetDirt(ped) / ClearDirt(obj) / ClearDegradation(obj)clientDirt, soot and degradation helpers
Discord.Log(channel, src, title, fields[, description])serverSend a log embed
Discord.Security(src, reason, details)serverShortcut for the security channel
Discord.FormatComponents(comps)server→ stringReadable component list

Other resources reach rsg-weaponcomp through the export and event above, its callbacks, or by reading the weapon item data.

EnsureDatabase() (server) creates the tables; it runs automatically when Config.AutoDatabase is true.


8. Integration examples#

8.1 Read a weapon's modifications from another resource (server)#

local RSGCore = exports['rsg-core']:GetCoreObject()

local function getWeaponComponents(src, serial)
    local Player = RSGCore.Functions.GetPlayer(src)
    if not Player then return nil end
    for _, item in pairs(Player.PlayerData.items) do
        if item.type == 'weapon' and item.info and tostring(item.info.serie) == tostring(serial) then
            return item.info.componentshash -- nil when the weapon is at factory
        end
    end
end

8.2 Re-apply components after your script changes a weapon (server → client)#

-- force = true also strips parts when nothing is saved (use after clearing componentshash)
TriggerClientEvent('rsg-weaponcomp:client:reloadWeapon', src, true)

8.3 Open the inspect / clean flow from your own script#

-- client
TriggerEvent('rsg-weaponcomp:client:InspectionWeapon')
-- server
TriggerClientEvent('rsg-weaponcomp:client:InspectionWeapon', src)

The player must hold a serialised short or long arm and own a Config.RepairItem.

8.4 Give a player a workbench item (server)#

local Player = RSGCore.Functions.GetPlayer(src)
if Player and exports['rsg-inventory']:CanAddItem(src, 'gunsmith', 1) then
    Player.Functions.AddItem('gunsmith', 1, nil, nil, 'quest-reward')
    TriggerClientEvent('rsg-inventory:client:ItemBox', src, RSGCore.Shared.Items['gunsmith'], 'add', 1)
end

The player then uses the item to place it. Placement itself needs the gunsmith item in their inventory (the server takes it in createnewprop).

8.5 Start workbench placement from another script (client)#

-- Opens rsg-gizmo placement; the server still removes the item and validates the result
TriggerEvent('rsg-weaponcomp:client:createprop', {
    propmodel = `p_gunsmithprops09x`, -- model hash of the workbench
})

8.6 List all placed workbenches (client)#

-- client (the callback is already registered by rsg-weaponcomp)
RSGCore.Functions.TriggerCallback('rsg-weaponcomp:server:getProps', function(props)
    for _, p in ipairs(props) do
        print(p.gunsiteid, p.citizenid, p.x, p.y, p.z)
    end
end)

8.7 Add a new weapon (or new parts) to the menu#

Add the weapon to Config.Specific and give every new component a locale entry in all 11 files:

-- shared/config.lua
Config.Specific["WEAPON_RIFLE_SPRINGFIELD"]["GRIP"] = {
    "COMPONENT_RIFLE_SPRINGFIELD_GRIP",          -- first entry = factory part
    "COMPONENT_RIFLE_SPRINGFIELD_GRIP_IRONWOOD",
}
// locales/en.json (repeat translated in the other 9 files)
"COMPONENT_RIFLE_SPRINGFIELD_GRIP_IRONWOOD": "Ironwood Stock"

Because the server builds its whitelist from the same config, no other change is needed. Check that the category has a price in Config.price, or it will be free.

8.8 Log a custom entry to Discord (server, inside this resource)#

Discord.Log('workbench', src, 'Workbench inspected', {
    { 'Workbench ID', prop.gunsiteid },
    { 'Location', ('`%.2f, %.2f, %.2f`'):format(prop.x, prop.y, prop.z) },
})
Discord.Security(src, 'Suspicious request', 'details here')

9. Persistence and database#

9.1 Tables#

The tables are created by server/database.lua on start (and by installation/database.sql for a manual install):

CREATE TABLE IF NOT EXISTS `player_weapons` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `serial` varchar(16) NOT NULL,
  `citizenid` varchar(9) NOT NULL,
  `components` varchar(4096) NOT NULL DEFAULT '{}',
  `components_before` varchar(4096) NOT NULL DEFAULT '{}',
  `price` decimal(5,2) NOT NULL DEFAULT 0.00,
  `town` int(11) NOT NULL DEFAULT 0,
  `customname` varchar(32) NULL DEFAULT NULL,
  `engraving` varchar(64) NULL DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS `player_weapons_custom` (
  `gunsiteid` varchar(20) NOT NULL,
  `propid` varchar(20) NOT NULL,
  `citizenid` varchar(50) NOT NULL,
  `item` varchar(50) NOT NULL,
  `propdata` longtext NOT NULL,
  PRIMARY KEY (`gunsiteid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS `player_weapons_presets` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `citizenid` varchar(50) NOT NULL,
  `weapon` varchar(64) NOT NULL,
  `name` varchar(32) NOT NULL,
  `components` varchar(4096) NOT NULL DEFAULT '{}',
  PRIMARY KEY (`id`),
  KEY `idx_citizen_weapon` (`citizenid`, `weapon`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
TableWritten byContent
player_weaponssaveToDatabase after every purchase / resetserial + citizenid identify the weapon; components current JSON, components_before previous JSON, price last price paid
player_weapons_customcreatenewprop / adminplace / removegunsiteprops / setaccessOne row per placed workbench; propdata is the JSON record from section 5.2 (citizenid = 'public' for admin benches)
player_weapons_presetssavePreset / deletePresetSaved loadouts per player and weapon

Automatic setup. With Config.AutoDatabase = true (default) EnsureDatabase() runs CREATE TABLE IF NOT EXISTS for all three tables and, using INFORMATION_SCHEMA, adds the customname and engraving columns to an existing player_weapons table. It never drops or changes existing data. The console prints a green "database tables ready" line, or a red error and the workbenches are not loaded. To install by hand, set Config.AutoDatabase = false and import installation/database.sql.

9.2 Where data lives#

  • Weapon components: primary copy on the weapon item (item.info.componentshash); player_weapons is a backup. If the item has no components, getPlayerWeaponComponents falls back to the database row (checked at most once per weapon per session) and writes the result back to the item.
  • Workbenches: loaded from player_weapons_custom on resource start into Config.PlayerProps, then pushed to clients with rsg-weaponcomp:client:updatePropData on every change and fetched by joining clients (RSGCore:Client:OnPlayerLoaded, onClientResourceStart).

10. Security model#

What the script validates on the server, and what other scripts must not assume.

AreaChecks
Purchase / resetPlayer exists; cooldown; wHash is a number; the player is within Config.UseDistance of a workbench; the weapon item is in the player's own inventory (matched by serial; melee / bows by weapon hash); the weapon is not restricted (checked against the item name, not only the client hash)
ComponentsEvery category = component pair must exist in the config whitelist (built at start from Config.Shared and Config.Specific) and be offered for that weapon: a weapon with its own list for a category only accepts that list, shared categories obey Config.SharedRequires. Non-string keys, unknown parts or more than 64 entries refuse the whole request and are logged to the security channel (nothing is charged)
PriceCalculated server-side with WeaponComp.ChangePrice; the client never sends a price. Payment uses RemoveMoney and the change is only applied after it succeeds
Workbench placementCooldown; coords is a vector3 and heading a number, all finite (NaN / infinity are rejected); Config.RequiredJob; exports['rsg-gizmo']:IsPlacementValid(src, coords, PlaceDistance + 2.0); own distance check; MaxGunsites per player; minimum spacing (gunZoneSize); the item is removed before the row is created
Pack-upCooldown; owner only (citizenid match); within 10.0 of the workbench; refuses when the owner's inventory cannot take the item back, so a workbench is never lost
MaintenanceItem removal happens server-side before the client changes anything; repair refuses at 100% quality
ScopeThe server flips equippedScope and the client only mounts or removes the scope when it returns true
Workbench accessnearWorkbench only counts benches the player may use (everyone, owner, job or gang match against the server's player data). Only the owner can change access or pack up a bench; public benches cannot be packed up. Admin placement and commands require Config.AdminPermission
Discount / skill / materialsDiscount comes from the player's server-side job and duty state. Locked categories are refused using the XP in player metadata; XP is only awarded for purchases that cost money. Materials are checked before charging, taken after the money, and everything is refunded if one cannot be removed
Identity / presetsText is stripped of control characters and <>"\, length-checked (UTF-8 aware) and charged server-side; presets re-run the per-weapon component whitelist, only accept real weapon items and are limited per player and weapon
CooldownsPer player, cleared on playerDropped

Note for other developers: do not trigger the rsg-weaponcomp:server:* events from your own scripts expecting them to bypass checks. They validate the caller's position, inventory and the config whitelist every time.


11. Discord logging#

server/config.lua (DiscordConfig):

OptionDescription
EnabledMaster switch
BotName, Avatar, FooterWebhook identity
SecurityPingRole mention for security alerts, e.g. '<@&123456789012345678>'
RsgLogNameAlso send each log through rsg-log under this name (nil = off)
Webhookspurchase, reset, workbench, repair, security; leave a URL empty to turn that log off
ColoursEmbed colour per channel (decimal)
ShowIdentifiersWhich identifiers to show: license, discord, steam, ip
ShowComponentsList every component in purchase logs
ChannelLogged when
purchaseParts bought or removed
resetAll modifications removed
workbenchWorkbench placed or packed up
repairRepair kit or gun oil used
securityInvalid component data, restricted weapon, no workbench nearby, out-of-range placement or pack-up, touching another player's workbench

Messages are queued per webhook (about one per 1.1 s) to respect Discord's rate limit.


12. Locales#

Locales are handled by rsg-core: @rsg-core/shared/locale.lua in shared_scripts, locales/*.json in files, and locale('key') in code. Set the language in server.cfg:

setr rsg:locale "de"

Languages: en (master), de, el, es, fr, ja, nl, pl, pt-br, ro, ru. Every file has the same keys. Key groups: ui_* (NUI), cl_* (client messages), sv_* (server messages and Discord logs), and one key per category name (BARREL, WRAP_TINT, ...) and per component (COMPONENT_...). Add every new key to all 10 files.


13. Server owner how-tos#

Install

  1. Make sure rsg-core, rsg-inventory, rsg-weapons, rsg-target, rsg-gizmo and oxmysql are started before it.
  2. Start the resource: the tables are created automatically (or set Config.AutoDatabase = false and import installation/database.sql).
  3. Add the items from section 6.5 (and any Config.PartItems materials).
  4. ensure rsg-weaponcomp in server.cfg.
  5. Set your webhooks in server/config.lua (optional).

Restrict workbenches to a job

Config.RequiredJob = 'gunsmith' -- job name from your jobs table

Charge from the bank instead of cash

Config.PaymentType = 'bank'

Make everything cheaper / free

Config.RemovePrice = 0.0
Config.price["BARREL"] = 0.25

Block a weapon

Config.WeaponRestriction[#Config.WeaponRestriction + 1] = 'WEAPON_REVOLVER_LEMAT'

Turn off gun oil

Config.GunOilItem = nil

Change the workbench model

Config.Gunsmithprop = `p_gunsmithprops09x`

Show the workbench name near it

Config.gunZoneActive = true
Config.showTextZone = true

Remove a stuck workbench (SQL)

DELETE FROM player_weapons_custom WHERE gunsiteid = 'CSID12345678';

Restart the resource afterwards so Config.PlayerProps reloads, and give the owner a gunsmith item if needed.

Clear a weapon's saved modifications (SQL backup only)

DELETE FROM player_weapons WHERE serial = '12345678' AND citizenid = 'ABC12345';

The primary copy lives on the weapon item, so the player must also use Reset at a workbench.

Give gunsmiths a discount

Config.GunsmithJobs = { gunsmith = { discount = 0.25, requireDuty = true } } -- 25% off while on duty

Turn on skill levels and lock parts behind them

Config.Skill.Enabled = true
Config.Skill.Unlocks = { BARREL = 2, GRIP = 3 } -- minimum level per category

XP is stored in player metadata under Config.Skill.MetaKey; levels come from Config.Skill.Levels.

Require materials for a part

Config.PartItems = { BARREL = { { item = 'steel', amount = 2 } } }

The item must exist in rsg-core/shared/items.lua. The menu shows the materials on the category and in the purchase confirmation.

Expire abandoned workbenches

Config.WorkbenchExpireDays = 30 -- checked hourly; the item is not returned

Look a weapon up from another resource (e.g. rsg-lawman)

local rec = exports['rsg-weaponcomp']:GetWeaponRecord(serial)
if rec then print(rec.citizenid, rec.customname, rec.engraving, json.encode(rec.components)) end

14. Troubleshooting#

ProblemCause / fix
Menu won't openHold a serialised weapon, stand within targeting range of the workbench, and make sure the weapon is not in WeaponRestriction. Melee and bows are the only weapons allowed without an rsg-weapons serial
"You are too far from a workbench" on purchaseThe server checks Config.UseDistance from the player's real position; move closer to the workbench
Components vanish after drawing the weaponStart rsg-weapons before this resource; use /loadweapon; check the weapon item has info.componentshash
Finishes (tints, materials) look missingThey sometimes need a second pass; the script re-applies them three times after a draw. /loadweapon forces it
Can't place a workbenchCheck MaxGunsites, RequiredJob, that the gunsmith item exists, that you are within PlaceDistance and not within gunZoneSize of another workbench, and that rsg-gizmo is started
Placement preview does not appearrsg-gizmo is not running or not listed before this resource; check the F8 console for export errors
Workbench placed but item not taken / nothing savedIsPlacementValid or one of the server checks failed; look at the security Discord channel and the server console
"SQL table doesn't exist" errorsCheck the console for a red "database setup failed" line (oxmysql permissions). Otherwise make sure Config.AutoDatabase is true, or import installation/database.sql
Players can't use a benchIts access mode may be owner, job or gang; the owner changes it under Workbench access, an admin can place a public bench with /createworkbench
Can't type a name or presetPush-to-talk is unavailable while a text box has focus; click outside the box to use it again
No Discord logsSet the webhook URL for each channel in server/config.lua and keep Enabled = true
Wrong languagesetr rsg:locale "xx" in server.cfg; make sure all 11 locale files have the same keys
Item box not showingThe gunsmith, weapon_repair_kit and weapon_gun_oil items must exist in rsg-core/shared/items.lua

Support: https://rexshack.tebex.store

<!-- BEGIN AUTO-REFERENCE (generated from the code; re-run the generator instead of editing by hand) -->

Technical reference#

Generated from the source of rsg-weaponcomp 3.5.1. Names, arguments and defaults below are read straight from the code.

Dependencies#

rsg-core, rsg-inventory, rsg-weapons, rsg-target, rsg-gizmo, oxmysql

Database#

Tables: player_weapons, player_weapons_custom, player_weapons_presets.

Tables are created automatically on start while Config.AutoDatabase = true (default). Nothing is ever dropped or overwritten. For a manual install set Config.AutoDatabase = false and import installation/database.sql once.

-- shared/config.lua
Config.AutoDatabase = true -- false = import the SQL file yourself

Configuration#

OptionDefaultNotes
Config.PlayerProps{}
Config.PlaceDistance5.0Placement settings
Config.UseDistance6.0max distance (server-checked) from a workbench to buy/reset modifications
Config.SetupTime10000ms to set up a workbench after placing it (cancellable)
Config.RepairItem'weapon_repair_kit'Items and limits
Config.GunOilItem'weapon_gun_oil'quick clean: removes dirt/soot only (does not restore condition)
Config.GunOilTime6000ms the oiling animation takes
Config.Gunsmithitem'gunsmith'
Config.RequiredJobnilJob name required to use gunsmith item (set to nil to disable)
Config.Gunsmithpropp_gunsmithprops09x
Config.MaxGunsites6
Config.PaymentType'cash'
Config.animationSave10000
Config.AutoDatabasetrueDatabase: tables are created automatically on start. Set false to import installation/database.sql manually.
Config.AllowPushToTalkWhileOpentruePush-to-talk: keep voice chat usable while the customisation menu has focus.
Config.PushToTalkControlstable
Config.DefaultAccess'everyone'who may use a new player workbench: 'everyone' | 'owner' | 'job' | 'gang'
Config.WorkbenchExpireDays0remove player workbenches unused for this many days (0 = never)
Config.AdminPermission'admin'Admin tools (public workbenches: anyone can use them, they never expire and do not count toward MaxGunsites)
Config.CommandAdminPlace'createworkbench'
Config.CommandAdminList'listworkbenches'
Config.CommandAdminRemove'removeworkbench'
Config.GunsmithJobstableGunsmith job: discount on every purchase while the player holds the job
Config.SkilltableGunsmith skill: buying parts earns XP; higher levels unlock categories (disabled by default)
Config.Enabledfalse
Config.MetaKey'gunsmithxp'
Config.XPPerPurchase10
Config.XPJobBonus5
Config.Levels{ 0, 100, 300, 600, 1000 }
Config.Unlockstable
Config.PartItemstableMaterials: items consumed per category when buying a part (empty = no materials needed)
Config.MaxPresets5Saved loadouts per weapon
Config.IdentitytableWeapon identity (custom name and engraving written to the weapon item)
Config.NamePrice5.0
Config.EngravePrice10.0
Config.MaxNameLength24
Config.MaxEngravingLength40
Config.gunZoneActivefalseZone settings
Config.gunZoneSize3.0
Config.showTextZonefalse
Config.distBack0.7camera distance as a multiple of the weapon's length
Config.distFov60.0
Config.showStatstrue
Config.Commandinspect"w_inspect"
Config.Commandloadweapon"loadweapon"
Config.Commandequipscope"scope"
Config.Commanddesequipscope"unscope"
Config.promptstablePrompt controls
Config.camRotateSpeed90.0camera orbit speed in degrees per second
Config.AutoFocusDefaulttrueplayers can toggle it in the menu; their choice is remembered
Config.PartFocustable
Config.BARREL{ at = 0.80, zoom = 0.40 }
Config.SIGHT{ at = 0.90, zoom = 0.30 }
Config.SCOPE{ at = 0.50, zoom = 0.35 }
Config.TUBE{ at = 0.75, zoom = 0.40 }
Config.MAG{ at = 0.45, zoom = 0.35 }
Config.CLIP{ at = 0.45, zoom = 0.35 }
Config.CYLINDER{ at = 0.55, zoom = 0.30 }
Config.FRAME{ at = 0.45, zoom = 0.40 }
Config.HAMMER{ at = 0.40, zoom = 0.25 }
Config.TRIGGER{ at = 0.40, zoom = 0.25 }
Config.GRIP{ at = 0.15, zoom = 0.35 }
Config.GRIPSTOCK{ at = 0.15, zoom = 0.35 }
Config.STOCK{ at = 0.10, zoom = 0.35 }
Config.WRAP{ at = 0.60, zoom = 0.40 }
Config.STRAP{ at = 0.45, zoom = 0.50 }
Config.MELEE_BLADE{ at = 0.70, zoom = 0.45 }
Config.WeaponRestrictiontableWeapons that can not be customised at the gunsmith
Config.RemovePrice0.3
Config.pricetable
Config.SharedRequirestable
Config.WRAP_MATERIAL{ part = 'WRAP' }
Config.WRAP_TINT{ part = 'WRAP' }
Config.CYLINDER_MATERIAL{ weapon = { 'REVOLVER' } }
Config.CYLINDER_ENGRAVING{ weapon = { 'REVOLVER' } }
Config.CYLINDER_ENGRAVING_MATERIAL{ weapon = { 'REVOLVER' } }
Config.Sharedtable
Config.Specifictable

Exports#

Server

ExportArgumentsFile
GetWeaponRecordserialserver/server.lua
-- example
local result = exports['rsg-weaponcomp']:GetWeaponRecord(serial)

Callbacks#

CallbackSideArgumentsFile
rsg-weaponcomp:server:getPlayerWeaponComponentsserversource, cb, serial, weaponNameserver/server.lua
rsg-weaponcomp:server:equipScopeserversource, cb, serialserver/server.lua
rsg-weaponcomp:server:unequipScopeserversource, cb, serialserver/server.lua
rsg-weaponcomp:server:getPropsserver_, cbserver/server.lua
rsg-weaponcomp:server:countpropserversource, cbserver/server.lua
rsg-weaponcomp:server:setIdentityserversource, cb, serial, weaponName, name, engravingserver/server.lua
rsg-weaponcomp:server:listPresetsserversource, cb, weaponNameserver/server.lua
rsg-weaponcomp:server:savePresetserversource, cb, weaponName, name, compsserver/server.lua
rsg-weaponcomp:server:deletePresetserversource, cb, idserver/server.lua
rsg-weaponcomp:server:useRepairKitserversource, cb, serialserver/server.lua
rsg-weaponcomp:server:useGunOilserversource, cb, serialserver/server.lua
-- client side
RSGCore.Functions.TriggerCallback('rsg-weaponcomp:server:getPlayerWeaponComponents', function(result)
    -- use result
end, serial, weaponName)

Events#

Server events can be fired by any client, so every handler re-validates the player, the arguments and any permission, distance or cooldown on the server. Never add a reward to a handler without those checks.

EventSideArgumentsFile
rsg-weaponcomp:client:ExitCamclient``client/client.lua
rsg-weaponcomp:client:animationSavedclientwHashclient/client.lua
rsg-weaponcomp:client:updatePropDataclientdataclient/client.lua
RSGCore:Client:OnPlayerLoadedclient``client/client.lua
rsg-weaponcomp:client:setupgunzoneclientcoords, headingclient/client.lua
rsg-weaponcomp:client:confirmpackupclientpropidclient/client.lua
rsg-weaponcomp:client:reloadWeaponclient``client/inhands.lua
rsg-weaponcomp:client:InspectionWeaponclient``client/inspect.lua
rsg-weaponcomp:client:oilWeaponclient``client/maintenance.lua
rsg-weaponcomp:client:createpropclientdataclient/propplace.lua
rsg-weaponcomp:client:adminplaceclient``client/propplace.lua
rsg-weaponcomp:client:printlistclientlinesclient/propplace.lua
rsg-weaponcomp:server:purchaseserverserial, wHash, weaponName, compsserver/server.lua
rsg-weaponcomp:server:resetserverserial, wHash, weaponNameserver/server.lua
rsg-weaponcomp:server:createnewpropservercoords, headingserver/server.lua
rsg-weaponcomp:server:removegunsitepropsserverpropidserver/server.lua
rsg-weaponcomp:server:setaccessserverpropid, modeserver/server.lua
rsg-weaponcomp:server:adminplaceservercoords, headingserver/server.lua
-- from a client script
TriggerServerEvent('rsg-weaponcomp:server:purchase', serial, wHash, weaponName, comps)
-- from a server script
TriggerClientEvent('rsg-weaponcomp:client:ExitCam', source)

Locales#

Language files in locales/: de, el, en, es, fr, ja, nl, pl, pt-br, ro, ru. Set the language with setr rsg:locale "en".

<!-- END AUTO-REFERENCE -->