All resources

rsg-railroad — Developer Docs#

Technical reference for server owners and developers. For a feature overview and install steps see README.md. Version 3.3.0.

Contents#

  1. Dependencies
  2. File overview
  3. Installation
  4. Gameplay rules
  5. Configuration reference
  6. Database schema
  7. Server API (globals and DB.*)
  8. Events (client to server)
  9. Callbacks
  10. Client API, NUI and locales
  11. Feature internals
  12. Code examples
  13. Security model
  14. Troubleshooting

Dependencies#

rsg-core, rsg-inventory, rsg-target, oxmysql. No ox_lib. Optional: rsg-telegram (owner notices) and rsg-weather (weather speed caps). Both are detected at runtime; the features are skipped if the resource is not started.

FeatureImplementation
Locales@rsg-core/shared/locale.lua in shared_scripts; locale('key', ...); convar rsg:locale (> ox:locale > en). The NUI receives the full table from GetLocaleTable()
Server callbacksRegisterCallback(name, function(source, ...) return value end) (server/db.lua) wraps RSGCore.Functions.CreateCallback and lets handlers return
Client callbacksRSGCore.Functions.AwaitCallback(name, nil, ...) (default 10 s timeout, nil on timeout)
Notifyclient Notify(msg, type, duration) -> RSGCore.Functions.Notify; server NotifyPlayer(src, text, type, duration) -> RSGCore:Client:Notify
ProgressRSGCore.Functions.ProgressBar({...})
Targetingexports['rsg-target']:addLocalEntity / removeLocalEntity
MoneyPlayer.Functions.AddMoney / RemoveMoney('cash', amount, reason) only (cash is an item when EnableMoneyItems is on)

File overview#

FilePurpose
fxmanifest.luaLoad order. server/sv_config.lua loads before server/db.lua
shared/config.luaAll gameplay configuration (sent to clients: no secrets)
server/sv_config.luaServer-only config: Discord webhook URLs and options
server/db.luaDB.* queries, RegisterCallback, automatic table install (DB.EnsureTables)
server/webhook.luaWebhook.Send / Webhook.SendFields
server/telegram.luaSendOwnerTelegram, CheckLowSupply (rsg-telegram notices)
server/storage.luaPer-deployment train stash (TrainStorage.OnSpawn / OnPutAway)
server/main.luaTrain buy/sell, deploy/park tracking (ActiveTrains), state sync, maintenance items, ticket revenue, helpers (HasActiveTrain, ClearActiveTrain, IsAtStation, RequireStation, GetCompanyRole, NotifyPlayer, CompanyLabel)
server/companies.luaAddCompanyXP (membership, rank-up, rank reward)
server/missions.luaMission leg sessions, payout split (register / driver wage), railwayman milestone rewards
server/company_ownership.luaBuy/sell/rename company, withdraw, wage percent, stats callbacks
server/employees.luaApplications, approve/reject/fire
server/supplies.luaCompany supply store (add/take)
server/upgrades.luaCompany train upgrades
server/ticketsserver.luaTicket check when boarding as a passenger
server/ambient.luaAmbient NPC train ownership and admin commands
server/robbery.luaRobbery sessions and consequences
client/utils.luaNotify, ApplyNuiFocus, ShowInfoMenu, ConfirmDialog, GetLocaleTable, helpers
client/main.luaStation prompts/blips, OpenStationHUD, NUI callbacks
client/train_spawn.luaSpawn/park/despawn, fuel/water/condition loops, SetupTrainTarget
client/train_control.luaEngine, cruise, brake, GetMaxTrainSpeed
client/train_hud.lua, train_switches.lua, train_ambient.luaHUD, junctions, ambient route trains
client/missions.lua, cargo.luaDelivery and maintenance legs, barrel carry/load/unload
client/passengers.lua, tickets.luaBoarding NPC passengers, ticket check
client/preview.luaTrain preview camera
client/train_robbery.luaOutlaws, engine pressure, ambient robberies
html/index.html, script.js, style.cssNUI (station panel, train HUD, pressure HUD, dialogs)
locales/*.jsonen, de, el, es, fr, ja, nl, pl, pt-br, ro, ru (identical keys)
install/rsg_railroad_full.sqlAll tables (CREATE TABLE IF NOT EXISTS); used by auto-install and manual import
install/shared_items.luaItem snippets to paste into your shared items
install/images/Item icons

Installation#

  1. Add oilcan and trainticket to your items (see install/shared_items.lua); copy install/images/* to your inventory images. Fuel/water items default to resource_coal and fullbucket.
  2. Database: with Config.AutoInstallDatabase = true the tables are created on start and the wage_percent column is added to older databases. For a manual install set it to false and import install/rsg_railroad_full.sql.
  3. ensure rsg-railroad after rsg-core, rsg-inventory, rsg-target and oxmysql.
  4. Put your Discord webhook URLs in server/sv_config.lua.

Gameplay rules#

RuleDetail
RanksConfig.Ranks 1 Brakeman (0 XP) to 5 Foreman (1000 XP). Rank and XP are per company and stored in railroad_companies
CompanyBought for Config.CompanyPurchasePrice, sold back for CompanySellPercent. The owner has a cash register (cash_register)
EmployeesApply at a station; the owner approves/rejects/fires. Approved drivers use company trains
Company trainsDefined in Config.Trains (company, requiredRank, maxSpeed ...). They have no database row (id 0) and use the company's upgrades
Personal trainsBought with buyTrain, stored in railroad_trains, limited by Config.MaxTrainsPerPlayer
Delivery paypay = floor((basePay + destination.pay) * cargo.weight); XP = delivery.xpReward. Maintenance pay = maintenance.basePay
Mission splitIf Config.DriverWages is enabled: wage = floor(pay * wage_percent / 100) goes to the driver in cash, pay - wage to the register
SpeedGetMaxTrainSpeed(): train maxSpeed + upgrade bonus (native cap 30), times the condition multiplier (0.25 + 0.75 * condition%), times the weather multiplier, capped to RobberySlowSpeed during a robbery
Fuel / water / conditionDecrease on timers (Config.Fuel / Water / Condition); refilled with the configured items; a stopped boiler cannot run
TicketsA passenger uses a trainticket (credited to the register at Config.TicketPrice) or pays Config.MarkupPrice in cash. Owners ride free
Passenger revenueStopping at a station with NPC passengers pays passengers * PassengerSystem.TicketPrice; CompanyShare goes to the register, the rest to the driver

Configuration reference#

Gameplay options are in shared/config.lua. Only the keys most often changed are listed; every block is commented in the file.

KeyDefaultDescription
Config.AutoInstallDatabasetrueCreate/verify tables on start
Config.MaxTrainsPerPlayer5Personal train cap
Config.ServerInteractRadius25.0Server-side station distance for menu actions
Config.TrainDespawnDist250Auto-despawn distance from the player
Config.TicketItem / TicketPrice / MarkupPricetrainticket / 20 / 25Ticket economics
Config.CompanyPurchasePrice / CompanySellPercent50000 / 0.5Company market
Config.SupplyItemscoal, bucket, oilItems the company store accepts
Config.Fuel / Water / Conditionsee fileItem, refill amount, decrease interval/amount
Config.Ranks5 rankslabel, xpRequired, payMultiplier
Config.Companies4 companieslabel, shortLabel, blipColor, description
Config.Trainslistmodel, label, company, cost, sellPrice, maxFuel, maxWater, maxCondition, maxSpeed, requiredRank, upgradeable, hasPassengerCars
Config.Stationslistid, label, company, coords, spawnCoords, passengerSpawn, hasWaterTower, waterTowerCoords, hasMaintenanceDepot, depotCoords
Config.Upgradesspeed/fuel/water/durability tierslabel, cost, itemCost = { item, amount }, bonus
Config.Missionssee fileMinLegSeconds, delivery (basePay, xpReward, jobLegs, cargoTypes), maintenance (basePay, xpReward, requiredRank, locations)
Config.DeliveryDestinationslistcoords, label, pay, isWest, radius
Config.CargoDeliverysee fileBarrel prop, platform positions, carry offsets (several values still marked PLACEHOLDER in the file)
Config.TrainStoragesee fileSlots/weight per train model, wipe-on-put-away warnings
Config.PassengerSystemsee fileBoarding counts, ticket price/XP, CompanyShare
Config.RailwaymanRewardslistOne-time milestones: id, label, condition (trains_owned / total_miles / missions_completed), threshold, cashReward, xpReward
Config.CompanyRankRewardsby rankCash on rank-up
Config.DriverWagessee belowWage split
Config.Telegramsee belowOwner notices
Config.WeatherSpeedCapssee belowWeather multipliers
Config.TrainRobberysee belowRobbery tuning
Config.AllowPushToTalkWhileOpen / PushToTalkControlstrue / { 0x4BC9DABB }Push-to-talk while a NUI has focus
Config.DriverWages = {
    Enabled = true, DefaultPercent = 0, MaxPercent = 60, OwnerEarnsWage = false,
}
Config.Telegram = {
    Enabled = true, LowSupplyThreshold = 5, LowSupplyCooldown = 3600,
}
Config.WeatherSpeedCaps = {
    Enabled = true,
    Multipliers = { shower = 0.9, rain = 0.85, thunderstorm = 0.7, hurricane = 0.5,
                    fog = 0.8, snow = 0.8, blizzard = 0.55, whiteout = 0.5, sandstorm = 0.6 },
}

Config.TrainRobbery keys: Enabled, AmbientEnabled, AmbientCheckInterval, AmbientChance, AmbientFollowMs, AmbientMaxPlayerDist, PlayerChance, SafeZoneRadius, ManualStopRobRadius, TrainStopSpeed, RobberySlowSpeed, BoardTrain, BoardDistance, BoardSideOffset, EscapeTimeMs, InitialMessageDelay, SpawnAheadDistance, SpawnMultiplier, OutlawCount {min,max}, OutlawAccuracy, OutlawModels, HorseModels, OutlawWeapons, PressureDecayInterval, PressureDecayPerOutlaw, PressureAttackRadius, PressureRecoveryInterval, PressureRecoveryAmount, PressureRepairAmount, PressureRepairTime, RobberyTakePercent, RobberyTakeMin, RobberyTakeMax, CompanyCooldown, StartCooldown, MinSeconds.

Config.TrackSwitches and Config.TrackModels are data only and not read by the scripts.

Server-only (server/sv_config.lua):

Config.Webhooks = {
    Enabled = true, BotName = 'RSG Railroad', BotAvatar = '',
    URLs = { economy = '', robbery = '', employees = '', admin = '' },
    Colors = { success = 3066993, error = 15158332, info = 3447003, warn = 15105570 },
    LogMissionCompletions = false,
}

Database schema#

All tables are in install/rsg_railroad_full.sql.

TablePurposeKey columns
railroad_trainsPersonal trainscitizenid, company_id, train_model, label, fuel, water, condition, upgrade_speed/fuel_cap/water_cap/durability, total_miles, is_parked, parked_station, parked_direction
railroad_companiesPer-player membership per companycitizenid, company_id, rank, xp, missions_completed, total_earnings; unique (citizenid, company_id)
railroad_rewardsClaimed milestone rewardsunique (citizenid, reward_id) (claim uses INSERT IGNORE)
railroad_companies_ownedOwned companiescompany_id (unique), owner_citizenid, owner_name, company_name, cash_register, wage_percent, purchased_at
railroad_employeesApplications and staffcompany_id, citizenid, firstname, lastname, status (pending / approved / rejected), xp, rank, missions_completed, total_earnings; unique (company_id, citizenid)
railroad_company_upgradesCompany upgrades per train modelcompany_id, train_model, upgrade_speed/fuel_cap/water_cap/durability; unique (company_id, train_model)
railroad_company_suppliesCompany store stockcompany_id, item_name, quantity; unique (company_id, item_name)

wage_percent is added automatically to existing installs by DB.EnsureTables() (checked through INFORMATION_SCHEMA, never destructive). Train storage uses rsg-inventory stashes, not these tables.

Server API#

This resource registers no exports. Its server functions are globals shared between its own server files; they are not callable from other resources. To integrate from another resource, use the callbacks and the database (see examples).

Helpers#

FunctionReturns / does
RegisterCallback(name, handler)Registers an rsg-core callback; the handler's return value is sent to the client
NotifyPlayer(src, text, type, duration)rsg-core notification to a player
CompanyLabel(companyId)Display label of a company
GetCompanyRole(companyId, citizenid)'owner' | 'driver' | nil, ownership row, employee row
HasActiveTrain(src)true when the server tracks a deployed train for the player
ClearActiveTrain(src)Forgets the train, wipes its stash, drops mission and robbery sessions
GetPlayerCoordsServer(src)Server-side ped coordinates (OneSync)
GetNearbyStation(src, radius)Closest Config.Stations entry within radius
IsAtStation(src, companyId, radius?) / RequireStation(src, companyId)Distance check (default Config.ServerInteractRadius); RequireStation also notifies
AddCompanyXP(src, citizenid, companyId, xp)Adds XP, handles rank-up and rank reward
CheckRailwaymanRewards(src, citizenid, companyId)Pays any newly met milestone once
SendOwnerTelegram(companyId, subject, message)rsg-telegram message to the company owner (no-op if disabled/not running)
CheckLowSupply(companyId, item, label)Telegram the owner when stock <= LowSupplyThreshold (rate limited)
Webhook.SendFields(category, title, { {name, value}, ... }, type, description?)Discord embed; categories economy / robbery / employees / admin; types success / error / info / warn
ClearMissionSession(src) / ClearRobberySession(src)Drop in-flight sessions

DB.* (server/db.lua, oxmysql, parameterised)#

Companies: GetCompanyOwnership, GetAllOwnedCompanies, GetOwnedCompaniesByCitizen, GetOwnedCompanyCount, PurchaseCompany, SellCompany, SetCompanyName, SetWagePercent, GetCashRegister, AddToCashRegister, WithdrawFromCashRegister (atomic: only succeeds when the register holds enough, returns affected rows). Members: GetCompanyMembership, EnsureCompanyMembership, JoinCompany, AddCompanyXP, SetCompanyRank, IncrementMissions, AddEarnings. Employees: ApplyAsDriver, ApproveEmployee, RejectEmployee, FireEmployee, GetEmployeeByIds, GetEmployeeById, GetEmployeesByCompany, GetPendingApplications, GetPlayerEmployment, IncrementEmployeeMissions, AddEmployeeEarnings, DeleteEmployeesByCompany. Trains: InsertTrain, GetOwnedTrains, GetTrainById, GetCompanyTrains, CountTrains, DeleteTrain, ParkTrain, UnparkTrain, UpdateTrainState/Fuel/Water/Condition, AddMiles. Upgrades: GetCompanyUpgrades, GetCompanyTrainUpgrade, UpsertCompanyUpgrade, DeleteUpgradesByCompany. Supplies: GetCompanySupplies, GetSupplyItem, AddSupplyItem, TakeSupplyItem (atomic), DeleteSuppliesByCompany. Rewards: HasClaimedReward, ClaimReward (atomic, INSERT IGNORE). Setup: EnsureTables.

Events (client to server)#

Every handler resolves source, re-checks the player and validates all arguments. Arguments are untrusted.

EventArgumentsServer checks
rsg-railroad:buyTraintrainIndexAt a station of the train's company, rank, personal limit, cash
rsg-railroad:sellTraintrainIdAt a station, ownership, parked, atomic delete
rsg-railroad:setTrainSpawnedspawned, trainId, modelAt a station, known model, ownership for personal trains, one train per player
rsg-railroad:parkTraintrainId, _, fuel, water, conditionOnly the player's deployed personal train; station derived from server position
rsg-railroad:updateTrainState(trainId, fuel, water, condition), updateFuel / updateWater / updateCondition(trainId, value)ids and valuesDeployed personal train only, clamped to the train's maxima
rsg-railroad:addMilestrainId, milesThrottled (min 5 s), capped by elapsed time and max speed
rsg-railroad:useMaintenanceItemtype, trainId (trainId ignored, the cached deployment is used)Item chosen by the server; removed through rsg-inventory
rsg-railroad:missionLegStartedtype, labelActive train; stores a leg session
rsg-railroad:completeMissiontype, destination, cargo, companyIdCompany role, session, MinLegSeconds, server position at the destination, 15 s cooldown; pay from config
rsg-railroad:ticketRevenuecompanyId, passengersRole, active train, real station, 30 s cooldown, new station each time, count capped
rsg-railroad:buyCompany / sellCompany(companyId), renameCompany(companyId, newName), withdrawFunds(companyId, amount)companyId, ...At the company's station, owner checks, atomic SQL; rename 3-50 chars sanitised
rsg-railroad:setWagePercentcompanyId, percentOwner, at the station, integer within 0..MaxPercent
rsg-railroad:applyAsDriver / approveDriver / rejectDriver / fireDrivercompanyId, employeeId?At the station; owner only except apply
rsg-railroad:addSupply / takeSupplycompanyId, item, qtyAt the station, role, item whitelist, qty cap, atomic stock
rsg-railroad:purchaseUpgradecompanyId, trainModel, upgradeTypeAt the station; owner or approved driver rank 3+
rsg-railroad:openTrainStoragenoneActive train with a stash
rsg-railroad:robberyStartedcompanyIdRobbery enabled, company role, active train, outside SafeZoneRadius of all stations, StartCooldown
rsg-railroad:robberyOccurred / robberyDefeatedcompanyIdNeeds an open robbery session older than MinSeconds; company cooldown; take clamped by config
rsg-railroad:ambientDespawnednoneOnly the ambient owner

Server to client: rsg-railroad:refreshStationData(companyId), rsg-railroad:client:trainpos, rsg-railroad:client:setjunction(args).

Admin commands (admin permission): /trainpos, /setjunction <trackName> <junctionIndex> <0|1>. Client debug command (only with Config.Debug = true): /trainrobbery.

Callbacks#

All are registered with RegisterCallback and called from the client with RSGCore.Functions.AwaitCallback.

CallbackArgumentsReturns
rsg-railroad:getCompanyOwnershipcompanyIdOwnership row (includes wage_percent); cash_register and owner_citizenid only for the owner; nil if unowned
rsg-railroad:getPlayerRolecompanyId'owner' | 'driver' | 'pending' | 'visitor' | 'unowned'
rsg-railroad:getMyEmployeeDatacompanyIdEmployee row with rank/xp from railroad_companies
rsg-railroad:getMyCompanyMembershipcompanyIdMembership row
rsg-railroad:getMyEmploymentnonePlayer's employments
rsg-railroad:getEmployees, getPendingApplicationscompanyIdOwner only, else {}
rsg-railroad:getCompanyStatscompanyIdOwner only
rsg-railroad:getAllCompanyStatsnonePublic leaderboard-style stats
rsg-railroad:getCompanyTrainscompanyIdCompany train list
rsg-railroad:getCompanySuppliescompanyIdRole-gated supply stock
rsg-railroad:getCompanyUpgrades, getTrainModelUpgradecompanyId[, model]Upgrade rows
rsg-railroad:getOwnedTrains, getTrainById[trainId]Caller's personal trains
rsg-railroad:canSpawnTrainnonetrue when no train is deployed
rsg-railroad:getTrainStorageStatenone{ active, stacks }
rsg-railroad:server:useTicketcompanyId'has_ticket' | 'bought_ticket' | 'no_ticket' (10 s repeat cooldown)
rsg-railroad:shouldSpawnAmbientnonetrue for the first client only (ambient ownership)
rsg-railroad:getAmbientStatenonetrue while no company is owned

Client API, NUI and locales#

Client globals (shared between this resource's client files): Notify, LoadModel, LoadTrainCars, GetDistanceBetween, DebugPrint, GetNearestStation, FindTrainConfig, GetLocaleTable, ApplyNuiFocus, ShowInfoMenu, ConfirmDialog, train state (ActiveTrain, ActiveTrainConfig, ActiveTrainData, EngineRunning, TrainFuel, TrainWater, TrainCondition), controls (ToggleEngine, EmergencyBrake, ToggleCruiseForward/Backward, GetMaxTrainSpeed, GetCurrentSpeed), and robbery hooks (IsEnginePressureDamaged, IsRobberySpeedCapActive, IsTrainUnderAttackOrRecovering, FixEnginePressure, TriggerTrainRobbery).

  • ApplyNuiFocus(enable): the only place NUI focus is set. Uses SetNuiFocusKeepInput and a per-frame control whitelist so push-to-talk keeps working.
  • ShowInfoMenu(title, { { title, description }, ... }): read-only NUI list.
  • ConfirmDialog({ header, content, labels = { confirm, cancel } }) -> true/false.

NUI messages (Lua -> JS): openStation, closeStation, openTrainHUD, closeTrainHUD, updateHUD, openInfoMenu, openDialog, showPressureHUD, updatePressureHUD, hidePressureHUD. NUI callbacks (JS -> Lua): closeStation, buyTrain, sellTrain, spawnTrain, parkTrain, despawnTrain, purchaseUpgrade, startMission, buyCompany, sellCompany, renameCompany, setWagePercent, withdrawFunds, applyAsDriver, approveDriver, rejectDriver, fireDriver, addSupply, takeSupply, buyCompanyTrain, previewTrain, closeInfoMenu, dialogResult. Every NUI callback only forwards to a server event that re-validates; the UI is not trusted.

Locales: locales/en.json is the master and every other language has the same keys with the same %s/%d placeholders. NUI texts use t('key', 'fallback') and are filled from GetLocaleTable(). Server notifications use locale() too, so the server language follows rsg:locale.

Feature internals#

Missions and pay#

missionLegStarted records { type, label, startedAt }. completeMission requires the same type/label, at least MinLegSeconds, the server position within radius + 60 m of the destination (delivery) or 10 + 60 m (maintenance), and clears the session after payout (one payout per leg). XP goes through AddCompanyXP, then CheckRailwaymanRewards pays each milestone once.

Driver wages#

wage = floor(pay * pct / 100) with pct = min(wage_percent, Config.DriverWages.MaxPercent). Owners earn no wage unless OwnerEarnsWage. The wage is paid with AddMoney('cash', wage, 'railroad-driver-wage') and pay - wage goes to the register. The owner sets the percent in the station panel (setWagePercent).

Telegram notices#

SendOwnerTelegram calls exports['rsg-telegram']:SendTelegram(ownerCitizenId, subject, message, { senderName = companyLabel }) inside pcall, only when Config.Telegram.Enabled and rsg-telegram is started. Triggers: a driver application, and a supply take that leaves stock at or below LowSupplyThreshold (one message per company+item per LowSupplyCooldown).

Weather speed caps#

GetMaxTrainSpeed() multiplies the speed by Config.WeatherSpeedCaps.Multipliers[weather], where weather is the lowercase string from exports['rsg-weather']:getWeather() (client export). Unlisted weather is unchanged. The new value is used the next time the engine loop re-reads the max speed.

Train robbery#

  1. Every 3 to 5 minutes the client rolls 20% while the driver is in the seat, the engine is running, speed >= 5 and the train is further than SafeZoneRadius from all stations. TriggerTrainRobbery(force) can also be called by other client code.
  2. The client sends robberyStarted(companyId). The server checks role, active train, station safe zone and StartCooldown, then opens a one-shot session.
  3. Outlaws spawn mounted beside the train, ride at it and shoot. Each living outlaw within PressureAttackRadius drains PressureDecayPerOutlaw engine pressure per tick. The train is slowed to RobberySlowSpeed.
  4. Outcomes: all outlaws killed -> robberyDefeated (company XP, no cash); train stopped with an outlaw within ManualStopRobRadius, pressure at zero, or driver killed with an outlaw close -> robberyOccurred (register cut RobberyTakePercent, clamped to RobberyTakeMin..Max, atomic, then CompanyCooldown).
  5. Afterwards the engine cannot start until pressure recovers or the player repairs it with the "Repair Engine Pressure" train target. Ambient robberies are visual only and spawn for ambient trains within AmbientMaxPlayerDist of the player.

Train storage#

Each deployed train gets an rsg-inventory stash sized by Config.TrainStorage.Models[model]. The stash id is regenerated per deployment and cleared whenever the train leaves the world (park, despawn, yard, auto-despawn, death, disconnect, restart). Reverse Direction recreates the entity but keeps the load.

Ambient train#

Only one client at a time owns the ambient NPC train (shouldSpawnAmbient). It is released through ambientDespawned or when that player leaves.

Code examples#

Read a company's state from another client script#

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

local role = RSGCore.Functions.AwaitCallback('rsg-railroad:getPlayerRole', nil, 'heartlands_express')
if role == 'owner' then
    local o = RSGCore.Functions.AwaitCallback('rsg-railroad:getCompanyOwnership', nil, 'heartlands_express')
    print(('Register: $%s, wage share: %s%%'):format(o.cash_register, o.wage_percent))
end

Read railroad data from another server resource (database)#

-- Rank and XP of a player in a company (read only)
local row = MySQL.single.await(
    'SELECT `rank`, xp FROM railroad_companies WHERE citizenid = ? AND company_id = ?',
    { citizenid, 'heartlands_express' })

Write through this resource's events/callbacks instead of editing tables directly, so the validation and webhooks run.

Add a new company train#

-- shared/config.lua -> Config.Trains
{ model = 'engine_config', label = 'Valentine Switcher', company = 'heartlands_express',
  cost = 300, sellPrice = 180, maxFuel = 110, maxWater = 110, maxCondition = 100,
  maxSpeed = 20, requiredRank = 2, upgradeable = true, hasPassengerCars = false },

Add a matching entry in Config.TrainStorage.Models if it should have its own capacity.

Add a station#

-- shared/config.lua -> Config.Stations
{
    id = 'my_station', label = 'My Station', company = 'lemoyne_central',
    coords = vector3(0.0, 0.0, 0.0), spawnCoords = vector3(0.0, 0.0, 0.0),
    passengerSpawn = vector3(0.0, 0.0, 0.0),
    hasWaterTower = false, hasMaintenanceDepot = false,
},

For delivery cargo also add Config.CargoDelivery.PlatformOverrides.my_station = vector4(x, y, z, heading).

Add a delivery destination or a supply item#

-- Config.DeliveryDestinations
{ coords = vector3(1521.84, 428.44, 90.68), label = 'Emerald Siding', pay = 18, isWest = false, radius = 25 },

-- Config.SupplyItems (the item must exist in rsg-inventory)
{ item = 'resource_iron_bar', label = 'Iron Bar', icon = 'wrench' },

Change a wage or weather rule#

Config.DriverWages.MaxPercent = 40
Config.WeatherSpeedCaps.Multipliers.rain = 0.7
Config.WeatherSpeedCaps.Enabled = false -- no weather effect

Send the owner a custom telegram from this resource#

-- inside any server file of rsg-railroad
SendOwnerTelegram(companyId, locale('tg_subject_lowstock'), locale('tg_body_lowstock', 'Coal', 3))

Add a Discord log line#

Webhook.SendFields('economy', 'Custom Event', {
    { 'Player', GetPlayerFullName(Player) .. ' (' .. Player.PlayerData.citizenid .. ')' },
    { 'Company', CompanyLabel(companyId) },
}, 'info')

Add a locale key (all 11 languages)#

Add the same key to every file in locales/, keep placeholders in order, then use it:

NotifyPlayer(src, locale('my_new_key', amount), 'success')   -- server
Notify(locale('my_new_key', amount), 'success')              -- client
t('my_new_key', 'Fallback text')   // NUI (script.js)

Write a safe server event (pattern used throughout)#

RegisterNetEvent('rsg-railroad:myAction', function(companyId, qty)
    local src = source
    local Player = RSGCore.Functions.GetPlayer(src)
    if not Player then return end
    if not GetCompanyRole(companyId, Player.PlayerData.citizenid) then return end
    if not RequireStation(src, companyId) then return end   -- server-side distance
    qty = math.floor(tonumber(qty) or 0)
    if qty < 1 or qty > 50 then return end
    -- ... atomic SQL, then reward
end)

Security model#

  • The client never decides money, items, prices or pay: everything is computed from config on the server.
  • Position checks use the server-side ped position (OneSync), never client-sent coordinates.
  • Fuel, water and condition of personal trains are reported by the client and clamped; company trains (id 0) have no database row and are client-authoritative by design.
  • Money-moving SQL is atomic (WithdrawFromCashRegister, TakeSupplyItem, ClaimReward, train delete).
  • getCompanyOwnership hides cash_register and owner_citizenid from everyone except the owner; staff and application callbacks are role-gated.
  • Mission payouts need a server-seen leg, a minimum travel time and the server position at the destination. Robbery payouts need a server-opened session.
  • Webhook URLs live in server/sv_config.lua, which is never sent to clients.
  • Known limits: ticket revenue and fuel/water/condition for company trains rely on client reports within the checks above; per-driver supply withdrawal limits do not exist.

Troubleshooting#

ProblemCheck
"You need to be at a company station"Server position is further than Config.ServerInteractRadius from a station of that company
Mission finished but nothing paidLeg took less than Config.Missions.MinLegSeconds, or no active train / company role
Train cannot be deployedNot at a station, or the server still thinks a train is out (park or send to yard first)
Webhooks silentURLs must be set in server/sv_config.lua (not shared/config.lua)
Tables missing / SQL errorsConfig.AutoInstallDatabase = true and the DB user can CREATE TABLE/ALTER TABLE; or import install/rsg_railroad_full.sql
Driver wage always 0Owner has not set a percent (DefaultPercent is 0), the player is the owner, or Config.DriverWages.Enabled = false
No telegram to ownerrsg-telegram not started, Config.Telegram.Enabled = false, or the owner's citizenid has no character
Weather does not slow the trainrsg-weather not started, or the weather name is not in Multipliers (names are lowercase)
No robberiesConfig.TrainRobbery.Enabled, driving far from all stations (SafeZoneRadius), engine running, speed >= 5, and the 3 to 5 minute roll; use /trainrobbery with Config.Debug = true to test
Outlaws do not spawnCheck the F8 console for model load warnings; verify OutlawModels / HorseModels exist on your build
Barrels float or clip on the flatbedTune Config.CargoDelivery.TrainAttachOffsets / PlatformOverrides in game
NUI will not release focusClose with Escape/back; ApplyNuiFocus(false) runs on close and on resource stop

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-railroad 3.3.0. Names, arguments and defaults below are read straight from the code.

Dependencies#

rsg-core, rsg-target, oxmysql, rsg-inventory

Database#

Tables: railroad_trains, railroad_companies, railroad_rewards, railroad_companies_owned, railroad_employees, railroad_company_upgrades, railroad_company_supplies.

For a manual install set Config.AutoDatabase = false and import install/rsg_railroad_full.sql once.

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

Configuration#

OptionDefaultNotes
Config.AllowPushToTalkWhileOpentrueWhile the NUI is open, block game controls but allow push-to-talk.
Config.PushToTalkControlstable
Config.Debugfalse
Config.AutoInstallDatabasetrueautomatically creates/verifies all required MySQL tables on resource start (from install/rsg_railroad_full.sql
Config.MaxTrainsPerPlayer5max trains a single player can personally own
Config.ServerInteractRadius25.0server-side: how close (m) to a company station a player must be for buy/sell/manage actions
Config.TrainDespawnDist250despawn if player is far from their train
Config.StationInteractRadius3.0how close to station marker to interact
Config.TicketItem'trainticket'
Config.TicketPrice20.00
Config.MarkupPrice25.00
Config.PassengerSystemtable
Config.Enabledtrue
Config.MaxBoardPerStop10
Config.MinBoardPerStop1
Config.SearchRadius120.0
Config.TicketXP5
Config.DisembarkChance50
Config.MinBoardedToKeep1
Config.BoardingWindowMs38000
Config.BoardWalkSpeed5.0
Config.BoardDistance5.0
Config.StationStopRadius135.0
Config.TrainStopSpeed1.5
Config.CompanyShare0.50
Config.Rankstable
Config.CompanyPurchasePrice50000
Config.CompanySellPercent0.50
Config.SupplyItemstable
Config.Fueltable
Config.Watertable
Config.Conditiontable
Config.Companiestable
Config.Upgradestable
Config.Trainstable
Config.Stationstable
Config.TrackSwitchestable
Config.TrainSetuptable
Config.RouteOneTrainSwitchestable
Config.RouteOneTrainStopstable
Config.RouteThreeTrainSwitchestable
Config.RouteThreeTrainStopstable
Config.TrackModelstable
Config.WeatherSpeedCapstable
Config.Multiplierstable
Config.Telegramtable
Config.LowSupplyThreshold5
Config.LowSupplyCooldown3600
Config.DriverWagestable
Config.DefaultPercent0
Config.MaxPercent60
Config.OwnerEarnsWagefalse
Config.Missionstable
Config.MinLegSeconds20
Config.DeliveryDestinationstable
Config.CargoDeliverytable
Config.PropModel'p_barrel010x'
Config.MaxSimultaneous3
Config.RequiredTrainModel'appleseed_config'
Config.FlatbedCarModel'privateflatcar01x'
Config.PlatformOverridestableneeded (e.g. move it away from doorways/props, face it properly, etc.).
Config.PlatformFallbackCoordsvector4(-164.49, 636.65, 114.03, 111.05)Used only if a mission is somehow started without a station reference.
Config.PlatformBarrelOffsetstablebarrels don't spawn stacked on top of each other.
Config.TrainAttachOffsetstableare clipped into the flatbed deck or float above it.
Config.CarryOffset{ x = 0.0, y = 0.7, z = -0.2 }Proven values from mack-oilcompany's Config.CarryOffsets.barrel (CP_BeltFront attach point).
Config.CarryAnim{ dict = 'mech_carry_box', name = 'walk_heavy' }Proven barrel carry animation from mack-oilcompany's AttachBarrelToPlayer.
Config.CarryMoveRate0.7
Config.PickupRequiresStoppedtrue
Config.MaxTrainSpeedToPickup1.5
Config.DropRadius4.0
Config.AbandonDistance100.0
Config.MinMoveDistance15.0must move at least this far from that spot before "Unload Cargo" appears again.
Config.TrainStoragetable
Config.DefaultSlots20Used for any train model not listed in Models below.
Config.DefaultMaxWeight150000
Config.ModelstablePer-model capacity: bigger engines haul more.
Config.WarnOnFirstOpentrueWarn the player once per deployment, the first time they open storage.
Config.ConfirmOnPutAwaytruethat would destroy a non-empty stash. Never blocks the action.
Config.DistanceWarnPercent0.7carrying cargo, since the auto-despawn is the most common cause of loss.
Config.DistanceWarnInterval15000
Config.TrainPreviewtable
Config.ShowFullConsisttruefalse = show a single car only, chosen by CarIndex below
Config.CarIndex0Used only when ShowFullConsist = false. 0 is the locomotive.
Config.MaxCars12can't spawn dozens of vehicles at once.
Config.CarGap0.4Coupling gap between cars, in metres.
Config.HeightOffset90.0How far above the player the preview is staged.
Config.OrbitRadiusMult0.60reads much more impressive than framing the whole thing small and distant.
Config.MinOrbitRadius15.0
Config.CameraHeightMult0.20
Config.MinCameraHeight4.5
Config.RotateSpeed0.25Degrees per frame the camera orbits. 0 gives a static side-on view.
Config.ExitControl0xCEFD9220than bound to guessed A/D control hashes.
Config.LoadTimeout5000Safety cap on waiting for each model to stream in (ms).
Config.RailwaymanRewardstable
Config.CompanyRankRewardstable
Config.Blipstable
Config.TrainRobberytable
Config.AmbientEnabledtrue
Config.AmbientCheckInterval300000
Config.AmbientChance25
Config.AmbientFollowMs45000
Config.PlayerChance20
Config.SafeZoneRadius500.0
Config.ManualStopRobRadius15.0
Config.RobberySlowSpeed8.0
Config.BoardTraintrue
Config.BoardSideOffset1.2
Config.EscapeTimeMs15000
Config.InitialMessageDelay4000
Config.SpawnAheadDistance80.0
Config.SpawnMultiplier3.0
Config.OutlawCount{ min = 2, max = 4 }
Config.OutlawAccuracy35
Config.OutlawModels{ 'g_m_m_unibanditos_01', 'g_m_m_uniduster_01', 'g_m_m_unicriminals_01Model names checked against rdr3_discoveries peds_list.lua / weapons list:
Config.HorseModels{ 'a_c_horse_kentuckysaddle_black' }
Config.OutlawWeapons{ 'WEAPON_REPEATER_WINCHESTER', 'WEAPON_REVOLVER_CATTLEMAN' }
Config.PressureDecayInterval4000
Config.PressureDecayPerOutlaw4
Config.PressureAttackRadius40.0
Config.PressureRecoveryInterval2000
...10 more options in the config files

Callbacks#

CallbackSideArgumentsFile
rsg-railroad:shouldSpawnAmbientserversourceserver/ambient.lua
rsg-railroad:getCompanyOwnershipserversource, companyIdserver/company_ownership.lua
rsg-railroad:getPlayerRoleserversource, companyIdserver/company_ownership.lua
rsg-railroad:getMyEmployeeDataserversource, companyIdserver/company_ownership.lua
rsg-railroad:getCompanyStatsserversource, companyIdserver/company_ownership.lua
rsg-railroad:getAllCompanyStatsserversourceserver/company_ownership.lua
rsg-railroad:getCompanyTrainsserversource, companyIdserver/company_ownership.lua
rsg-railroad:getEmployeesserversource, companyIdserver/employees.lua
rsg-railroad:getPendingApplicationsserversource, companyIdserver/employees.lua
rsg-railroad:getMyEmploymentserversourceserver/employees.lua
rsg-railroad:getOwnedTrainsserversourceserver/main.lua
rsg-railroad:getTrainByIdserversource, trainIdserver/main.lua
rsg-railroad:canSpawnTrainserversourceserver/main.lua
rsg-railroad:getAmbientStateserver``server/main.lua
rsg-railroad:getMyCompanyMembershipserversource, companyIdserver/main.lua
rsg-railroad:getTrainStorageStateserversourceserver/storage.lua
rsg-railroad:getCompanySuppliesserversource, companyIdserver/supplies.lua
rsg-railroad:server:useTicketserversource, companyIdserver/ticketsserver.lua
rsg-railroad:getCompanyUpgradesserversource, companyIdserver/upgrades.lua
rsg-railroad:getTrainModelUpgradeserversource, companyId, trainModelserver/upgrades.lua
-- client side
RSGCore.Functions.TriggerCallback('rsg-railroad:shouldSpawnAmbient', function(result)
    -- use result
end)

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-railroad:refreshStationDataclientcompanyIdclient/main.lua
rsg-railroad:setAmbientStateclientactiveclient/train_ambient.lua
rsg-railroad:client:trainposclient``client/train_ambient.lua
rsg-railroad:client:setjunctionclientargsclient/train_ambient.lua
rsg-railroad:maintenanceResultclientmType, successclient/train_spawn.lua
rsg-railroad:ambientDespawnedserver``server/ambient.lua
rsg-railroad:buyCompanyservercompanyIdserver/company_ownership.lua
rsg-railroad:sellCompanyservercompanyIdserver/company_ownership.lua
rsg-railroad:renameCompanyservercompanyId, newNameserver/company_ownership.lua
rsg-railroad:setWagePercentservercompanyId, pctserver/company_ownership.lua
rsg-railroad:withdrawFundsservercompanyId, amountserver/company_ownership.lua
rsg-railroad:applyAsDriverservercompanyIdserver/employees.lua
rsg-railroad:approveDriverservercompanyId, employeeIdserver/employees.lua
rsg-railroad:rejectDriverservercompanyId, employeeIdserver/employees.lua
rsg-railroad:fireDriverservercompanyId, employeeIdserver/employees.lua
rsg-railroad:buyTrainservertrainIndexserver/main.lua
rsg-railroad:sellTrainservertrainIdserver/main.lua
rsg-railroad:ticketRevenueservercompanyId, passengerCountserver/main.lua
rsg-railroad:setTrainSpawnedserverspawned, trainId, modelserver/main.lua
rsg-railroad:parkTrainservertrainId, _, fuel, water, conditionserver/main.lua
rsg-railroad:updateTrainStateservertrainId, fuel, water, conditionserver/main.lua
rsg-railroad:updateFuelservertrainId, fuelserver/main.lua
rsg-railroad:updateWaterservertrainId, waterserver/main.lua
rsg-railroad:updateConditionservertrainId, conditionserver/main.lua
rsg-railroad:addMilesservertrainId, milesserver/main.lua
rsg-railroad:useMaintenanceItemservermType, trainIdserver/main.lua
rsg-railroad:missionLegStartedservermissionType, labelserver/missions.lua
rsg-railroad:completeMissionservermissionType, destination, cargo, companyIdserver/missions.lua
rsg-railroad:robberyStartedservercompanyIdserver/robbery.lua
rsg-railroad:robberyOccurredservercompanyIdserver/robbery.lua
rsg-railroad:robberyDefeatedservercompanyIdserver/robbery.lua
rsg-railroad:openTrainStorageserver``server/storage.lua
rsg-railroad:addSupplyservercompanyId, itemName, quantityserver/supplies.lua
rsg-railroad:takeSupplyservercompanyId, itemName, quantityserver/supplies.lua
rsg-railroad:purchaseUpgradeservercompanyId, trainModel, upgradeTypeserver/upgrades.lua
-- from a client script
TriggerServerEvent('rsg-railroad:ambientDespawned')
-- from a server script
TriggerClientEvent('rsg-railroad:refreshStationData', source, companyId)

Commands#

CommandNotesFile
/trainrobberyclient/train_robbery.lua
/trainposShow train locations (admin)server/ambient.lua
/setjunctionSet a train track junction (admin)server/ambient.lua

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 -->