Rules: the rules document and the registry
Melange 0.18 lets the host of a match change its rules: the game style’s fields, each weapon’s ammo, delay and crate
weight, and the match settings the mods declare. The rules travel as one JSON document, melange-rules-1. Every machine
resolves it the same way, and the resolved bytes are hashed, so peers can prove they play the same match.
This page covers the document, its validation, the canonical form and hash, the registry of modes, and the draft folder. The fields and weapons the document may set are in rules-fields.md. How a mod declares modes and match settings is in spice.md.
The authoring form
Section titled “The authoring form”What a UI, a preset or a tool writes. Everything except format and mode is optional.
{ "format": "melange-rules-1", "name": "Friday Sandworms", "mode": "sandtide/sandworms", "scheme": { "TurnTime": 30000, "WormHealth": 150 }, "weapons": { "*": { "delay": 1 }, "Bazooka": { "ammo": 2, "delay": 1 }, "Sheep": { "ammo": 0 }, "HolyHandGrenade": { "ammo": 1, "delay": 3, "crate": 5 }, "HealthMystery": { "crate": 40 } }, "mods": { "sandtide": { "teamClockMs": 120000 } }, "note": "free text"}| Key | Meaning |
|---|---|
format |
Always "melange-rules-1". |
name |
Display only, at most 80 characters. Not part of the resolved form or the hash. |
mode |
A mode id from the registry (below): vanilla/<style>, scheme/<style> or <mod>/<mode>. The mode gives the base: its style’s values, its locks and its match settings’ defaults. |
scheme |
Game style fields to change, by their SchemeData names (rules-fields.md). Bools are true/false; AssistedShotLevel is its string. |
weapons |
Weapon entries to change, by their SchemeData names: ammo (-1 infinite, 0 absent, up to 99), delay (own-team turns greyed, 0-20) and crate (weight, 0-100). "*" applies first, then the named entries; "*" sets only crate on the 15 mystery entries, which take only crate. A weapon clone (kWeaponAcidSpitter) is refused: it shares its base’s values (“Acid Spitter shares Bazooka’s settings: edit Bazooka”). |
mods |
<mod id>: {<setting>: <value>}: match settings only. Player settings never enter a rules document. |
note |
Free text, at most 280 characters. Not resolved. |
x-* |
Any key starting x- (tooling metadata) is kept in the authoring form and ignored. |
Any other top-level key is an error.
The resolved form
Section titled “The resolved form”Core resolves the authoring form into an absolute document that holds every value, so machines never re-resolve it against their own registry:
{"deps":{"sandtide":"1.1.0"},"format":"melange-rules-1","mode":"sandtide/sandworms", "mods":{"sandtide":{"breakout":true,...,"teamClockMs":120000,"technique":"player"}},"resolved":1, "scheme":{"ArtileryMode":0,"AssistedShotLevel":"AssistedShot.Intermediate",...,"WormSelect":0}, "schemeName":"FETXT.Scheme.Sandworms","weapons":{"Airstrike":[1,0,2],...}}schemeholds the 28 editable fields.Special,Name,Permanent,LockandAssistedShotSettingsare never written. A mode’slockvalues always win.weaponsholds all 58 entries as[ammo, crate, delay]. A mystery entry carries its style’s own ammo and delay.schemeNameis whatGM.SchemeData.Namebecomes: the mode’s style key, sowum.sim.scheme()keeps working.modsholds, for the mode’s own mod, every match setting it declares (all its modes’settingsand itsmatchSettings), and for every other enabled mod itsmatchSettings; unset values are the declared defaults.depslists the mods the document uses (the mode’s mod, the style’s mod,requires, every mod inmods) at this machine’s versions. A peer with another version fails validation (deps).- A resolved document is itself valid input (
"resolved": 1, withschemeNameanddepschecked) and resolves to the same bytes.
Canonical JSON and the hash
Section titled “Canonical JSON and the hash”- Members are sorted by key in byte order; there is no whitespace; numbers are integers in decimal; booleans are
true/false. A number with a fraction is refused. rulesHashis the SHA-256 of the canonical bytes (lowercase hex).hash16, its first 16 hex digits, appears in lobby keys, logs and the UI.- The limit is 24 KB (24576 bytes), for the authoring text and for the resolved bytes. A resolved document that sets every value is about 2-4 KB.
Validation
Section titled “Validation”rules::Validate (the UI, presets, the RPC and acks all use it) returns every problem it finds, each as
{path, code, message, min?, max?, allowed?}. path is dotted: scheme.TurnTime, weapons.Bazooka.ammo,
mods.sandtide.teamClockMs, mode, or empty for the whole document.
| Code | When |
|---|---|
format |
Not JSON, not an object, a wrong or missing format, or (resolved form) a wrong schemeName |
duplicate_key |
A JSON object names a key twice; path is the key |
too_large |
Over 24576 bytes |
unknown_mode |
mode is missing or names no mode of the registry |
mode_unavailable |
The mode’s mod, a mod it requires, or its game style is not loaded |
unknown_field |
An unknown top-level key, game style field or weapon value; Special; ammo/delay on a mystery entry |
unknown_weapon |
Not one of the 58 weapon entries; a clone is named with the weapon it shares |
unknown_mod |
mods.<id> names a mod that is not on |
unknown_setting |
The mod declares no such match setting, or the setting belongs to another of its modes |
type |
The wrong JSON type (a string for a number, 1 for a bool, a fraction) |
range |
Outside the field’s or setting’s range, or off its step (min, max given) |
enum |
Not one of the allowed values (allowed given) |
locked |
The mode pins this game style field to another value |
not_int24 |
A match setting outside +-2^24 (16777216): sim numbers are float32 |
deps |
(resolved form) a mod version differs from this machine’s, or is missing |
The registry
Section titled “The registry”The registry is every mode the host can pick on this machine, and every match setting:
vanilla/<style>: each of the 18 built-in game styles ofLOCAL.XOM(vanilla/FE.Scheme.Standard, …).scheme/<style>: each game style a mod adds withschemesthat no mode of the same mod names (scheme/FETXT.Scheme.Kanly).<mod>/<mode>: each entry of a mod’smodes(sandtide/sandworms). A mode whose mod is off is listed as unavailable. A mode with a badlock,featuredor preset field, or aschemethat is neither built-in nor the mod’s own, is left out and logged as an error. A card that is missing, not a PNG or larger than 512x256 is dropped with an error; the mode stays.
The Rules module builds it from LOCAL.XOM, the enabled mods’ styles (the same bank the Schemes module loads) and
every installed mod’s spice.json, again whenever the mods change, and writes it to Melange.log:
[rules] registry: 21 modes (1 declared, 2 from mod schemes), 21 styles, built in 40.0 ms[rules] mode 18 vanilla styles: Beginner, Standard, Pro, Bng, Shopping, ...[rules] mode sandtide/sandworms "Sandworms" (FETXT.Scheme.Sandworms) settings: teamClockMs=180000 hungry=true ... lock: SuddenDeath=1 presets: 1 card: landsraad/sandworms-card.png [available][rules] mode scheme/FETXT.Scheme.Kanly "Kanly" (FETXT.Scheme.Kanly) [available][rules] mode scheme/FETXT.Scheme.KanlyMelee "Kanly Melee" (FETXT.Scheme.KanlyMelee) [available]A generated JSON Schema (draft 2020-12) describes the authoring form for one machine’s registry: the mode enum, every
field’s and weapon’s range, and each mod’s settings with their types and ranges. rules-1.schema.json
is the static, registry-free version (regenerate it with rules_doc_selftest --schema; the selftest fails when it is
out of date).
Test verbs (automation builds): rules.modes writes the registry to the log again, rules.validate <json> logs the
problems or the hash16, and rules.draft logs the draft.
Weapons and art for a lobby UI
Section titled “Weapons and art for a lobby UI”wum.rules.weapons([modeId]) lists the 58 weapon entries the way a player sees them on this machine: the name the game
shows now (an enabled content mod’s weaponText rename wins over the game’s string table, so with Kindjal on the
Bazooka reads “Ripper”), the help text, the tags of the field catalog, the panel cell, the clones that share the
entry’s values (Acid Spitter on the Bazooka row) and a style’s [ammo, crate, delay]. wum.draw.weaponIcon draws an
entry’s weapons-panel icon, with the enabled mods’ weaponIcons replacements and clone icons in, so a grid of cells
row * 6 + col matches the panel of a match with the same mods. wum.rules.cardTexture(modeId) gives the calling mod a
texture of a mode’s card. See lua-api.md.
The icons come from our own copy of the game’s three “Weapon Panel Icons” sheets, read from Data\Bundles\Bundl09.xom
once per launch on the first call (a background thread, about a second; only the images are kept), with each
replacement alpha-blended over the vanilla icon and each clone icon over an empty tile, as the panel does in a match.
They are drawn from one 768x768 texture (and a greyed copy for state = "off"), so they need no game state and work in
the frontend and the lobby. The panel’s cells, icon codes and the engine’s weapon names are build 1077’s static tables
(src/rules/weapon_rows.cpp; rules_weapons_selftest checks them against the catalog). Melange.log shows
[rules] weapon catalog: ... and [rules] weapon icons: 3 panel sheets, N replaced by mods, M clone icon(s) ....
The draft folder
Section titled “The draft folder”The host’s working rules (the draft) are kept across launches in <[Rules] Dir>\draft.json as
{"doc": <authoring document>, "format": "melange-rules-draft-1", "rev": N}. Every accepted change raises rev by one;
a writer passes the rev it started from and gets a conflict if the draft moved meanwhile. Only a valid document is
stored.
[Rules]; Where the draft and presets live. Empty = Documents\Melange\rules. A relative path is under the game folder.Dir=Presets
Section titled “Presets”Named rules live in <[Rules] Dir>\presets\<slug>.json. A preset file is the authoring document itself, as canonical
JSON with its display name in name. The slug is the name in lowercase letters and digits, runs of anything else
joined by one -, at most 48 characters (a name with no letter or digit, a control character or over 80 characters is
refused: bad-name). At most 200 presets exist (full). A save validates the document first, writes a temporary
file and renames it, so the folder holds only the preset files. A file that fails validation (hand-edited, or from
another set of mods) is still listed, with its problems, and does not load.
Client mods reach all of this through wum.rules (lua-api.md): draft() returns the document
and its rev, and setDraft(doc, {baseRev = rev}) reports conflict when the draft moved since the mod read it, so
two writers (a UI and the AI, say) never overwrite each other. Writing needs permissions.rules = "edit"; in a
lobby only the owner writes (not-host). diff and explain work on resolved documents and are deterministic: the
same documents give the same changes and the same text on every machine. Sim scripts read their mod’s match
settings with wum.sim.setting(key) from the document the match VM was given, else the declared defaults
(developer-guide.md).
The Oasis RPC
Section titled “The Oasis RPC”rules.schema, rules.get, rules.validate, rules.set and rules.presets.list/get/save/delete (docs/oasis.md, “Rules”)
reach the same registry, draft and presets folder from outside the game. rules.set follows the same host rule as
wum.rules.setDraft and tells mods about it with the melange.rules event external.
Applying the rules
Section titled “Applying the rules”The rules of a match are one resolved document, frozen before the match starts:
- Offline (no net session), at the local
WXMsg.StartGame: the document armed byrules.test, else the draft while the local “use these rules” switch is on (wum.rules.active, off by default and not persisted). Nothing is frozen otherwise, and the match plays the style it was given. - Online, at the lobby agreement (“The lobby agreement” below): every machine freezes the lobby’s agreed document as the match leaves the lobby. A document frozen offline never applies to an online match.
At every match VM creation (each round of a multi-round match included), before the level’s Initialise copies
the style into the clocks, the worms and the inventories, the frozen document is written into GM.SchemeData, on every
machine alike:
GM.SchemeDatais deep-cloned twice with the engine’s own clone action (as the frontend’s style load does). One clone is the backup. The other is copied in, soGM.SchemeDataowns freshWeaponSettingsDataobjects. The weapon objects it held before may be shared (CopyFromcopies refs, so a joiner’s are the receivedGameDataSetupMsg’s) and are never written.Name(set to the document’sschemeName, sowum.sim.scheme()reads the mode’s style key), the scalars andAssistedShotLevelare written through an engine-LuaEditContainer("GM.SchemeData")chunk built only from catalog names, integers and checked keys.- The 58 weapon entries’
Ammo,CrateandDelayare written into the fresh objects. - Everything is read back and compared with the document. Melange.log and the session log (
rules.applied) record it:
[rules] frozen 6c0da03a503480a2 (vanilla/FETXT.Scheme.QuickGame, style FETXT.Scheme.QuickGame) for the local match 'QuickStartHvHvHvH' (from test)[rules] applied 6c0da03a503480a2 (vanilla/FETXT.Scheme.QuickGame, 5 overrides) to GM.SchemeData; scheme fnv 40ba12ffe6f9666a[rules] changed: WormHealth 100->150, TurnTime 45000->20000, Bazooka.ammo -1->2, Bazooka.delay 0->1, Sheep.ammo 1->0[rules] weapon objects: GM.SchemeData owns fresh copies (0 shared with what the game loaded)A match without frozen rules logs [rules] match VM <n>: no rules. A failed apply logs [rules] NOT applied <hash16> (<mode>): <why> (rules.apply_failed in the session log) and leaves GM.SchemeData as the game loaded it.
The scheme fnv is a 64-bit FNV-1a over Name, WindMaxStrength, the integer fields, TelepadsOn,
MineFactoryOn and the 58 weapons’ three values. It holds no pointer, so machines that applied the same document read
the same fnv. “Overrides” counts the values that differ from what the game had loaded.
After the match. Once the game is back at the frontend (no match VM, Game.Scope 0, for about 2 s), and also at
the next StartGame, at the next match VM without rules (the attract demo included) or on entering a lobby,
GM.SchemeData is put back from the backup if it still holds the applied values. If the game has loaded a style into it
since, nothing is written. Wins keeps the applied value until the frozen document is dropped, in case the round loop
reads it between rounds.
What the document cannot change:
- Early-read fields (catalog
earlyRead):WindMaxStrengthis read by the HUD wind gauge before the match VM exists (the sim’s wind cap is set later and follows the document), andWinsmay be read by the round loop. They are written like every other field, a change is logged as “early-read fields changed … not supported yet”, and Landsraad shows them greyed out. SkipGoandSurrenderare always available (the level script hard-wires them).CrateShower,CrateSpy,DoubleDamage,Armourand the mysteries only use their crate weight. A weapon with infinite ammo never comes from crates.- The frontend maps a style’s
WormHealthof 125 to 150 when it loads a style; the rules are written after that, so a document’s 125 stays 125.
[Rules] Enabled=0 turns the whole Rules module off: no registry, no draft and nothing applied. Applying needs the
known game build (#1077) and is off otherwise.
Test verbs (automation builds):
rules.test <json>validates and resolves a document (authoring or resolved form) and arms it for the next local match only;rules.test demo <json>arms it for the next match VM whatever starts it (the attract demo too, which a key leaves, so the following match of the same session can be checked);rules.test cleardisarms it, andrules.testalone logs what is armed, frozen and applied.rules.local on|offsets the local switch (the draft then freezes at each local StartGame).rules.appliedlogs the last apply and the scheme fnv ofGM.SchemeDatanow.
The lobby agreement
Section titled “The lobby agreement”In an online lobby the owner’s rules travel as Steam lobby data: nothing goes over the game’s own channel, and
GameDataSetupMsg is unchanged. Every machine checks the document, the owner’s start is held until all of them agreed,
and every machine applies the same bytes.
| Key | Written by | Value |
|---|---|---|
mlg.rules |
the owner (lobby data) | 1;<owner steam id>;<hash16>;<bytes>;<chunks> |
mlg.rules.<i> |
the owner (lobby data) | the canonical resolved document, cut every 7000 bytes (at most 4 chunks) |
mlg.rules.ack |
each member, the owner too (member data) | 1;<hash16>;ok, 1;<hash16>;err:<code>, or 1;;off with [Rules] Enabled=0 |
mlg.rules.applied |
each member, after each match VM’s apply | 1;<hash16 or ->;<scheme fnv> |
mlg.rules.status |
the owner (lobby data) | 1;<owner steam id>;drafting or ...;proposed; deleted when there is nothing to say |
Publishing (owner). While its rules switch is on (wum.rules.active, the same switch as offline), the owner
publishes its draft: the chunks first, then mlg.rules, then stale chunks are deleted. The first document is published at
once; an edit is published 500 ms after the last change, or at once when the start is attempted while it waits. With the switch off or no valid draft, the owner
deletes mlg.rules* (“follow the game’s style”); a lobby value written by an earlier owner is deleted the same way. The
owner publishes only on the lobby screen: an edit made during a match waits for the next lobby.
Checking (every member). When mlg.rules changes (polled about every 100 ms), a member reads the chunks and checks
that the owner tag is the lobby’s current owner, that the byte count matches, and that the SHA-256 of the bytes starts
with hash16. It then validates the document against its own registry (modes, ranges, the deps versions), checks
that it resolves to the same hash here and that it can be applied, and writes its ack. The error code is the first
problem’s code (mode_unavailable, deps, range…), hash (the bytes do not match after 4 s of retries, so not a
read in the middle of an update), resolve or apply. Melange.log says:
[rules] lobby: published 6c0da03a503480a2 (vanilla/FE.Scheme.Standard, 3412 bytes in 1 chunk(s))[rules] lobby: rules 6c0da03a503480a2 from HostA (vanilla/FE.Scheme.Standard, changes 4): ok[rules] lobby: every member (2) agreed on 6c0da03a503480a2The start hold (owner). Through the shared start hold, the reason rules holds the owner’s start while:
- an edit is waiting to be published;
- a member has no Melange (no
mlgmember key), or runs a Melange older than 0.18; - a member has
[Rules] Enabled=0(its Handshake writes the ack1;;off); - a member has not acked the current
hash16, or acked it with an error.
So a host’s edit made just before Start can never start a match on a stale document: the start waits until every member has re-acked. The lobby banner names each member that holds the start (“Rules (6c0da03a): the match can’t start yet: JoinB has not confirmed these rules yet”). Once everyone agreed, every machine’s banner says what the match plays: “Host rules: Standard, 4 changes (6c0da03a), agreed 2/2”. A member whose game can’t use the rules sees why in red.
The freeze. At the moment the sim fixes are decided (the match leaving the lobby, before anything is simulated),
every machine reads mlg.rules once. It freezes the document only if the owner tag is the current owner, the hash is
the one it validated, and its own ack of that hash is ok. Otherwise it applies nothing and logs [rules] lobby: rules: NOT applied (<why>); the host’s start hold makes that state unreachable except through a lobby-data race. Lobby changes
during the match change nothing until the next lobby. The frozen document is dropped back in the lobby, or when the
lobby is left. If a machine’s match VM is created before it saw the agreement point, it freezes then (logged “late”).
The applied check. After each match VM’s apply, every machine writes mlg.rules.applied with the hash it applied
(- for none) and the scheme fnv of GM.SchemeData read back. The host compares every member’s value with its own for
up to 60 s:
[rules] lobby: reported applied 1;6c0da03a503480a2;40ba12ffe6f9666a[rules] applied check: JoinB ok (6c0da03a503480a2 fnv 40ba12ffe6f9666a)A difference that persists for 5 s logs [rules] MISMATCH <member>: <what differs>, records rules.mismatch in the
session log and makes Wormsign write a desync bundle (its report’s correlation line names the mismatch).
The status key. mlg.rules.status lets the owner tell the lobby that it is drafting rules or has a proposal (the
Landsraad AI banner) without a peer channel. Only the owner writes it, and a value written by an earlier owner reads as
empty. Every member logs a change: [rules] lobby: the host's rules status is now 'drafting'.
Test verbs (automation builds), in addition to those above:
rules.set <json>makes the document the draft (validated, at the draft’s current rev). Withrules.local on, an owner then publishes it.rules.lobbylogs the lobby state: the document, this machine’s ack, the hold and its reasons, the frames the start was held for the rules, the status, and every member’s ack and applied value.rules.status drafting|proposed|clearsets the owner’s status;rules.statuslogs it.