Skip to content

KOTT under the hood

The story of the night says what happened. This page says how, with the parts of the mode script that carry the weight. The snippets are trimmed, but they're the real thing, not pseudocode. None of this is secret: a mode script you can't inspect is a mode script nobody can trust.

A few words first, in Trackmania's own terms:

  • Mode script: the ManiaScript file the dedicated server runs to define the rules of a match. Time Attack, Rounds and Knockout are mode scripts.
  • Callbacks: the fixed names a mode script is built from, such as Match_InitMap and Match_PlayLoop, which the server calls in a fixed order.
  • MatchSettings: the file that names the maps and sets the mode script settings, the S_ values you'll see below.
  • Waypoint: any checkpoint crossing. The finish line is the waypoint with IsEndRace set.
  • XML-RPC: the socket a server controller talks to the dedicated server on. The controller sends a mode-script event with TriggerModeScriptEventArray, and the mode script answers with a callback it registered.

We extend the stock mode, we don't fork it

The qualifier is Nadeo's TM_TimeAttack_Online with a ledger bolted on. #Extends does that, and everything the players feel stays Nadeo's: the driving, the waypoints, the respawns and the stock HUD. Our settings sit next to Nadeo's, so a server operator sets them in MatchSettings like any other S_ value.

#Extends "Modes/TrackMania/TM_TimeAttack_Online.Script.txt"
#Setting S_KackyQualifierId "" as "Unique qualifier run ID (required)"
#Setting S_KackyFirstFinishSeconds 600 as "First valid finish deadline, seconds"

Fork it, and you re-merge after every Trackmania update, because Nadeo keeps changing the stock modes. Extend it, and you ride along.

The hold, before the server assigns StartTime

Each round has a race clock. The stock mode script sets StartTime for the round, and every race time is measured from it. The shared start must therefore be decided before StartTime exists. Our code holds the map in Match_InitMap. The server calls that callback before the parent mode script assigns the value, and our code waits there for the start event.

***Match_InitMap***
// The parent StartMap assigns StartTime before appended child hooks run. Hold earlier.
KackyQualifier::PrepareSharedStart(S_KackyQualifierId, Map.MapInfo.MapUid,
    S_TimeLimit * 1000, S_KackyFirstFinishSeconds * 1000);
while (KackyQualifier::WaitForSharedStartStep()) {
    MB_Yield();
}

MB_Yield() hands control back for one tick, the 10 millisecond step the dedicated server runs on, so the server keeps answering XML-RPC while the map is held. A loop without it is a frozen server.

Accepted, or missed. Never late

The server controller sends one mode-script event, Kacky.Qualifier.Start, with four values: the run id, the start id, the moment to begin, and a disposition. The disposition is the whole idea. A controller that gets the decision too late doesn't start the round a few seconds later: it sends missed, and the mode script kills the run.

if (RunId != Kacky_Qualifier.RunId) {
    Private_Abort("run-id-mismatch");
    return;
}
if (Disposition == "missed") {
    Private_Abort("missed-start");
    return;
}
Kacky_Qualifier.StartStatus = "accepted";

Every refusal writes a named reason: invalid-settings, start-before-hold, run-id-mismatch, missed-start, invalid-start-trigger. The reason travels in the snapshot and in the server log, so nobody has to guess afterwards.

The ledger only accepts what the rules allow

A finish is recorded with two numbers: the race time, and how far into the qualifier run it happened. The second number is what makes the time windows possible.

Void Record(Text _AccountId, Text _Login, Integer _TimeMs, Integer _ElapsedMs) {
    if (Kacky_Qualifier.State != "running" || Kacky_Qualifier.StartStatus != "accepted") return;
    if (_ElapsedMs < 0 || _ElapsedMs >= Kacky_Qualifier.DurationMs) return;
    if (!Kacky_Qualifier.Results.existskey(_AccountId)) {
        Kacky_Qualifier.Results[_AccountId] = K_Result {
            AccountId = _AccountId, Login = _Login, FirstFinishMs = _ElapsedMs,
            BestMs = _TimeMs, BestAtMs = _ElapsedMs
        };
        Kacky_Qualifier.Revision += 1;
    } else if (_TimeMs < Kacky_Qualifier.Results[_AccountId].BestMs) {
        Kacky_Qualifier.Results[_AccountId].BestMs = _TimeMs;
        Kacky_Qualifier.Results[_AccountId].BestAtMs = _ElapsedMs;
        Kacky_Qualifier.Revision += 1;
    }
}

Three things worth seeing. The ledger holds one row per account, not per finish. Every change bumps a revision number, which is how a controller knows whether it already has the newest version. And the ledger itself drops a finish that lands after the duration, so nothing downstream has to watch for it.

The finish time comes from the waypoint event in Race::GetPendingEvents(), not from a sampled value. Event.RaceTime is the time the server itself measured for that lap:

// Event.RaceTime is the exact finish time; CurrentRaceTime is sampled on the 10 ms server tick.
KackyQualifier::Record(Event.Player.User.WebServicesUserId, Event.Player.User.Login,
    Event.RaceTime, Event.Player.StartTime + Event.RaceTime - Kacky_QualifierStart);

CurrentRaceTime is read on the server tick, so it can be up to 10 milliseconds stale. Nobody cares on a 3 minute lap. Everybody cares when it decides place 100 against place 101.

Sealing is a clock, not a command

Nobody stops the qualifier. The mode script seals itself in Match_PlayLoop, on the tick where the elapsed time reaches the duration from MatchSettings.

Void Tick() {
    if (Kacky_Qualifier.State != "running" || Kacky_Qualifier.StartStatus != "accepted") return;
    Kacky_Qualifier.ElapsedMs = Now - Kacky_QualifierStart;
    if (Kacky_Qualifier.ElapsedMs >= Kacky_Qualifier.DurationMs) {
        Kacky_Qualifier.ElapsedMs = Kacky_Qualifier.DurationMs;
        Kacky_Qualifier.State = "sealed";
        Private_SendState();
    }
}

After the seal, Record refuses everything, because its first line tests the state. A late admin, a network hiccup, a controller that reconnects: none of them can add a time.

Delivery survives a lost message

The server does not push its result once and hope. Match_Yield runs between rounds and while the map is held, and the mode script answers every pending XML-RPC request there. The controller asks for the snapshot with a mode-script event, and the mode script replies with its registered callback Kacky.Qualifier.Snapshot.

***Match_Yield***
KackyQualifier::HandleRequests();
KackyQualifier::PublishClock();
KackyQualifier::PublishRevisionCallback();
KackyQualifier::PublishRemoteStandings();

The snapshot is JSON. It carries a schema number, the run id and the map UID. It also carries the state, the duration, the cutoff, the elapsed time, the revision, and one entry per account. The platform keeps the first sealed version it receives and ignores later copies, so a repeated delivery is harmless.

The fold: four sealed ledgers into one cup

The fold is the step between the qualifier and the knockout. It takes the merged ranking and turns it into a knockout that only the qualified players can race.

The platform hands out the ranking only after every expected server seals a compatible result. Each row carries a rank, an account id, and the run it came from. Before anything is installed, that list is checked again. The ranks must run 1, 2, 3 with no gaps, and no account can appear twice. Every row must come from the qualifier being folded, and at least two players must remain. A list that fails any of those checks installs nothing.

From that list, the fold generates a mode script of its own, for this cup and no other. It extends our knockout mode script and bakes the roster in as a constant, next to a run id that only a generated division has. A plain knockout can therefore never pass as a folded one.

The generated part is small. Every quarter second, it looks for a player who is not on the roster:

// Off the roster means forced spectator from connect, warm-up included.
if (KackyDivision_NextRosterCheck < Now) {
    KackyDivision_NextRosterCheck = Now + 250;
    declare Text[] KackyDivision_Roster = TL::Split(",", C_KackyDivisionRoster);
    foreach (Player in Players) {
        if (Player.User == Null || KackyDivision_Roster.exists(Player.User.WebServicesUserId)) continue;
        if (Player.SpawnStatus != CSmPlayer::ESpawnStatus::NotSpawned) UnspawnPlayer(Player);
        if (!KackyDivision_Forced) {
            KackyDivision_Forced = ServerAdmin.ForceSpectator(
                Player.User, CServerAdmin::ESpecMode::SpectatorForced);
        }
    }
}

Anyone can watch. Only the roster can race. Nobody gets kicked, which is exactly why the cup host has to start the night empty: a spectator still holds a connection, and a full server has no room left for the people who earned a place.

The fold writes its output once and refuses to overwrite it. Together with the roster checksum it records, that makes the cup reproducible: the same qualifier gives the same roster, and a second attempt needs new identifiers rather than a quiet overwrite.

The last step is the invitation. The knockout server logs its own join link. The fold reads that link and sets it as a mode script setting on the other servers. That setting puts the join button on their qualifier panel. A server that cannot show the button keeps its sealed qualifier on screen instead. Nobody is left on an empty server with no way across. The other servers return to the lobby only after a delay, five minutes by default, so players have time to click.

On the night that button didn't work, which is why people joined by hand. The mechanism was right. The path from the mode script setting to the panel wasn't.

The gulag is a set of settings, and one deliberate choice

The knockout extends Nadeo's Knockout mode script, the one Cup of the Day runs on, and adds a revival round. Most of it is mode script settings, not new code:

#Setting S_GulagEveryNRounds 5 as _("Revival round every N rounds (0 = never)")
#Setting S_GulagRevivalPct 50 as _("Revive this % of the previous round's KOs (0 = use the fixed number)")
#Setting S_GulagStopBelowAlive 4 as _("Stop reviving once this many players are left (0 = never stop)")
#Setting S_GulagOneShot False as _("One gulag attempt per elimination")

The last one carries a story. The mode script can give each knocked out player a single gulag attempt. We turned that off, because players asked for it: with one attempt each, losing your gulag means watching the rest of the night. A grace window also exists, so a player who disconnects to fix something does not lose the attempt at once.

What the game gives you, and what we wrote

It is worth being clear about the split, because Trackmania gives you a lot.

From Nadeo, unchanged: the driving and the physics, TM_TimeAttack_Online, and the Knockout mode script that Cup of the Day runs on. Also the waypoint and record handling, the respawn rules, the scores table, and the knockout board with its elimination warning art. And MatchSettings, the XML-RPC socket with its callbacks, and the ManiaLink layer system that draws every panel.

From us: the qualifier ledger, with one row per account, the time windows, the self-seal and the revision counter. The shared start, which is the hold in Match_InitMap, the start event with its disposition, and the named abort reasons. The snapshot and the callbacks that hand it out until somebody stores it. On the knockout side, the whole gulag. That means which round revives, how many places it gives back, and the round count where reviving stops. It also means the choice between one attempt and many, and the grace window for a player who disconnects. And every screen that tells a player what just happened to them.

The rule we followed: if Nadeo ships it, use it. We wrote the parts that decide a result, and the parts that tell a player what just happened to them.

How the interface was made to feel right

Nadeo's knockout screens are built for Cup of the Day, and some of them cannot say what a gulag needs to say. The knocked-out module has a fixed title and count line, so the gulag screens are our own layer. We measured them against Nadeo's own modules, so our screens sit where a player already expects them.

Every panel reuses Nadeo's art rather than new textures:

<quad id="quad-warn-top" fullscreen="1" pos="0 91.5" size="380 16"
      image="file://Media/Manialinks/Nadeo/Trackmania/Modes/Knockout/hud_knockout_warning_top.dds"
      colorize="{{{Theme::C_KackyRedBright}}}"/>

The art is neutral, so a colorize tints it Kacky red. It still looks like Trackmania, and it's unmistakably ours.

One colour carries the whole night:

/// Panel fill. Nadeo's popup art is neutral, so a colorize tints it.
#Const C_KackyRed "E9583C"

Elimination, gulag, revival and the winner screen are all the same red, told apart by wording, icons and layout, never by a second colour. A revival isn't a green screen, it's a different message. The gulag rounds get one exception: a warmer version of the same red. It is built by stacking tinted copies of the native panel texture, because this build has no gradient attribute in ManiaScript. The shipped modes fake gradients the same way.

Two details do most of the work for the feel.

The panels update on the client, not on the server. The mode script writes values with netwrite, and each panel reads them with netread. A small ManiaScript block inside the ManiaLink then formats the clock and the gap. Nothing waits for a server round trip, so a counter ticks smoothly even while the server is busy with 100 players.

And every screen has a reading time. A roster screen stays up long enough to read, then fades:

/// The gulag roster is read, then taken down, before the countdown starts.
#Const C_GulagRosterReadMs 2600
#Const C_GulagRosterFadeMs 300

Six names are shown, then "and N more". The layout therefore never grows past the screen, and the reading time is the same for two players and for forty.

What we would build differently

The qualifier ledger is paranoid about every way a time can be wrong, and it keeps publishing itself until somebody stores it. The knockout mode script has no such ledger: it keeps the final placings in Scores, shows them on the end screen, and registers no callback to hand them out. That's the piece we add before the next cup, and the shape is already sitting in the qualifier.