Skip to content
Connected RailsConnected Rails

Writing a scenario

A line can be used in two ways. A scenario is one prepared run: a start time, the trains on the line, events that fire on triggers, and an ending. An operating day is the whole timetable of a day, looping every 24 hours, and the player picks one service out of it. This guide builds both against the example mod. Its probefahrt and rangierfahrt scenarios and its beispieltag day are the worked examples throughout.

You need a mod with a line in it (Building a line). Everything below goes into that mod’s folder. As everywhere, content is addressed as "<mod>:<file stem>".

A scenario is a RON file in scenarios/. Start with the smallest useful one:

  1. Create scenarios/probefahrt.ron and give it a name and a description.
  2. Name the line it runs on with line: Some("<mod>:<line>"). A scenario’s positions are indices into one line’s track graph, so it should always say which line that is. A composition works here too. --line on the command line still wins.
  3. Set the wall clock at the start of the run with start:. It decides where the sun and moon stand and which season the ground wears. Without it, a run begins at midsummer noon.
  4. Optionally set weather: to one of the presets (Clear, Cloudy, Rain, Snow, …). The run starts in it, wet rail and all.
(
name: "Probefahrt",
description: "Short test run on the example line: pull away, then obey the main signal.",
start: (year: 2026, month: 8, day: 15, hour: 6, minute: 45, utc_offset: 2.0),
player_train: 0,
events: [ /* step 3 */ ],
line: Some("example:beispielstrecke"),
)

utc_offset is the local clock’s offset from UT in hours (Germany: 1 in winter, 2 in summer). Event triggers and Scenario timetables count from the start of the run, not from this clock.

A scenario may say exactly what stands on the line with consists:. The order of the list is the order of the train indices, starting at 0. player_train picks the one the player drives, and every event’s train: and every script address the same list. rangierfahrt.ron stands a rake of three machines on the line and the player’s light engine in the siding:

consists: [
(
// 0: three stabled machines at km 3.8, braked, waiting to be collected.
number: "Lokzug 77401",
vehicles: [(vehicle: "example:br101_afb", count: 3)],
at: At(edge: EdgeId(0), s: 3800.0, dir: 1),
),
(
// 1: the player's light engine, standing in the siding.
number: "Lz 77400",
vehicles: [(vehicle: "example:br101_afb", count: 1)],
at: Yard("Abstellgleis 1"),
),
],
player_train: 1,
  • vehicles names the stock head first, as stretches of (vehicle, count). A stretch may also pick a livery and a load (variant: Some(1), load: Some(0)).
  • at: is a spawn point. At(edge, s, dir) is where the head stands and which way it faces (dir: 1 = towards rising s). Yard("…") names one of the line’s yards:, a stabling road or a portal (Stabling roads and portals).
  • A consist without a timetable stands where it was put with its brakes applied. With timetable: Some("<mod>:<name>") the AI drives it, and with shunt: it works a shunt job. prepared: false puts a cold engine there for the player to wake up.

Leave consists: out and the run builds the player’s train from the vehicle picked in the menu. That is what probefahrt.ron does, and why its player_train is 0.

The core of a scenario is its events: list. Each event has a unique name, one trigger and a list of actions. It fires once, unless it says once: false. From probefahrt.ron:

events: [
(
name: "welcome",
trigger: Time(2.0),
actions: [Message("Test run: proceed to the main signal at km 2.0.")],
),
(
name: "arrived",
trigger: TrainStopped(train: 0, edge: EdgeId(0), s: 1980.0, radius: 60.0),
actions: [
Score(points: 20, reason: "Stopped at the signal"),
Finish(success: true, reason: "Test run complete"),
],
),
],

The triggers the format knows:

trigger true when
Time(seconds) the run has lasted that long
TrainPast(train, edge, s) the head of the train has reached or passed the point
TrainStopped(train, edge, s, radius) the train stands within radius metres of the point
SpeedAbove(train, kmh) / SpeedBelow(train, kmh) its speed is above / below the threshold
SignalStop(signal, stop) the signal shows stop (stop: true) or proceed (false)
ForcedBrake(train) the train protection has intervened
After(event, delay) delay seconds after the named event fired
All([…]) / Any([…]) all / at least one of the nested triggers
Never never on its own; a script fires it (step 5)

And the actions:

action does
Message("…") / Announcement("…") a message to the player / an announcement
SetSwitch(node, position) throws a switch (Straight / Diverging)
RequestRoute(RouteId(i)) / ReleaseRoute(RouteId(i)) sets / releases a route of the interlocking
SetWeather(preset) moves the weather to a preset over five minutes, a front rather than a switch
SetRail(Dry | Wet | Slippery) the rail condition alone, until the weather next changes
Score(points, reason) adds or deducts points
Finish(success, reason) ends the run

Texts in messages and reasons are mod content, written in the language your mod ships. They do not go through the simulator’s translation.

On a line built from modules, a module: on the scenario or on a single event makes its indices module-local (Modules and compositions).

Without a timetable only the scenario’s own points count. With one, the scoring also counts position error and delay at every stop.

  1. Create timetable/probefahrt.ron with the train’s number, category and stops.
  2. Use kind: Scenario: the times are seconds from the start of the run, and the timetable runs once.
  3. Reference it from the scenario with timetable: Some("example:probefahrt").

timetable/probefahrt.ron:

(
number: "Lt 91351",
category: "Lt",
kind: Scenario,
stops: [
(
name: "Beispielstadt Bksig",
edge: EdgeId(0),
s: 1980.0,
arrival: 150.0,
departure: 210.0,
platform: "1",
),
],
)

The other kind, Daily, reads the times as seconds since local midnight and wraps around every 24 hours. That is the looping all-day timetable an AI train can follow indefinitely, and it is anchored by the scenario’s start: clock.

From the repository root:

Terminal window
cargo run -p app -- --scenario example:probefahrt

Useful flags while you iterate:

flag does
--line <mod>:<name> runs on another line or composition than the scenario names
--time 22:30 moves the run’s start clock
--date 2026-01-15 moves the run’s start date (and with it season and sun)
--weather snow lets that preset move in over five minutes; with --screenshot it is placed at once

A few things to check on a test run:

  • Every TrainStopped and TrainPast point lies where you think it does: drive there and see whether the event fires.
  • An event that never fires usually addresses the wrong train:, a point on another edge, or a radius that is too small.
  • Warnings about the scenario go to the log. See Troubleshooting.

A trigger table has no memory. “The train has been standing for 60 seconds after it had already moved” cannot be written as a trigger. That is what a script is for, and the rule is: the script decides when, the RON says what.

probefahrt does it the simplest way. The RON declares an event that never fires by itself:

(
name: "stalled",
trigger: Never,
actions: [
Announcement("Dispatcher: are you having trouble? Report your position."),
Score(points: -5, reason: "Unscheduled stop"),
],
),

and names a script with script: Some("example:probefahrt"), which is scripts/probefahrt.lua. That script uses the older hook shape: on_frame(ctx) reads the speed from ctx and answers with { fire = { "stalled" } } once the train has stood long enough. It still runs, but new scripts should use the director API below. In it the same thing is cr.fire("stalled").

7. The director: a scenario told as a story

Section titled “7. The director: a scenario told as a story”

A scenario script is the director of the run. Through the cr API it reads the whole world, sets the player tasks, puts trains on the line, gives AI drivers work, scores and ends the run. rangierfahrt is told entirely this way: its RON says only what stands on the line, and scripts/rangierfahrt.lua does the rest.

  1. Name the script in the scenario: script: Some("example:rangierfahrt") loads scripts/rangierfahrt.lua.
  2. Return a module table. Every handler on it is optional. on_start() runs once at the first frame, on_tick(dt) at every 0.1 s mark of simulation time, and world events arrive as on_<event>(...).
  3. Tell the story in a task that waits. cr.start(fn) runs fn as a coroutine, and inside it cr.wait, cr.wait_until and cr.wait_for wait without stopping anything else.
  4. Put the steps on the HUD with cr.task(id, text) and tick them off with cr.task_done(id) or cr.task_failed(id).
  5. Score with cr.score(points, reason) and end with cr.finish(success, reason).

The core of rangierfahrt.lua, shortened:

local M = {}
local ENGINE = 1 -- index in the scenario's consists: list
local function player()
return cr.train(cr.player())
end
local function story()
cr.wait(2.0)
cr.task("ausfahren", "Aus dem Abstellgleis 1 ausfahren")
cr.task("kuppeln", "An den Lokzug bei km 3,8 kuppeln")
cr.wait_until(function() return not cr.at_yard(ENGINE, "Abstellgleis 1") end)
cr.task_done("ausfahren")
cr.wait_until(function()
local train = player()
return train ~= nil and train.vehicles >= 4
end)
cr.task_done("kuppeln")
cr.score(10, "Lokzug gekuppelt")
-- … wait until it stands at the goal, then:
cr.finish(true, "Rangierfahrt beendet")
end
function M.on_start()
cr.start(story)
cr.start(watch_speed) -- a second task: -5 points per excursion over 25 km/h
end
-- A world event: the rake parted again before the goal.
function M.on_uncoupled(train)
if train == cr.player() and cr.objective("kuppeln") == "done" and not cr.finished() then
cr.task_failed("bringen")
cr.finish(false, "Lokzug unterwegs abgekuppelt")
end
end
return M

Run it with:

Terminal window
cargo run -p app -- --scenario example:rangierfahrt

The player couples with Insert and uncouples with Home (Shunting).

Things worth knowing before you write your own:

  • Every index starts at 0, as in the RON: trains, signals, routes, switches, services. Only Lua’s own lists (cr.trains(), cr.yards(), cr.services()) start at 1, so use the values in them, not their positions.
  • Reads see the world as it stood when the call began. Writes are commands that take effect after the handler returns. A wrong argument (a road the line does not have) is an error and switches the script off. A refusal by the world (nothing in reach to couple to) comes back as a refused event, and the script runs on.
  • Indices you write into the script are not moved on a composition. The RON’s indices are. Add cr.offset().edges to an edge of your own, as rangierfahrt.lua does for its goal.
  • Positions along the track: cr.distance(train, target) gives the metres from the train’s front end to a road, another train or { edge, s }.

A script can bring traffic of its own. cr.spawn{…} takes the same consist as a consists: entry, written as a table, and returns the new train’s index at once. cr.drive(train, timetable) gives it an AI driver for a timetable, and cr.shunt(train, job) one for a shunt job. A job is a table built from cr.moves, or a jobs/*.ron file named by id, like jobs/lokzug_abstellen.ron:

(
name: "Lokzug abstellen",
moves: [
SetBack(Yard("Abstellgleis 1")),
Uncouple(0),
DrawUp(At(edge: EdgeId(0), s: 3700.0)),
Stand,
],
)
cr.set_switch(1, "diverging") -- the points have to lie right first
cr.shunt(train, "example:lokzug_abstellen")

The AI does not throw points for itself, so the script sets them (cr.set_switch) or sets a route (cr.request_route). The move formats are in Shunt jobs for the AI.

Besides the handlers on the module, cr.on(event, fn) adds a listener and cr.wait_for(event [, filter [, timeout]]) waits for one inside a task. Some of the events: stopped / departed, coupled / uncoupled, entered / left a road, signal, event (a RON event fired), refused and finished. The complete list with arguments, every read and every command are in the reference: Scenario scripting.

Each run gets a fresh Lua 5.4 state with table, string, math and coroutine, and no io, os, require, filesystem or network. pairs visits keys in a fixed order and math.random is seeded from the script’s name and the start of the run, so the same scenario on the same day draws the same numbers. A script that raises an error or runs too long is switched off, the HUD says so, and the run goes on without it. Keep your state in locals. Details: The sandbox.

The second way to use a line is an operating day in days/. Instead of one prepared run it holds every service of a day, and the run picker offers the playable ones. days/beispieltag.ron is complete.

  1. Create days/<name>.ron with a name, description and the line it belongs to. A day whose line names another line than the one picked is not offered. Leave line out and it is offered everywhere.
  2. Set the default date and utc_offset. The player can move the date in the run picker.
  3. Set the default weather: Dynamic lets the day make its own weather out of the date, Fixed(Rain) names one preset and holds it. The player can override this too.
  4. Add the services. Each has a number, category, description, a head vehicle (None takes what the player picked), cars, an origin spawn point and its stops.
  5. Optionally say where the stock goes afterwards with stable_at (a road of the line) and stable_way (SetBack, the default, or DrawUp).
  6. Mark services the player should not be offered with playable: false. The AI still runs them, so the line is not empty.
(
number: "RB 30001",
category: "RB",
description: "Frühzug nach Beispielstadt",
vehicle: Some("example:br101_afb"),
cars: 3,
origin: At(edge: EdgeId(0), s: 200.0, dir: 1),
stops: [
(name: "Beispielbach", edge: EdgeId(0), s: 200.0,
arrival: 22500.0, departure: 22500.0, platform: "1"), // 06:15
(name: "Beispielstadt", edge: EdgeId(0), s: 3800.0,
arrival: 22980.0, departure: 23040.0, platform: "2"), // 06:23
],
),

Service times are always seconds since local midnight, read as a Daily timetable that wraps at 24 hours. A service that leaves at 23:50 and arrives at 00:12 is simply 85 800 and 720. The run starts two minutes before the player’s service departs. Every other service is put on the line as its hour comes and driven by the AI, and its unit is reused by the next service that needs the same stock.

A day may also declare consists: (stock standing there from the first minute, with or without a timetable or a shunt: job) and a script:. That script is a director like a scenario’s and also sees the services (cr.services(), working_start / working_end, cr.offer_working). The full format: Operating days.

The run picker offers the day under its line. Without the menu, --day and --service take a service directly. --service is the index into the day’s services: list, starting at 0. Without it, the first service is taken.

Terminal window
cargo run -p app -- --line example:beispielstrecke --day example:beispieltag --service 0

--date 2026-01-15 moves the date of the service, so the same 06:15 departure becomes a night run in winter. --weather and --time work as for a scenario. Drive a service to its last stop and check that the next working is offered (F10 takes it), and that services with stable_at end up on their road.

Every scenario and every day also runs on a dedicated server, from the same file:

Terminal window
cargo run -p app -- --dedicated 27015 --scenario example:rangierfahrt

Keep these points in mind while you write one:

  • The server runs the director, never a client. A client receives what the world made of the script’s commands and applies it. A script that changes the world only through cr works in multiplayer with no extra effort.
  • Do not depend on the player. On a dedicated server nobody is “the” player, and cr.player() returns the scenario’s train there. Several people may be on the line, so write checks against train indices, not against what one screen shows.
  • The consists are the server’s. Clients build the scenario’s trains, liveries and loads from the server’s description. Their own menu and --variant have no say over them.
  • The operating day’s dispatching is a function of the clock. Server and clients put the same services on the line without sending anything about it. Only the driving is the server’s.
  • --time and --weather do nothing on a server, so test a scenario’s sky through its start: and weather: fields, not through those flags.

Running and joining a server: Multiplayer.