Skip to content

Lua API for client mods (wum.*)

A mod’s entry.client script (from its spice.json) runs in Melange’s Lua 5.4 VM, the Sandbox. This page lists everything a client script can use. The offline self-test (sandbox_selftest) fails if a wum.* function is missing from this page.

Sim scripts (entry.sim) run in the game’s own Lua 5.0 match VM and have a different API (wum.sim.*); they are not covered here. They are documented in the developer guide, including the Melange 0.11 additions wum.sim.worm(slot) (worm state and the anchor), wum.sim.worms(), wum.sim.land() and the turn-start hold wum.sim.holdTurn(ticks), wum.sim.releaseTurn() and wum.sim.turnHold(), and the turn and round counters wum.sim.turn() and wum.sim.round() and the rising-water helper wum.sim.waterSchedule{...}, and the Melange 0.16 additions wum.sim.carve/carveLine (removing land), worm:kill{...} and worm:aim(), and wum.sim.melee (melee weapons as tools, hit events and overrides), and the Melange 0.18 sim event sim.anchorInput (a walk, jump, backflip or fire press of an anchored worm; see Worms and the anchor), and wum.sim.endTurn() (ends the turn in play the way its timer does; see Ending the turn), and worm:damage(points[, {show}]) and worm:moveScale(walk, jump) (Melange 0.18: health taken at once, and a slower walk and lower jumps for one worm). A client mod sees a hold through the events melange.turnHold and melange.turnHoldEnd below.

Every mod gets its own global table. Globals a mod defines are invisible to other mods. _G is the mod’s own table.

Available:

  • Base functions: assert error ipairs next pairs pcall xpcall rawequal rawget rawlen rawset select tonumber tostring type getmetatable setmetatable collectgarbage print _VERSION.
    • print(...) writes to the mod log (wum.log.info).
    • collectgarbage accepts only "collect", "count" and "step".
    • setmetatable refuses metatables with __gc.
    • rawset refuses the shared read-only tables.
  • Libraries: string (without string.dump), table, math, utf8, coroutine, and os.time, os.clock, os.date.
  • wum, described below.

Not available: load, loadstring, dofile, loadfile, require, package, io, debug, the rest of os, and precompiled (binary) chunks. The shared tables (string, math, wum, wum.log, …) are read-only; assigning to them raises an error.

Set in [Sandbox] of Melange.ini:

Key Default Meaning
InstrPerCall 500000 Lua instructions per call from Melange into a mod (a callback, the top-level chunk, a panel function). Coroutines share the caller’s budget. A mod’s own pcall cannot catch the stop.
ModMemoryMB 16 Memory per mod. Over the limit, Lua runs one full garbage collection, then the allocation fails (“not enough memory”).
TotalMemoryMB 96 Memory for the whole VM.
HotReload 1 Reload a mod when a .lua file in its entry.client folder changes.

Faults. An error in a callback, a spent instruction budget or an out-of-memory is a fault. After 3 faults the callback is disabled for the rest of the session (it is logged; a disabled panel shows a notice). If the top-level chunk fails, the mod is not loaded and the error, with its line number, is shown on the Mods page.

Hot reload. The new script is compiled and run first. If it fails, the previous version keeps running and the error is shown. If it succeeds, every handle of the previous version (event subscriptions, timers, panels, menu items, hotkeys, draw callbacks, textures) is revoked, then wum.mod.onReload(prev) is called with the previous version’s wum.mod.keep table. wum.storage is not affected.

Name Description
wum.mod.id The mod id.
wum.mod.name Display name.
wum.mod.version Version from spice.json.
wum.mod.dir The mod folder (UTF-8).
wum.mod.readFile(rel) Contents of a file inside the mod folder as a string, or nil, err. Needs permissions.filesystem: "own-folder". At most 8 MB.
wum.mod.keep A table that is handed to the next version on hot reload.
wum.mod.onReload Set it to function(prevKeep) ... end to receive the previous version’s keep after a hot reload.

wum.log.debug(...), wum.log.info(...), wum.log.warn(...), wum.log.error(...): arguments are converted with tostring and joined with tabs. Records go to the Melange log (category mod, tagged with the mod id). At most 200 records per second per mod.

Name Description
wum.events.on(name, fn) Subscribes fn(payload, name); returns a handle.
wum.events.off(handle) Unsubscribes; returns true if the handle was the mod’s.
wum.events.emit(name, table) Sends mod.<your id>.<name> to every subscriber (a name that already starts with mod.<your id>. is kept). The table is copied (strings, numbers, booleans and nested tables only).

Events are delivered at the next frame, in mod load order, then subscription order, at most 256 per frame.

Names:

  • Engine messages by name, for example GameLogic.Turn.Started or Weapon.Fired. The payload table holds the decoded message fields (vectors are {x, y, z} arrays); messages without a decoder give an empty table. Land.NewShape (Melange 0.16) gives {radius, pos} for every change to the land, explosions and wum.sim.carve alike.
  • Melange events:
    • melange.frame {frame}: every frame.
    • melange.scene {scene}: boot, menu, loading or match.
    • melange.match.start {online}, melange.match.end.
    • melange.mods.changed: the mod list changed.
    • melange.reload {id}: a mod was hot-reloaded.
    • melange.level.sea {on, r, g, b, opacity, reflection, foam} (Melange 0.15): the level’s sea material, set by its script with wum.level.water{Sea = {r, g, b, opacity}, SeaKeep = {reflection, foam}} (the colour 0-255, the rest 0-1), and {on = false} when the match ends. A mod that replaces the water shader draws the sea as that matte colour (erg.md).
    • melange.level.haze {on, r, g, b, amount, start, distance} (Melange 0.15): the level’s haze, set by its script with wum.level.water{Haze = {r, g, b, amount}, HazeRange = {start, distance}} (the colour 0-255, amount 0-1, the range in world units, 0 for the mod’s own), and {on = false} when the match ends. A graphics mod with a haze fades the distance and the band under the horizon toward that colour (erg.md).
    • melange.turnHold {ticks, tick, roundMsLeft} and melange.turnHoldEnd {ticks, tick, roundMsLeft}: a sim mod held the next turn start with wum.sim.holdTurn (ticks is the hold’s length, or at the end the ticks held; tick the sim tick; roundMsLeft the round clock, which does not run during the hold). See the developer guide’s sim scripts.
    • melange.turn {index, team, worm, mine, ai, online}: a turn started (after the game state snapshot of that frame); see wum.game.turn(). melange.ui {weaponPanel, pause, readyIntro}: one of wum.game.ui()’s flags changed. (Melange 0.12)
    • melange.lobby.enter {isHost}, melange.lobby.leave, melange.lobby.members, melange.lobby.owner {owner, isHost}, melange.lobby.phase {phase}: see wum.lobby. (Melange 0.12)
    • melange.media {type, ...}, melange.input.mouse, melange.input.wheel, melange.input.key, melange.input.char, melange.input.paste: delivered only to the mod they concern; see wum.media and wum.input. (Melange 0.12)
    • melange.spotify {type = "status", state, user, premium, linked, error, app}: delivered only to the mods that use wum.spotify. (Melange 0.13; app from 0.14.1)
    • melange.ai {type, job, ...}: delivered only to the mod that called wum.ai.ask (or registerClaude, requestKey). (Melange 0.18)
    • Events that C++ modules post with melange::lua::PostEvent (to every listener) or melange::lua::PostEventTo (to one mod’s listeners, Melange 0.12).
  • Mod events: mod.<id>.<name> from wum.events.emit.
Name Description
wum.timers.after(seconds, fn) Calls fn() once after seconds (wall clock); returns a handle.
wum.timers.every(seconds, fn) Calls fn() every seconds (0 = every frame); returns a handle.
wum.timers.cancel(handle) Stops a timer; returns true if the handle was the mod’s.

Settings declared in the settings array of spice.json. They are shown on the Mods page and stored in [Mod.<id>] of Melange.ini.

Name Description
wum.config.get(key) The value (boolean, integer, number or string, by the declared type), or the default.
wum.config.set(key, value) Checks the type, min/max and options, then stores it. Raises on an undeclared key or a bad value.
wum.config.getFor(mod, key) Melange 0.18, needs permissions.modSettings: another loaded mod’s player setting, typed like get. nil, "unknown-mod" when that mod is not loaded, nil, "undeclared" when it declares no such setting. Match settings are the host’s and are never reachable here (see wum.rules.setting).
wum.config.setFor(mod, key, value) Melange 0.18, needs permissions.modSettings (raises without it). The same checks as set against the target’s declared type, range and options, but a refusal is a value: true, or false, reason ("unknown-mod", "undeclared", or the message set would raise, such as wum.config: size is out of range).

A per-mod JSON file (Melange\mods\<id>\storage.json next to melange.asi), at most 1 MB. Values are strings, numbers, booleans and tables of those (sequences become arrays, other tables need string keys). Writes are saved within 2 seconds, and when the mod is unloaded or the game exits.

Name Description
wum.storage.get(key) A copy of the stored value, or nil.
wum.storage.set(key, value) Stores a copy; nil removes the key. Raises when the file would exceed 1 MB.
wum.storage.remove(key) Removes the key.
wum.storage.keys() The keys, sorted.

JSON for mods (Melange 0.18). Strict RFC 8259, UTF-8 checked on input and output, at most 64 levels deep, at most 4 MB of text. Integers are exact: a JSON number without a fraction or exponent that fits 64 bits decodes to a Lua integer, and a Lua integer encodes as its digits (a larger integer decodes to a float). Lua has no null and cannot tell [] from {}, so there are three markers. Object keys encode in sorted order, so the same table always gives the same text.

Name Description
wum.json.encode(value) The JSON text, or nil, message (a function, a cycle, NaN or infinity, a non-string key, bad UTF-8, too deep or too large). nil encodes as null. A table that is a sequence 1..n is an array; any other table is an object; an empty untagged table is {}.
wum.json.decode(text) The value, or nil, message (with line and column) for bad JSON, duplicate keys, bad UTF-8, a lone surrogate, nesting over 64 or text over 4 MB. Every JSON null becomes wum.json.null, so a key set to null is present and an absent key is nil. Every empty array is returned tagged with wum.json.array, so it encodes back as [].
wum.json.null The value that stands for JSON null. It is a userdata that prints as wum.json.null.
wum.json.array(t) Tags t (a new table if omitted) as an array, so that an empty one encodes as []. Returns t. Raises if t already has another metatable.
wum.json.object(t) Tags t as an object (keys must be strings), so an empty one is {}. Returns t.

Read-only game state.

Name Description
wum.game.scene() "boot", "menu", "loading" or "match".
wum.game.inMatch() A match (including the attract demo) is running.
wum.game.online() A net session exists: the online lobby, its loading screens, the match and its results (Melange 0.12; before 0.12 it was true only once the online match was running).
wum.game.turn() {index, team, worm, ai, mine, phase}: index = turns started in this match, counted from 1 as sim.turnStarted’s turn is (before Melange 0.13 a first turn that started in the frame the match’s VM appeared was missed, so index ran one behind for the whole match); team = the current team’s index and worm = the active worm’s index, both absent between turns; ai = the current team is computer-controlled; mine = the current turn is played on this machine (online: the turn owner’s player is local, kept across the gap between turns; offline: the team is local and not AI); phase = "intro" (the hot-seat timer), "play", "retreat", "settle" or "none". The fields after index are Melange 0.12.
wum.game.ui() {weaponPanel, pause, readyIntro, feCursor, attract} booleans: the weapon panel is open, a pause menu or popup is up, the “Ready?” turn intro shows, the frontend’s own menu cursor is active, the attract demo runs. nil on an unrecognised build. Changes are also sent as melange.ui. (Melange 0.12)
wum.game.tick() Simulation ticks (50 per second) since the match started, when the sim bridge is running; otherwise 0.
wum.game.worms() The worms of the current match, an array of {slot, team, name, health, alive, pos={x,y,z}, vel={x,y,z}, yaw, weapon} (vel is the engine’s own velocity in world units per second: the game keeps it per millisecond of game time and Melange multiplies by 1000; it is the worm’s physics velocity, so it is about zero while the worm stands or walks and large while it flies, falls or is knocked back; weapon is the weapon id, absent when none; yaw is the facing angle in radians about +Y, the facing direction is (sin yaw, 0, cos yaw), it is not wrapped to a range and it spins while a worm is thrown; aim (Melange 0.16) is the aim pitch in radians, the angle an aimed weapon fires at; clone (Melange 0.16) is the name of the weapon clone the active worm holds, for example "kWeaponGraveSpade", with weapon its base’s id, and absent for a vanilla weapon; voice (Melange 0.17) is the speech bank the game speaks the worm with, such as "voclassi", for wum.audio.voice, absent when it could not be read). Empty outside a match; nil, "unavailable" on an unrecognised game build or with [GameState] Enabled=0.
wum.game.teams() The teams of the current match, an array of {slot, name, active, ai, local, voice}; empty outside a match, nil, "unavailable" as above. voice (Melange 0.17) is the team’s speech bank, such as "voclassi", for wum.audio.voice; it is absent when it could not be read (in build #1077 the team’s own field is empty during a match, so the worms’ voice is the one to use).
wum.game.activeWorm() The slot of the worm whose turn it is, or nil.
wum.game.theme() The level theme of the current match as the game names it (for example "SPACE"), or nil outside a match.
wum.game.match() The current match’s clocks and levels, or nil outside a match (and on an unrecognised build or with [GameState] Enabled=0). See below.
wum.game.landRay(x0, y0, z0, x1, y1, z1) Casts the segment from (x0, y0, z0) to (x1, y1, z1) against the land with the game’s own collision code. On a hit it returns t, nx, ny, nz: t from 0 to 1 along the segment (the point is p0 + t * (p1 - p0)) and the unit outward surface normal there. A miss returns nil. See below for the details and the other results.

wum.game.landRay in detail. It runs the straight sweep the game’s camera uses for its own ray casts, against the landscape (including terrain that weapons have changed) and the heightmap around it; it does not see water, worms, crates, barrels or other objects. The hit is the last point outside the land the sweep found, refined by bisection, so it sits on or just in front of the surface; a segment that starts inside land hits at t = 0. The game’s collision state is saved and restored around the call, so a ray never changes the match, online or offline.

  • nil alone: no land along the segment, the segment has zero length, or no match is running.
  • nil, "budget": more than 256 rays this frame (all mods together); try again next frame.
  • nil, "invalid": a coordinate is not finite or is beyond ±1e6.
  • nil, "unavailable": the game build is not #1077, [GameState] Enabled=0, the call is not on the main thread, the loaded landscape is not one the sweep can take (1024 or more land frames, or its objects do not look right), or a sweep faulted earlier this session (logged; the function then stays off until the game restarts). Only the build, setting and fault causes are permanent: the thread and landscape causes can clear on a later call or the next match, so a mod should try again later rather than give up for the session.
  • Segments longer than 4096 units are searched over their first 4096 units only; t is still measured along the whole segment.
  • Arguments that are not numbers (or strings that convert to numbers) raise an error.

Check for the function before using it, since older Melange versions do not have it: if wum.game.landRay then ... end. Melange logs the number of rays and their average and longest time at the end of each match.

wum.game.match() returns a table read from the game’s own data, from the same snapshot as wum.game.worms() (read once per frame), or nil outside a match. Detect it with if wum.game.match then ... end (Melange 0.11 and later).

Field Meaning
roundMs, roundMsLeft The game’s RoundTime and RoundTimeRemaining, integer milliseconds.
turnMs, turnMsLeft TurnTime and TurnTimeRemaining, integer milliseconds.
waterLevel Water.Level, the water surface height in world units.
suddenDeath true once sudden death started in this match: the versus script sends Comment.SuddenDeath when the round clock runs out (GameLogic.ActivateSuddenDeath counts too, for scripts that send it).
turnsStarted Turns started in this match (GameLogic.Turn.Started).
landMin, landMax {x, y, z}: the landscape’s bounding box (Land.MinBounds, Land.MaxBounds). Absent until the level has reported a valid box.

The land box is the game’s own. landMin.y is the lowest point of the land, which is usually under the water (-76 and -61 on the two quick-match maps tried, with the water at 0), and landMin.x/z can sit at the arena’s edge rather than at the land (-1500 on both). roundMs is the round’s full length from the scheme, so the time played is roundMs - roundMsLeft.

These are this machine’s values, for display. A client script must not feed them into anything that has to match between players; sim scripts read deterministic state through wum.sim.

Name Description
wum.ui.panel(id, title, fn[, open]) Adds an overlay panel. fn() draws its contents every frame while it is open. Returns a handle. The overlay’s View menu lists it as <mod name> > <title>; a / in title ("Tools/Grid") adds a submenu level.
wum.ui.menu(path, fn[, opts]) Adds a menu item Mods/<mod name>/<path> (for example "Reset"). opts.checked is an optional function asked every frame the menu is open: the item shows a check mark while it returns true, for an item that switches something on and off (wum.ui.menu("Grid", toggleGrid, {checked = function() return gridOn end})). An error in it counts as a fault (the getter is disabled after 3, the item still works) and reads as unchecked. Returns a handle.
wum.ui.hotkey(keys, fn) Calls fn() on a hotkey such as "Ctrl+Shift+H", whether or not the overlay is shown. The key is kept from the game. A hotkey needs at least one of Ctrl, Shift or Alt, except that a bare function key ("F1" to "F12") is accepted; any other key without a modifier raises an error, because it would take an ordinary gameplay key away from the game.
wum.ui.remove(handle) Removes a panel, menu item or hotkey handle.

Widgets, only inside a panel function:

Name Returns
wum.ui.text(s)
wum.ui.button(label) true when clicked
wum.ui.checkbox(label, value) value, changed
wum.ui.sliderFloat(label, value, min, max) value, changed
wum.ui.sliderInt(label, value, min, max) value, changed
wum.ui.inputText(label, text[, maxLen]) text, changed
wum.ui.combo(label, index, items) index, changed (1-based)
wum.ui.collapsingHeader(label) true when open
wum.ui.progressBar(fraction[, text])
wum.ui.separator(), wum.ui.sameLine(), wum.ui.spacing()

Positions are tables {x, y, z} or {x = , y = , z = } in world units. Colours are 0xRRGGBBAA, "#RRGGBB", "#RRGGBBAA" or {r, g, b[, a]} in 0..1. frames (default 1) keeps a primitive for that many frames. Called outside a draw callback, primitives are queued for the next frame; inside wum.draw.on, they are drawn at that stage.

Name Description
wum.draw.line(a, b, color[, width[, frames]]) World line.
wum.draw.box(min, max, color[, width[, frames]]) World box outline.
wum.draw.sphere(center, radius, color[, width[, frames]]) World sphere outline.
wum.draw.axes(origin[, length[, width[, frames]]]) X/Y/Z axes.
wum.draw.quad(p1, p2, p3, p4, color[, frames]) Filled quad.
wum.draw.text(pos, text, color[, size[, frames]]) Screen-aligned text above a world point.
wum.draw.hudLine(x0, y0, x1, y1, color[, width[, frames]]) HUD line in window pixels (origin top-left).
wum.draw.hudRect(x0, y0, x1, y1, color[, filled[, width[, frames]]]) HUD rectangle.
wum.draw.hudText(x, y, text, color[, size[, frames]]) HUD text. Melange 0.12 also takes wum.draw.hudText(x, y, text, color, size, opts) with opts: font (a wum.draw.font id; UTF-8, kerning, a missing glyph draws ?), shadow (a colour, or false), shadowOffset = {dx, dy}, align = "left" | "center" | "right", maxWidth (pixels) and ellipsis (cut with an ellipsis at maxWidth).
wum.draw.hudImage(x0, y0, x1, y1, texture[, tint[, frames]]) HUD image from wum.draw.texture.
wum.draw.texture(rel[, opts]) Loads a PNG from the mod folder; returns a texture id, or nil, err. Freed when the mod unloads or reloads. A mod can hold 256 at a time. Textures get a full mip chain and trilinear filtering. With opts, the texture is for a shader (see Shader textures): {wrap = "repeat"|"clamp", filter = "linear"|"nearest", layers = n}. {mips = false} (Melange 0.12) loads a HUD texture without mips (linear filtering), which saves a quarter of its memory. From Melange 0.12, hudImage, hudImageUV and hudNine take only the calling mod’s own textures.
wum.draw.sprite(tex, x, y, z, halfW, halfL, ax, ay, az[, color[, mode]]) Textured world sprite; only inside a "world" or "worldLate" callback. Returns true, or false when dropped by the per-frame cap. See Sprites.
wum.draw.mesh(verts, idx, tex, model[, opts]) Triangle mesh from vertex and index arrays; only inside a "world" or "worldLate" callback. Returns true, or false when over the per-frame cap. See Meshes.
wum.draw.mesh(handle, tex, model[, color[, opts]]) The same for a mesh kept with wum.draw.newMesh.
wum.draw.newMesh(verts, idx[, format]) Keeps a mesh in Melange so it is not sent every frame; returns an integer handle, or nil, "too many meshes". Freed when the mod unloads or reloads.
wum.draw.freeMesh(handle) Frees a kept mesh; true if the handle was one of this mod’s live meshes.
wum.draw.on(stage, fn) Calls fn(stage) every frame at "world", "worldLate", "hud" or "screen"; returns a handle. "screen" (Melange 0.12) runs at present time in window pixels, after the game’s composite and every post effect, before the overlay, in the frontend, the lobby, loading screens and matches alike; it is never tinted or post-processed. The hud* primitives work there.
wum.draw.hudImageUV(x0, y0, x1, y1, tex, u0, v0, u1, v1[, tint]) A HUD image showing only the texture rectangle (u0, v0)-(u1, v1) (0..1), for atlases. (Melange 0.12)
wum.draw.hudNine(x0, y0, x1, y1, tex, l, t, r, b[, opts]) A nine-slice panel: l, t, r, b are the source insets in texture pixels; the corners are drawn at scale * inset, the edges and the centre are stretched. opts: tint, scale (default 1), uv = {u0, v0, u1, v1} to take the slice from part of an atlas. (Melange 0.12)
wum.draw.font(atlasPng, metricsJson) Loads a bitmap font from two files in the mod folder (format holo-font-1, see Mod fonts); returns a font id, or nil, reason. At most 4 per mod; freed on unload and reload. (Melange 0.12)
wum.draw.textSize(text, size[, opts]) w, h in pixels of text drawn by hudText at size, with opts.font for a mod font. (Melange 0.12)
wum.draw.hudClip(x0, y0, x1, y1) Clips the following HUD primitives of this callback to the rectangle (nests 4 deep, intersecting); wum.draw.hudClipEnd() ends the innermost clip. Clips still open end with the callback. (Melange 0.12)
wum.draw.hudPolyline(pts, color[, width[, opts]]) (Melange 0.18) One anti-aliased stroke through pts = {x1, y1, x2, y2, ...} (2 to 8192 points, window pixels), as one GL draw. width defaults to 1 (at most 512). opts: join = "round" (default), "miter" (limit 4, a sharper corner falls back to a bevel) or "bevel"; cap = "round" (default) or "butt"; closed = true joins the last point to the first; outline (a colour) with outlineWidth (default 2, extra pixels on each side) strokes a wider line under it first, the cartoon outline. Returns true, or false when the mod is over its vertex budget (nothing is drawn). See Batched HUD primitives.
wum.draw.hudSegments(segs, color[, width]) (Melange 0.18) Independent segments {x0, y0, x1, y1, ...} (at most 16384) in one batch, anti-aliased, butt caps; for grid lines, wicks and ticks. Returns true or false as hudPolyline.
wum.draw.hudRects(rects, colors[, opts]) (Melange 0.18) Filled rectangles {x0, y0, x1, y1, ...} (at most 16384), corners in either order. colors is one colour (a number or a string), or a table with one colour per rectangle (integers 0xRRGGBBAA or "#RRGGBB[AA]" strings; a {r, g, b} table is read as that per-rect list, not as one colour). opts.outline (a colour) and opts.outlineWidth (default 1) draw a border inside each rectangle; a fill with alpha 0 is skipped, so an outline alone gives a hollow box. Not anti-aliased. Returns true or false as hudPolyline.
wum.draw.hudTris(verts[, opts]) (Melange 0.18) A triangle list {x, y, rgba, ...} with an integer 0xRRGGBBAA per vertex, at most 49152 vertices (a multiple of 3); colours blend across each triangle. opts.format = "xy" takes {x, y, ...} and draws all of it in opts.color. A triangle with a non-finite coordinate is skipped. Returns true or false as hudPolyline.
wum.draw.media(player, x0, y0, x1, y1[, opts]) Draws a wum.media player’s current frame into the rectangle and returns the picture rectangle px0, py0, px1, py1, or nil when there is no frame yet. opts: fit = "contain" (default, letterboxed) | "cover" | "stretch", alpha 0..1. Only the mod that opened the player can draw it; drawing it is what keeps its frames uploading. (Melange 0.12)
wum.draw.off(handle) Removes a draw callback.
wum.draw.weaponIcon(name, x0, y0, x1, y1[, opts]) Draws a weapon’s weapons-panel icon into the rectangle: the game’s own icon, or the replacement an enabled mod’s weaponIcons gives it, or a clone’s own panelIcon (a clone without one shows its base’s). name is a catalog key ("Bazooka"), an engine name ("kWeaponBazooka", "kUtilityChangeWorm") or a clone name ("kWeaponAcidSpitter" or "AcidSpitter"). opts: tint (a colour), state = "normal" | "off" (greyed, for an unavailable weapon), fallback (default true). Returns true; or false, reason ("loading", "no panel icon", "unknown weapon", or why the icons could not be read) after drawing the name’s initials on a dark tile instead, unless fallback = false. The icons are read once per launch from the game’s Data\Bundles\Bundl09.xom (about a second, in the background, on the first call), so the first frames show the initials. Any mod may draw them; a HUD or "screen" stage. (Melange 0.18)

hudPolyline, hudSegments, hudRects and hudTris (Melange 0.18) draw many shapes as one HUD primitive and one GL draw, so a chart of thousands of points costs a few Lua calls instead of thousands. Each call is drawn in call order with the other HUD primitives, at "hud" or "screen" (inside a wum.draw.on callback, at that callback’s stage), and inside the open hudClip rectangles, which cut the strokes cleanly.

  • Budget. A mod may expand 262144 vertices per frame across the four calls (a rectangle is 6, a segment 18, a straight polyline segment 18 and an outlined polyline twice that; a sharp corner adds a wedge). A call that would pass the budget draws nothing and returns false; the budget starts again every frame.
  • Unchanged data is cheap. A call whose arguments are the same as one of the last few frames reuses that frame’s geometry instead of expanding it again (it still reads the table, still counts against the budget and is drawn as before), so a chart that redraws the same arrays every frame costs a fraction of one that changes. Reading a table is fastest when it is a plain array built with t[#t + 1] = v or a constructor.
  • Errors. Bad arguments raise: a table that is not a flat array of numbers, the wrong count (segments and rectangles come in fours, triangles in threes), a width of 0 or less, an unknown option or option value. A point or rectangle with a non-finite coordinate (nan, inf) is skipped, not raised; repeated points collapse.
  • Pixels. Coordinates are window pixels with the pixel centre at + 0.5. A 1 px line at an integer y straddles two pixel rows at half strength; use y + 0.5 for a crisp one.
  • Strokes have a 1 px feather (half a pixel of fade on each side of the width). A gentle bend (under about 20 degrees) is stitched without extra geometry, so a smooth curve of 4000 points costs 18 vertices per segment; a sharper corner ends both segments flat and adds the join. Translucent colours overlap slightly on the inside of a sharp corner; use opaque colours for strokes with many sharp turns.
local t = {}
for i = 0, 399 do t[#t + 1] = 40 + i * 2; t[#t + 1] = 200 + 60 * math.sin(i / 20) end
wum.draw.on("screen", function()
wum.draw.hudRects({30, 120, 830, 340}, 0x101820d0, {outline = 0x3a506bff, outlineWidth = 2})
wum.draw.hudPolyline(t, "#ffd166", 2, {outline = 0x000000c0, outlineWidth = 1.5})
end)

The batched HUD primitives: a smooth outlined polyline, mitered, bevelled and round joins, rectangles with outlines, a
vertex-coloured triangle fan and a gradient fill

wum.draw.font (Melange 0.12) reads a PNG atlas (at most 2048x2048: white glyphs with their outline baked in black, so the hudText colour tints the fill and the outline stays black) and a JSON metrics file:

{"format": "holo-font-1", "size": 28, "scale": 2, "lineHeight": 34, "ascent": 26, "outline": 2,
"glyphs": {"65": [0, 0, 30, 36, 1, -26, 29]}, "kern": {"65,86": -2}}

size is the pixel size at scale 1, and the atlas is baked at scale times that. Glyph keys are Unicode code points in decimal, each [x, y, w, h, xoff, yoff, adv] in atlas pixels; kern pairs adjust the advance between two code points.

Metrics, so a mod can measure text the way Melange draws it: every number except size and scale is in atlas pixels, and a text drawn at size S (the size argument of hudText and wum.draw.textSize) multiplies every atlas pixel by S / (size * scale). A glyph’s top-left is at the pen + xoff and the baseline + yoff, where the baseline lies ascent below the top of its line; the pen then advances by adv plus the kern value of the pair (previous character, this character), if any. A line is lineHeight tall. wum.draw.textSize(text, S, {font = f}) returns the width of the widest line (the sum of the advances and kerns, not the ink) and lines * lineHeight as the height; "\n" starts a new line. Text is UTF-8; a code point the font lacks draws as ?, or is skipped when ? is missing too, and control characters other than "\n" are skipped. Text past 64 KB is neither drawn nor measured. Without opts.font, the measure is of the built-in font at that size. hudText with maxWidth and ellipsis cuts a line to fit and ends it with U+2026 (or ...).

wum.draw.sprite(tex, x, y, z, halfW, halfL, ax, ay, az[, color[, mode]]) draws a textured quad for particles, sparks, smoke and similar effects. Detect it with if wum.draw.sprite then ... end (Melange 0.6 and later).

  • tex: a texture id from this mod’s wum.draw.texture. Any other number raises an error. The PNG can use straight or premultiplied alpha (pick the matching mode). It is sampled with bilinear filtering and mipmaps. Mips are averaged weighted by alpha, unless every pixel has r, g and b no greater than its alpha (a premultiplied image), in which case they are averaged as stored.
  • x, y, z: the world centre. halfW: half the width, in world units. halfL: half the length along the axis.
  • ax, ay, az: the world-space stretch axis (any length; it is normalised).
    • Zero axis: a round billboard that faces the camera. It is 2*halfW square, halfL is ignored, and the image is upright (texture top at the top of the screen).
    • Otherwise: a view-facing quad 2*halfW wide whose long side follows the screen projection of the axis, as for a velocity-stretched particle. Texture v runs from the tail (v = 0, the PNG’s top row) at centre - axis*halfL to the head (v = 1, the bottom row) at centre + axis*halfL, so draw streak textures with the head at the bottom. u runs 0..1 across the width. The tail and head keep their real depths, so the streak is in perspective.
    • When the axis points nearly at the camera, the sprite is not allowed to look shorter than min(halfW, halfL). It shows as that much quad in the axis’s screen direction (screen up if it has none), so a particle flying straight at the camera does not vanish.
  • color: a tint multiplied with the texture, in any colour form above. The default is opaque white.
  • mode: "alpha" (default, straight alpha blending), "premul" (premultiplied: ONE, ONE_MINUS_SRC_ALPHA; the tint is premultiplied by its own alpha, so its alpha still fades the sprite) or "additive" (SRC_ALPHA, ONE).

Sprites are drawn at the callback’s stage after that stage’s other primitives. They are depth-tested against the scene, with no depth writes and no face culling. All sprites of a stage, from every mod, are sorted back to front by view depth, and sprites at equal depth keep their call order. Additive sprites blend the same in any order, so each unbroken stretch of additive sprites in that order is regrouped by texture.

Sprites are batched into one vertex array per stage, with one draw call per run of consecutive sprites (in that order) that share a texture and mode. One texture costs one draw call however many sprites use it. Alpha-blended textures interleaved in depth cost a draw call for every switch.

A mod can draw 4096 sprites per frame across all its callbacks. Past that, calls do nothing and return false. They also return false if the stage already holds 65536 sprites from all mods.

The arguments are checked. A non-number position or size, a bad colour or mode, or calling outside a world callback raises an error. halfL and the axis may be nil (0). Non-finite values (NaN, infinity) are ignored: nothing is drawn and the call returns true. The same happens for halfW <= 0, and for a non-zero axis with halfL == 0.

local spark = wum.draw.texture("fx/spark.png")
wum.draw.on("worldLate", function()
for _, p in ipairs(particles) do
local v = p.vel
wum.draw.sprite(spark, p.x, p.y, p.z, 0.4, 0.4 + p.speed * 0.05, v.x, v.y, v.z, 0xffd080ff, "additive")
end
end)

Measured cost, x86 release build on a Ryzen 7 7800X3D with a Radeon RX 7800 XT:

  • Lua: about 0.18 ms per 1000 wum.draw.sprite calls.
  • Melange’s side (expand, sort, runs, GL submission), sharing one texture: about 0.04 to 0.06 ms per 1000.
  • Worst case: 4096 sprites with three textures shuffled at random in depth make about 3100 draw calls. That costs about 0.28 ms of CPU per 1000 sprites, plus a few milliseconds of GPU time per frame. Prefer few textures.

wum.draw.mesh draws an indexed triangle mesh in the world, for shapes sprites cannot make: a mound of sand, a cast, a shell. Detect it with if wum.draw.mesh then ... end (Melange 0.11 and later).

  • verts: a flat array of numbers, 8 per vertex: x, y, z, nx, ny, nz, u, v (position, normal, texture coordinate). With the format "pntc" (the array form’s opts.format, or newMesh’s third argument) it is 12 per vertex, adding r, g, b, a in 0..1, multiplied with everything else. Normals need not be unit length (a zero normal reads as +Y). At most 16384 vertices.
  • idx: a flat array of 1-based vertex numbers, three per triangle (at most 49152). Front faces wind counter-clockwise as seen from outside.
  • tex: a texture id from this mod’s wum.draw.texture, or nil (or 0) for none. A texture loaded with {wrap = "repeat"} tiles when u, v go past 0..1; a texture array cannot texture a mesh. The texture is multiplied with the vertex colour.
  • model: where the mesh goes. nil (the vertices are world coordinates), 16 numbers (a column-major matrix with the translation in 13..15, as glLoadMatrixf takes it), or {pos = {x, y, z}, yaw = radians, scale = s or {x, y, z}}: scaled, then turned about +Y by yaw (+Z turns to (sin yaw, 0, cos yaw), a worm’s facing at that yaw), then moved to pos.
  • color (handle form) or opts.color (array form): a tint in any colour form; its alpha fades the mesh.
  • opts:
Option Default Meaning
lit true Shades each vertex ambient + (1 - ambient) * max(0, N . light) with its world-space normal. false: colours as given.
light {0, 0.936, -0.351} The world direction toward the light (normalised); the default is the game’s landscape light.
ambient 0.6 0..1.
blend "alpha" "alpha" (SRC_ALPHA, ONE_MINUS_SRC_ALPHA) or "additive" (SRC_ALPHA, ONE).
depthWrite true Writes depth, so later world draws (particles, sprites) behind the mesh are hidden. Turn it off for see-through meshes.
cull true Skips back faces. false draws both sides.
xray false true draws without the depth test, over everything.
color, format The array form only, see above.

The mesh is depth-tested against the scene, so land and worms in front of it hide it. Lighting is computed on the CPU for each draw and follows model’s rotation: a mesh turned with yaw keeps its light from the same world direction. Meshes draw at the callback’s stage before that stage’s sprites, in call order (they are not sorted), so draw see-through meshes after opaque ones.

A mod can keep 64 meshes with 262144 vertices in all. Each frame it can make 256 wum.draw.mesh calls drawing up to 131072 vertices across its callbacks; past that, calls do nothing and return false. Bad arguments (an index out of range, a vertex array that is not 8 or 12 numbers per vertex, a non-finite number, another mod’s texture or handle, an unknown option) raise an error.

-- A dome of sand at each worm's feet, built once and drawn every frame.
local sand = wum.draw.texture("fx/sand.png", {wrap = "repeat"})
local function dome(rings, segs, radius, height)
local v, idx = {}, {}
for r = 0, rings do
local t = r / rings
local rr, y = radius * math.sin(t * math.pi / 2), height * math.cos(t * math.pi / 2)
for s = 0, segs do
local a = s / segs * 2 * math.pi
local x, z = rr * math.cos(a), rr * math.sin(a)
for _, n in ipairs({x, y, z, x / radius, y / height, z / radius, s / segs * 4, t * 2}) do v[#v + 1] = n end
end
end
for r = 0, rings - 1 do
for s = 0, segs - 1 do
local a, b = r * (segs + 1) + s + 1, (r + 1) * (segs + 1) + s + 1
for _, i in ipairs({a, a + 1, b, a + 1, b + 1, b}) do idx[#idx + 1] = i end
end
end
return wum.draw.newMesh(v, idx)
end
local mound = dome(8, 24, 14, 6)
wum.draw.on("world", function()
for _, w in ipairs(wum.game.worms() or {}) do
if w.alive then wum.draw.mesh(mound, sand, {pos = w.pos}, "#e8c890ff") end
end
end)
Name Description
wum.render.camera() {pos, fwd, up, near, far, fov, overridden} of the main camera as it is drawn (with a camera override, the override’s; on a pack or Test level, after [LevelCamera] moved it out of the land), or nil. fov is the vertical field of view in degrees; overridden is true while a camera override is set.
wum.render.gameCamera() The same for the game’s own camera, as it would be drawn without an override (to blend back into it), or nil.
wum.render.cameraOverride(spec) Draws the frame from a camera of the mod’s choosing; nil clears it. See Camera override.
wum.render.wormPose(slot, spec), wum.render.wormCopy(slot, spec), wum.render.wormBones(slot), wum.render.wormPoseStatus(), wum.render.wormPoseCaps() Render-only worm poses (the body laid down or carried, held animation clips and pose sliders, hands, a neck stump), a severed-head copy and the posed bone positions (Melange 0.16). See Worm poses.
wum.render.wormStump(slot, spec) The worm drawn without its tail, closed by a flat cap; its own channel, so it combines with another mod’s wormPose (Melange 0.18). See Worm poses.
wum.render.hideHud(frames) Leaves the engine’s own HUD (worm names and energy, the team bars, the turn timer, the wind) out of the picture for this frame and the frames - 1 after it (an integer, 1 to 600), for a cut-scene; call it every frame while it should last. Mods’ hud draws and the Final post-FX still show. Several mods may hide it at once. hideHud(), hideHud(nil), hideHud(false) or hideHud(0) ends this mod’s hiding. Returns true, or false, "unavailable" without the MirageNoHud module. Render only: the game, online play and Wormsign see nothing of it. It ends when the mod unloads. (Melange 0.16)
wum.render.worldToScreen(pos) x, y, depth in window pixels, or nil behind the camera.
wum.render.windowSize() width, height.
wum.render.timing() {busyMsP50, busyMsP95, frameMsP50, fps, frames, gpuMs}. gpuMs (where the GPU timers are supported): the GPU time of the last timed frame, ms: frame (the whole swap-to-swap command stream), world, worldLate, postWorld, hud, final, screen (each present once read). screen (0.18) is the GPU drawing of the "screen" stage’s primitives alone; the swap-to-swap frame also counts the GPU waiting while draw callbacks run on the CPU. fps can be CPU-bound (testenv B: near 36 whatever is drawn), so compare gpuMs.frame for a graphics cost.

wum.render.cameraOverride({pos = {x, y, z}, target = {x, y, z}[, up = {x, y, z}][, fov = degrees][, frames = n]}) replaces the camera the frame is drawn with, for cut-scenes, tours and replays. Detect it with if wum.render.cameraOverride then ... end (Melange 0.11 and later).

  • pos is the eye and target the point it looks at (not the same point). up is the up direction (default {0, 1, 0}; when it is parallel to the view direction the game’s own fallback applies). fov is the vertical field of view, 5 to 150 degrees (default: the game’s); the aspect ratio and depth range stay the game’s.
  • frames, 1 to 600 (default 30): the override ends by itself when it has not been set again for that many frames, so a mod that stops (an error, a disabled callback) gives the camera back. Set it every frame while it should last. A value set in a frame is drawn from the next frame on.
  • It also ends at the end of the match, when the mod unloads or reloads, and with wum.render.cameraOverride(nil), which returns true if the mod’s own override was cleared.
  • Returns true; false, "busy" while another mod’s override is set (one mod at a time); false, "unavailable" outside a match or on an unrecognised game build. Bad fields raise an error.

The override only changes the picture. The game keeps its own camera: aiming, the turn camera, the camera keys and the logical camera that online games and Wormsign compare between machines (reasons 6 to 10 in docs/wormsign.md) are untouched, so an override on one machine changes nothing on another. Melange puts the override into the engine’s render camera only while the frame is drawn, and the whole frame agrees with it: the land, sea, worms, particles and labels, the engine’s culling, wum.draw primitives, sprites and meshes, post-FX (mg_proj, mg_invProj and depth reconstruction from them) and GLSL replacements. wum.render.camera(), wum.render.worldToScreen() and positional wum.audio follow it everywhere, so HUD labels placed with them stay on their world points. wum.render.gameCamera() reads the game’s camera, which keeps moving underneath.

Two things still follow the game’s camera, because the game decides them before drawing: the land the game fades out when it stands between its camera and the active worm, and the picture-in-picture view of a computer player’s aim.

-- Orbit the active worm for five seconds, then hand the camera back.
local t0 = os.clock()
wum.events.on("melange.frame", function()
local t, slot = os.clock() - t0, wum.game.activeWorm()
if t > 5 or not slot then return end
for _, w in ipairs(wum.game.worms() or {}) do
if w.slot == slot then
local a, p = t * 0.8, w.pos
wum.render.cameraOverride{pos = {p.x + 140 * math.sin(a), p.y + 60, p.z + 140 * math.cos(a)},
target = {p.x, p.y + 10, p.z}, fov = 45}
end
end
end)

wum.render.wormPose(slot, spec) redraws one worm in a pose of the mod’s choosing: laid down on its back, carried onto another worm and leaning over it, holding a clip of the game’s own animations, looking or reaching with the game’s pose sliders, its head or tail bent, its hands carried to world points, or its head flattened into a neck stump (Melange 0.16; check if wum.render.wormPose then). It changes only how the worm is drawn: its position, physics, collisions and everything the game and Wormsign compare stay as they are, so a pose on one machine changes nothing on another.

wum.render.wormPose(slot, {
frames = 3, -- 1..600 (default 3): lasts that many frames unless set again
-- the body: the drawn mesh's own transform (hats, glasses and the shadow follow it)
body = {pitch = deg, roll = deg, yaw = deg | heading = deg, move = {x, y, z} | at = {x, y, z}},
-- the game's animation clips, by name, held at a time, and its pose sliders
clips = {{name = "HoldBat", time = 0.5, weight = 2}, ...}, -- up to 8
clipMode = "layer", -- "layer" (default: over the game's clips) or "base" (only Base and these)
sliders = {HeadRotX = 1.3, RightArmRotY = 0.8, TailAngle = 1.2, ...}, -- up to 8; 0..2, 1 = neutral
-- the skinning palette, in world space, on top of the body and the clips
root = {rot = {pitch, yaw, roll}, move = {x, y, z}, pivot = {x, y, z}},
head = {rot = {...}, move = {...}, pivot = {...}},
tail = {...},
leftHand = {target = {x, y, z}, rot = {...}}, -- the wrist (and the hand with it) carried to a world point
rightHand = {...},
hide = {head = "stump", attachments = "hide"}, -- flatten the head; hide (or "follow") hats and the like
})

Every field is optional, and the three layers stack in the engine’s own order: the body first, then the clips, then the palette edits, which are made in world space on the worm as the body and clips left it.

  • body (degrees, world units) turns and moves the drawn worm about its feet, the mesh origin, which the engine draws 3 units above the worm’s position. pitch is a lean in the worm’s own frame after its heading: positive tips it forward onto its face, -90 lays it on its back with its head behind it. roll turns it about its forward axis (90 lies it on its side; combined with a pitch the order is inferred, so keep to pitch and heading for a reliable pose). yaw is added to the drawn yaw; heading replaces it (0 faces +Z, 90 faces +X, as worms()[i].yaw in radians). move is added to the drawn origin; at puts the worm’s position there instead (same coordinates as worms()[i].pos). Name tags and health bars stay at the worm’s real position: hide them with wum.render.hideHud.
  • clips holds each clip at time seconds (it does not play on; advance time yourself to animate it) with weight 0..5 (default 1; 1..3 reads best, more exaggerates some channels). "layer" blends them over everything the game is playing; "base" keeps only the Base clip and these (the sliders go back to neutral unless set). The clip library is the worm’s own (about 330 clips: HoldBat, Fire2Bat, Cower, Terror, ClutchChest…); the Recover*, Blastflight*, Nailed and Squish clips carry root motion and move the whole worm far off its feet.
  • sliders sets the time of the game’s procedural pose clips (HeadRotX, HeadRotY, LeftArmRotX, LeftArmRotY, RightArmRotX, RightArmRotY, TailAngle, TailLag, TipAngle, Eyes_LR, Eyes_UD, Teeth), clamped to 0..2, 1 neutral. Clip and slider names are case-insensitive. An unknown name answers false, "no clip <name>". Before the worm has been drawn in the match its library is not known yet, and its clips and sliders are left out for that call.
  • The palette edits: rot is degrees ({pitch, yaw, roll} or {pitch =, yaw =, roll =}); here positive pitch tips the worm’s front (+Z) up and yaw turns +Z toward +X. A turn is made about pivot (world), then move (world units) is added. Default pivots: the main bone (root), the head bone (head, at the neck), the first tail bone (tail) and the wrists (leftHand, rightHand). target moves the wrist pivot onto that world point instead of move; the hand moves rigidly with it. Order: the root first; each group then turns about its own pivot after the root moved it; the stump last. Prefer body for laying a worm down: a palette root turn leaves its hat and shadow behind.
  • hide = {head = "stump"} flattens the head (the upper part of the worm, its eyes and mouth) onto the neck plane across the worm’s own up direction: a flat-topped stump. Its hat and the like are hidden with it.
  • hide.attachments: the head’s accessories (hat, moustache, glasses). true or "hide" hides them; "follow" keeps them on the head (they always follow body, clips and sliders; on a build that skins on the GPU they also follow a palette head or root edit). The weapon the engine puts in the worm’s hand keeps its place under palette edits: give a posed tool an invisible held mesh and draw it yourself with wum.draw.mesh at the wormBones wrists.
  • A spec with no edits ({} or {frames = n}) changes nothing drawn and only tracks the bones for wormBones.
  • Returns true; false, "busy" when another mod poses that slot (one mod per slot); false, "no clip <name>"; false, "unavailable" outside a match or without MiragePose. wum.render.wormPose(slot, nil) clears the mod’s own pose. A pose also ends when the mod unloads or the match ends. Bad fields raise (a non-table body, hide, clips or edit, yaw with heading, move with at, a non-number angle, slider or clip field, a clip without a name, a clipMode other than "layer" or "base", more than 8 clips or sliders, a hide.head other than "stump", an unknown hide.attachments, frames out of range).

wum.render.wormCopy(slot, {pos = {x, y, z}[, rot = {pitch, yaw, roll}][, frames = n]}) draws the worm a second time as its severed head: the real head mesh with its texture, skin and team colours, the neck carried to pos and turned by rot (palette convention, applied to the head as it is drawn, so a copy of a lying worm starts out lying), the rest of the body closed over the cut. Pair it with hide = {head = "stump"} on the worm itself. Same returns and lifetime as wormPose; nil clears it. The copy is drawn only while the engine draws the worm: when a killed worm unspawns at the end of its throes, the head copy goes with it (use worm:kill{throes = ...}, up to 10 s, to keep it, and a client mesh for gore that must stay longer).

wum.render.wormStump(slot, {tail = true[, cut = 0..1][, frames = n]}) draws the worm without its tail, for a worm that lost it (Melange 0.18; check if wum.render.wormStump then). The tail (the tail, tail2 and tail3 bones and the skin weighted to them) closes onto a flat cap. At the root of the tail (cut = 0, the default, up to about 0.27) the cap is level across the upright body at the ground, so the worm stands on a flat bottom; it moves with the body as the worm walks, jumps, is laid down or dies. Further down (cut up to 1, the tip, where nothing is removed) a stub of the lying tail stays, closed by a cap facing along it. frames is 1..600 (default 3): re-set it every frame for a stump that lasts the rest of the match.

  • It is a channel of its own, not a field of wormPose: one mod per slot and part (today the only part is tail), applied after every wormPose edit. Another mod may pose the same worm at the same time (Kindjal laying it down or executing it), and the stump stays on it.
  • Returns true; false, "busy" when another mod holds that slot’s tail stump; false, "unavailable" outside a match or without the palette layer (wormPoseCaps().stump). {tail = false} or nil clears the mod’s own stump on the slot (true if there was one). It also ends when the mod unloads or the match ends. A tail that is not a boolean, a cut that is not a number from 0 to 1 and frames out of range raise.
  • Like a pose it changes only the drawing: the worm’s position, collisions and everything Wormsign compares stay as they were. The hands, the head and the attachments are left alone.

wum.render.wormBones(slot) returns the world positions of the worm’s 34 bone pivots as last drawn (posed), keyed by bone name (main, tail, tail2, tail3, head, the lip, mouth, eye and brow bones, shoulder_left, wrist_left, the left finger bones, shoulder_right, wrist_right, the right finger bones), plus neck (the point the stump is cut at), feet (the drawn mesh origin, the pivot of a body turn) and tailCut (Melange 0.18: the centre of the tail stump’s cap, or where the default cut would be on a worm without one), each {x, y, z}; nil when the worm was not drawn in the last two frames while posed, tracked, copied or stumped. For the unposed bones (hand targets for a dig), track the worm with an empty pose: wum.render.wormPose(slot, {frames = 5}), then read wormBones from the next frame. It reports the body and clips as drawn, so it is the way to find a lying worm’s neck or chest.

wum.render.wormPoseStatus() returns the status and the number of draws handled so far. The status is "ok" once a draw of a posed, tracked or copied worm has been identified and handled, "untested" while skinned worms were drawn but no posed one was identified yet, "no skinned worm drawn yet", "unsupported" (no palette route on this build) or "disabled" ([MiragePose] Enabled=0). Set the pose first and check a few frames later.

wum.render.wormPoseCaps() returns which layers work here, as booleans: body, clips, palette (the palette edits, the stump and wormBones), copy (wormCopy), hideAttachments and stump (wormStump, Melange 0.18). A layer whose engine code did not match is left out alone, and the fields for it are ignored. Pick the staging per layer: for example, with palette false draw the hands’ tool in the fists, and with body false keep the worms upright.

How it works. Build #1077 skins worms on the CPU. MiragePose works at three points of the engine’s frame:

  • body: after each worm’s graphic update, the worm mesh’s position and rotation are written again for the frame (the next update writes the game’s own back). The accessories are hidden the same way, and shown again as the game’s own accessory masks say.
  • clips and sliders: around the evaluation of the worm’s animation, its table of clip weights and times is changed for the call and put back. The game’s own clip choices and animation events are not touched.
  • the palette: around the draw of each skinned shape of a posed worm, its 34 bone matrices are replaced by the posed ones for the call (and once more for the head copy), then put back. Which worm a shape is comes from its bones, learned while the worms stand apart, so a worm lying on another is still told apart.

On a build that skins on the GPU, the palette is read back from the BlendMat registers of the FFVertex*Skinned programs instead, and a head accessory is a draw whose origin lies within 9 units of the head. Nothing is changed once every pose has expired or the match ended. pose.test <slot> prone|stump|mount|copy|lie|ride <slot>|clip <name> <time> <weight>|probe|off (Automation) poses a worm for 250 frames (about 4 s at 60 fps) for screenshots; [MiragePose] Log=1 logs what it found.

Every effect can be read; only the mod’s own effects (<mod id>/<effect>) can be changed.

Name Description
wum.postfx.list() Array of {id, title, stage, order, enabled, failed, own}.
wum.postfx.enable(id, on) Turns one of the mod’s effects on or off.
wum.postfx.setParam(id, param, v1[, v2...]) Sets a uniform (up to 16 floats, or one table of them).
wum.postfx.setTransient(id, param, v1[, v2...]) Like setParam, but the value is not saved to Melange.ini and not logged. For values a mod sets every frame. An effect reload keeps it, unless the edit removes the param or changes its size: then it returns to its saved value.
wum.postfx.getParam(id, param[, n]) n floats (default 1).
Name Description
wum.graphics.setShadowMapSize(n) Replaces the mod’s graphics.shadowMapSize request: 512, 1024, 2048 or 4096, 0 for none, nil to go back to the manifest’s. The shadow map is rebuilt on the next frame. [MirageShadows] in Melange.ini still has the last word.
wum.graphics.shadowMap() {size, effective, vanilla, modRequest, available}: the engine’s current size, the merged request (0 = vanilla), the size from the game’s own cfg files.
wum.graphics.setSupersample(n) Asks for supersampling: 2 (1x2) or 4 (2x2) samples per pixel, 0 or nil for none. The scene targets are rebuilt on the next frame; with no request left, the game’s own /SSAA setting comes back. [MirageSupersample] in Melange.ini still has the last word.
wum.graphics.supersample() {x, y, effective, sceneWidth, sceneHeight, multisampled, modRequest, available}: the engine’s current factors, the merged request in samples (0 = vanilla), the scene’s size, and whether /SSAA is running as multisampling instead.
Name Description
wum.shaders.setParam(file, entry, name, v1[, v2...]) Sets a shader parameter the mod’s own shaders\params.ini declares, e.g. ("Landscape.cg", "*FragmentMain", "softness", 1.5). entry is the section’s glob. Errors on anything else.
wum.shaders.enableGlsl(file, entry, on) Pauses (false) or resumes one of the mod’s own shaders\<File>.<Entry>.glsl replacements, e.g. ("Landscape.cg", "LandscapeFragmentMain", false), so the game’s own program draws again. Takes effect on the next frame and is not saved. Errors if the mod ships no such file.
wum.shaders.setTexture(file, entry, sampler, tex) Binds a texture from this mod’s wum.draw.texture (or nil to unset) to a sampler of the mod’s own shaders\<File>.<Entry>.glsl replacements, e.g. ("FixedFunction.cg", "FFFragmentMainTexLit*", "materials", tex). entry is a glob. Returns true, or false while GLSL replacements are off ([MirageShaders] GlslReplace=0). Errors on another mod’s replacement or texture, or a name starting with gl_ or mg_. Melange 0.10.0 and later; see Shader textures.

A GLSL replacement can sample a mod’s own tileable textures, for example a set of material detail maps:

if wum.shaders.setTexture then -- Melange 0.10.0 and later
local mats, err = wum.draw.texture("textures/materials.png", {wrap = "repeat", layers = 8})
if mats then
wum.shaders.setTexture("FixedFunction.cg", "FFFragmentMainTexLit*", "materials", mats)
end
end
#version 130
uniform sampler2D texture0; // the engine's texture
uniform sampler2DArray materials; // the mod's texture array
// ...
vec4 m = texture(materials, vec3(uv * 8.0, layer));
  • opts.layers = n (1 to 64): the PNG is a vertical strip of n equal tiles, layer 0 at the top, and loads as one texture array (sampler2DArray). Without layers it is an ordinary 2D texture (sampler2D). Arrays need GL 3.0 and cannot be sprites. The image height must be a multiple of n.
  • opts.filter: "linear" (the default) is trilinear, with a full mip chain per layer and the anisotropy from [MirageTextures] (the merged mod requests, see the developer guide). "nearest" keeps only the base level, for data tables read with texelFetch or at texel centres. Mips average every channel as stored: alpha is data here.
  • opts.wrap: "clamp" (the default, to the edge) or "repeat".
  • A replacement’s sampler that has no Cg parameter gets its own texture unit (8 to 13, six per program at most) and reads a neutral 1x1 texture, 0.502 in every channel, until a texture is set. A sampler with a Cg parameter’s name (texture0, shadowMap, …) is the engine’s and cannot be set.
  • sampler2DArray and texture() need #version 130 in the replacement. A #version 130 fragment replacement links with the game’s vertex programs, which Cg compiles to GLSL 1.10 writing gl_TexCoord[]: keep reading gl_TexCoord[n] and writing gl_FragColor, which GLSL 1.30 still has.
  • On an older Melange, wum.shaders.setTexture is nil, and wum.draw.texture ignores opts and returns a clamped 2D texture. The extra sampler then shares unit 0 with texture0, and a sampler2DArray there makes the program’s draws fail. Require this Melange in spice.json, or pause the replacement with wum.shaders.enableGlsl(file, entry, false) when wum.shaders.setTexture is nil. See the developer guide’s Shaders section.

Per-texture values for a replacement (uniform vec4 mg_texTag[2]) come from a table the mod declares in spice.json (graphics.textureTags), not from Lua: see Texture tags.

Only for mods whose spice.json has permissions.unsafe: true. Until the player allows it in the consent dialog, every function raises “Deep Desert not granted”. Every refusal and every fault is logged. A mod only counts as a content mod online once its Deep Desert grant is actually allowed; declining (“Keep sandboxed”) keeps it out of the online content hash. Libraries that C++ modules add with the Deep Desert flag are also visible only to granted mods.

Name Description
wum.unsafe.read(addr, type[, n]) Reads memory. Types: u8 i8 u16 i16 u32 i32 f32 f64 ptr cstr bytes. For numeric types n is a count (a table is returned when n > 1); for cstr it is the maximum length (default 256); for bytes it is the length.
wum.unsafe.write(addr, type, value) Writes memory (cstr adds the terminating zero).
wum.unsafe.call(addr, conv, ...) Calls native code. conv is "cdecl", "stdcall" or "thiscall" (object pointer first), optionally with ":f32" or ":f64" for a floating-point return. Up to 8 arguments: integers, floats (passed as 32-bit floats), booleans, strings (as pointers) or nil. Returns eax or the float.
wum.unsafe.base() Load address of WormsMayhem.exe.
wum.unsafe.build() The game build name and whether Melange knows it.

A memory fault inside these functions becomes a Lua error instead of a crash. Writes that change the simulation are the mod’s responsibility.

Lets a client mod push its own data into Oasis and add a panel to it. Everything a mod adds is named mod.<its id>.<x>, so mods never collide with each other or with the core channels and methods.

Name Description
wum.web.channel(name) Registers mod.<id>.<name> and returns ch. ch:publish(tbl) sends one JSON value to every subscriber (a no-op when nobody is subscribed); ch:subscribers() is the current subscriber count. Removed automatically on hot reload or disable.
wum.web.method(name, fn) Registers mod.<id>.<name> as an RPC method. fn(params) gets the call’s parameters as a table and must return a table (or raise, which the caller sees as an error); it runs on the main thread under the same instruction budget as any other callback, so a runaway fn is stopped and the call fails, it does not hang the page.
wum.web.panel{title=, entry="web/index.html"} Serves the folder containing entry (so its assets travel with it) in a sandboxed iframe at /ext/<id>/, listed in the page’s tab bar. One panel per mod. Removed on hot reload or disable, which also closes its channels.
wum.web.tool(name, fn) Melange 0.18. Binds fn(args, ctx) to an MCP tool the mod declared in its mcp/tools.json (spice.json "mcp": {"tools": "mcp/tools.json"}, docs/mcp.md); returns a handle. A name the manifest does not declare raises (the error lists the declared ones). args is the arguments table, already checked against the tool’s inputSchema; `ctx = {client = “mcp”

A panel page has no cookie and cannot reach /ws or document outside its own frame (sandbox="allow-scripts", no allow-same-origin); it talks to the shell only through /app/ext.js, which exposes OasisExt.call(method, params) and OasisExt.subscribe(channel, filter, fn) restricted to the mod’s own mod.<id>.* names plus read-only state and log.

Mouse look and aim options, and what the game’s controls are bound to. Everything here changes the numbers the game puts into its own mouse messages on this machine, before they are sent, so other players and Wormsign recordings receive the same final values as for any other input: no option can desynchronise a match. The namespace needs build #1077 and [Controls] Enabled=1 (the default); otherwise groups() returns nil, "unavailable" and the other functions do nothing useful (binding() returns nil, setOptions is accepted and has no effect, though options() reports what it set).

Name Description
wum.input.groups() An array of the active control-group names in index order, for example {"InGame", "WormFirstPersonAiming"}. The names are Menu, InGame, WormAiming, WormFirstPersonAiming, WormMoving, WormRoping, UtilityGirder, Flying, CameraSelect, Fire, UtilityFire, CrateChuteRelease, Spectator, NetworkSpectator, AttractMode, ControllerRemoved, ManualCam, EFMVMovie and XboxSignIn. An empty table when the game has no input service yet; nil, "unavailable" on an unknown build or with [Controls] Enabled=0.
wum.input.binding(messageName) A short label of the key mapped to an engine message ("Space", "Q"), or of the mouse button ("LMB", "MMB", "RMB") when no key is, or nil when neither is (joypad bindings are not reported). Names are the game’s message names, for example "Input.JumpPressed" or "Input.FirePressed".
wum.input.setOptions(t) Sets the options in t and returns true. t fields are all optional, and a missing one means the game’s own behaviour: cameraInvertY = "game", "standard" (mouse up looks up) or "inverted"; aimInvertY = the same for aiming; blimpInvert = a boolean, applies the camera invert in the Blimp view too, which the game skips; cameraSensitivity = a number from 0.25 to 3.0 (a number outside the range is clamped), scales camera and spectator-camera motion; aimSensitivity = the same for aiming. A wrong type or an unknown string raises an error. setOptions(nil) clears everything. The last caller wins, and a mod’s options are cleared when that mod unloads or is disabled.
wum.input.options() A table of the effective values: the five fields above ("game", false and 1.0 when unset) and smoothMouse, a boolean owned by Melange’s [Controls] SmoothMouse setting that Lua cannot change.

Scaled motion keeps its fractional part from one mouse event to the next, so a low sensitivity does not drop slow movements.

Mouse regions, pointer mode and keyboard focus

Section titled “Mouse regions, pointer mode and keyboard focus”

Melange 0.12 lets a client mod take mouse clicks and typing for its own on-screen controls, without them reaching the game. This is local input filtering only: a click or key a mod takes never becomes a game input, so nothing is sent to other players and the match cannot desynchronise. [Input] AllowModInput=0 turns all of it off (every call then returns false, "unavailable" or nil).

Name Description
wum.input.cursor() x, y, source in window pixels: source is "frontend" (the game’s own menu cursor, in menus and the lobby) or "pointer" (this mod’s pointer mode in a match). nil in a match without pointer mode, since the game hides and re-centres the mouse there.
wum.input.region(id, x0, y0, x1, y1[, opts]) Claims a rectangle for the next opts.frames frames (default 2), so renew it every frame while the control shows. While the cursor is inside, button presses, double-clicks and the wheel go to this mod instead of the game (mouse moves still reach the game, and a button release whose press the game saw is always passed on). opts.cursor: "arrow", "hand" or "ibeam". Returns true, or false, "busy" when another mod’s region or focus has priority. id is a string up to 64 bytes.
wum.input.hover() The id of this mod’s topmost region under the cursor, or nil.
wum.input.pointer(on[, opts]) Pointer mode for a match: the game stops re-centring the mouse and gets no mouse input, and Melange draws a cursor (opts.cursor = a texture of this mod, or the default arrow; opts.hot = {x = px, y = px} is the texture pixel of its tip, default the top-left corner). The keyboard still reaches the game. opts.release: "click-outside" (default; a click outside every region of this mod ends it and is not passed on) or "manual". It also ends on pointer(false), Esc (consumed), the overlay taking input, the end of the match, focus loss, unload, and when a turn of this machine’s player starts. On exit the cursor goes back to the centre and the game sees no mouse jump. Returns true, or false, "busy" / false, "unavailable" (outside a match).
wum.input.pointerActive() true while this mod’s pointer mode is on.
wum.input.focus(on) Keyboard focus for a text box of this mod: keys and characters go to this mod (melange.input.key, melange.input.char, melange.input.paste) and not to the game. Hotkeys with Ctrl, Shift or Alt still work; bare F-key hotkeys do not while focused. Ends on focus(false), Esc (delivered first), the overlay taking input, focus loss or unload. Returns true or false, "busy".

Priority: the overlay first, then the mod with focus or pointer mode, then regions (the most recently loaded mod first), then the game. Events, delivered at the next frame to the mod that owns the region, focus or pointer only:

  • melange.input.mouse {region, button, down, x, y, double}: button is "left", "right", "middle", "x1" or "x2".
  • melange.input.wheel {region, delta, x, y}: delta in notches (positive away from the user).
  • melange.input.key {key, down, repeat, ctrl, shift, alt}: key is a string, the keys.h name of the key (the same names as the hotkey settings), found by scan code first and the virtual key if that is unknown: "RETURN", "NUMPADENTER", "BACK", "DELETE", "LEFT", "HOME", "ESCAPE", "A" (letters and digits are upper case), "F5". Where a key has aliases (RETURN/ENTER, BACK/BACKSPACE, ESCAPE/ESC) the first is sent. A key with no name is not delivered. Compare case-insensitively and accept both spellings. down is false on release; repeat marks auto-repeat. Also melange.input.char {text} (UTF-8) and melange.input.paste {text} (Ctrl+V: the clipboard text, at most 4096 bytes, control characters removed): focus only.

A click that Melange delivered to a mod also counts as that mod’s user gesture, which wum.media.install requires.

Plays sounds from the mod folder on this machine. It is client-only: the library exists in the client VM and not in the match VM, the sound is mixed and played locally, and nothing about it reaches the simulation, the wire, the content handshake or other players. Each player hears only what their own copy of the mod plays. The backend is XAudio2 2.9 (xaudio2_9.dll, part of Windows 10 and later); where it or an output device is missing, ready() is false and play returns nil, "audio unavailable" (load still works, since it only reads the file). It is also unavailable with [Audio] Enabled=0.

Files must be WAV: PCM (format 1, or WAVE_FORMAT_EXTENSIBLE with a PCM subformat), 16-bit, 1 or 2 channels, 8000 to 48000 Hz, at most 2 MiB. Other RIFF chunks are skipped. Anything else (24-bit, float, ADPCM, a truncated file) returns nil and a short reason such as "not 16-bit" or "too large". Convert other formats first.

Name Description
wum.audio.ready() true when sound can play. The first call starts the audio backend, so a mod can check once at start-up.
wum.audio.load(rel) Reads and decodes a WAV from the mod folder (rel is relative to it, with no .., drive or leading slash) and returns a handle, an integer, or nil, reason. Loading the same path again returns the same handle without reading the file; paths that differ only in case, in / against \, or by a . segment count as the same path. load does not need the audio backend, so a load at the top of the mod works even if the output device comes up later. A mod holds up to 64 sounds and 16 MiB of decoded audio at a time; past that load returns nil, "too many sounds loaded" or nil, "sound memory limit reached". Handles are valid only in the mod that loaded them and are freed when the mod unloads, reloads or is disabled.
wum.audio.play(handle[, opts]) Starts the sound and returns a voice id, an integer, or nil, reason ("audio unavailable", "unknown sound", "too many voices"). opts is a table, all fields optional: volume = 0 to 2, default 1; pitch = a frequency ratio from 0.5 to 2.0, default 1 (2.0 is an octave up and half as long); loop = a boolean, default false, a looping voice plays until stop or stopAll; pos = {x=, y=, z=} (or {x, y, z}) in world units, which makes the sound positional. Numbers outside a range, infinities included, are clamped; a NaN volume or pitch is replaced by the default, and a NaN pos component makes the sound silent. Without pos the sound is plain 2D.
wum.audio.stop(voice) Stops a voice and returns true, or false if it is unknown, has already ended, or belongs to another mod.
wum.audio.stopAll() Stops every voice this mod has playing and returns how many.
wum.audio.cut(handle, from, len[, fade]) (Melange 0.17) A new handle for the part of a sound from from seconds, len seconds long, clamped to the sound, or nil, reason ("unknown sound", "empty cut" when nothing is left, or a limit as for load). Both ends get a linear fade of fade seconds (default 0.008, 0 to 0.25, at most half the cut) so the cut does not click. It is a copy: it counts towards the 64 sounds and 16 MiB, and it stays valid after the source is unloaded. The same arguments (to the sample) return the same handle.
wum.audio.unload(handle) (Melange 0.17) Frees one of this mod’s sounds, its memory and its slot, and returns true, or false if the handle is unknown. Voices already playing it finish.
wum.audio.set(voice, opts) (Melange 0.17) Changes a playing voice of this mod: volume (0 to 2; a positional voice keeps its distance falloff) and pitch (0.5 to 2.0), clamped as for play; a field left out or NaN is unchanged. Returns true, or false if the voice is unknown, has ended or is another mod’s.

A positional sound is attenuated by its distance to the render camera: full volume within [Audio] Near (150 world units by default), falling linearly to silence at [Audio] Far (1500), recalculated every frame, so a moving camera and a long or looping sound follow each other. There is no panning. If the camera is not available the sound plays at its own volume. The Volume setting (0 to 1) scales everything the mod plays, and at most [Audio] MaxVoices (default 32, up to 64) voices play at once across all mods; a new play over that returns nil, "too many voices" and does not cut off a playing one. A voice stopped with stop or stopAll frees its slot at once, so a play right after it has room.

Voices end by themselves when the sound finishes. Every voice that started before the match ended is also stopped when it does, and a mod’s voices when that mod unloads, reloads or is disabled. A sound started from a melange.match.end handler is not stopped (the handler runs in the same frame as the stop), so it can be used for a victory sound; it plays on into the menu. This is expected from the code and not yet tried in game. Errors are raised only for a wrong argument type (a handle that is not a number, opts that is not a table, a volume or pitch that is not a number, loop that is not a boolean, pos that is not a table); everything else returns nil, reason.

local boom = wum.audio.load("sfx/boom.wav") -- nil, reason if it is missing or not a usable WAV
wum.events.on("melange.match.start", function()
if boom then wum.audio.play(boom, {volume = 0.8}) end -- plain 2D
end)
-- positional, a little random pitch so repeats do not sound identical:
-- wum.audio.play(boom, {pos = {x = 120, y = 40, z = -300}, pitch = 0.9 + math.random() * 0.2})

Melange 0.12 lets a client mod silence the game’s own music (the menu and match themes, sudden death, victory and the frontend music, and replacement music from mods such as Kanly’s sudden-death bank) while it plays something else. It mutes the game’s FMOD music category; sound effects, speech and ambience are untouched, the music keeps running silently (so nothing that waits on it changes), and the player’s saved music volume is never written. Detect it with if wum.audio.music then ... end.

Name Description
wum.audio.music.available() true once the game’s music category was found (a request made earlier is kept and applied then).
wum.audio.music.suppress(on[, opts]) Asks for the game music to be silenced (true) or released (false). opts.fade = seconds (default 0.4, 0 = at once). opts.level (Melange 0.18, a number from 0 to 1, default 0) ducks instead of silencing: the music is ramped to that fraction of the player’s own volume, never muted, and restored on release; 0 silences. A level outside 0..1 is clamped and a non-number is an error. Melange before 0.18 ignores level and silences. Returns true, or nil, "unavailable" / nil, "disabled" ([Audio] AllowMusicSuppress=0). Each mod has one request; the effective level is the lowest any mod asks (so one mod asking for 0 silences it whatever the others ask). A mod’s request is released when it unloads, reloads or is disabled.
wum.audio.music.suppressed() effective, mine: whether the music is silenced or ducked (by any mod), and whether this mod asks for it.

wum.audio.play also takes {kind = "music"} in Melange 0.12: such a sound is silenced together with the game music.

Melange 0.17 reads the game’s own speech from the player’s install (Data\Audio\PC\vo*.fsb, one bank per team voice), so a mod can play or remix a team’s lines without shipping them. A bank is named by its file without .fsb, in any case ("voclassi", "voRussian"); wum.game.worms() gives the bank each worm speaks with as voice (and wum.game.teams() a team’s, where the game fills it). Names are 1 to 32 letters, digits, _ or - and start with vo. A bank’s table is read once; a line is decoded (MPEG or 16-bit PCM) when it is loaded. Detect it with if wum.audio.voice then ... end.

Name Description
wum.audio.voice.lines(bank) The bank’s lines, an array of {name, seconds} in bank order, or nil, "unknown bank" / nil, "unreadable bank". Names are the bank’s own, verbatim (they differ between banks: "nooo1", "Noooo!_1", "leavemealone", "taunt 2").
wum.audio.voice.load(bank, line) Decodes one line into this mod’s sounds and returns a handle for play, cut and unload, or nil, reason (the bank reasons, "unknown line", "unsupported sample format", or a limit as for load). line matches exactly first, then ignoring case. Loading it again returns the same handle. It counts towards the 64 sounds and 16 MiB.
local team = wum.game.teams()[1]
local line = team and team.voice and wum.audio.voice.load(team.voice, "leavemealone")
if line then
local bit = wum.audio.cut(line, 0.1, 0.6) -- the first word or two, faded at both ends
local v = wum.audio.play(bit, {pitch = 1.2})
if v then wum.audio.set(v, {volume = 0.5}) end
end

Melange 0.12 plays YouTube videos and playlists and torrent (magnet) videos for client mods, for watch parties such as the Holo plugin. Everything runs on this machine for presentation only: it is not available to sim scripts, it is not part of the content handshake, and nothing about it reaches the match or Wormsign. Detect it with if wum.media then ... end; a mod that needs it declares "melange": {"range": ">=0.12.0"}.

The decoder runs in a separate 64-bit process, holo-media.exe, from the media pack: a download of about 95 MB from Melange’s own GitHub releases, installed once per machine into Documents\Melange\media and shared by every mod. Melange checks every file of it against hashes compiled into melange.asi, and the helper’s signature, before each start. Nothing is downloaded until the user clicks the mod’s download button (see wum.media.install). YouTube items use yt-dlp, which Melange keeps up to date from the same releases (at most one check a day). See the media helper for the details, and the developer guide for the [Media] settings.

Name Description
wum.media.available() true, or false, reason: "disabled" ([Media] Enabled=0), "unsupported-os" (32-bit Windows), "unavailable" (the module did not start). open, torrent, resolve and install answer with the same reasons when it is false, except that install reports "disabled" where available() says "unavailable".
wum.media.pack() The media pack: {state, version, progress, bytes, total, downloadMB, diskMB, ytdlp, error}. state is "missing", "downloading", "verifying", "installing", "ready", "updating", "error", "unsupported" or "disabled"; progress 0..1 and bytes/total while downloading; downloadMB/diskMB for the consent text; ytdlp the installed yt-dlp version; updateAvailable and updateError (0.18.0: an older pack, media-v1, runs with state = "ready" while a newer one can be installed with install(), which keeps state = "updating" and downloadMB at the small helper zip when libmpv and deno can be reused from the old folder; a failed upgrade returns to "ready" with updateError set, the same values as error); error (state "error" only): "hash" (a file is not the pinned one, or the zip or its manifest was refused; the next install() reinstalls), "disk-space" (not enough free space), "disk" (the folder cannot be written), "network", "cancelled" (cancelInstall), "blocked" ([Media] AllowDownload=0), "url" ([Media] PackUrl refused), "in-use" (the helper is running, so the pack cannot be replaced) or "error" (anything else; the log has the detail). Melange 0.18.0: also proto, the media helper’s protocol (the running helper’s, else the installed pack’s: 1 for media pack v1, 2 for later packs), and features = {audio, sources, search, radio}: audio (open{audioOnly = true} and p:video(false)), sources (SoundCloud, Bandcamp, Jamendo and archive.org) and search (YouTube search through the helper) are true with protocol 2; radio (radio:<uuid>) also needs this build’s station lookup. Check features rather than the Melange version: a 0.18 Melange with media pack v1 has none of them until the pack is updated.
wum.media.install() Starts the pack download. It must be called within 2 seconds of a click Melange delivered to this mod (a melange.input.mouse press and release inside one of its regions; the region must cover at most a quarter of the window and have existed for half a second): that click is the user’s consent, so show the size, the source and the folder next to the button. Returns true, or nil, reason: "gesture" (no click in the last 2 seconds), "busy" (a download or update is running), "ready" (the pack is installed and no newer one is available), "disabled" ([Media] Enabled=0, or the module did not start), "unsupported-os", "blocked" ([Media] AllowDownload=0) or "unavailable" (this build has no published media pack to download: a development build without [Media] PackUrl). Allowed in the menus, the lobby and matches; in a match the download is throttled ([Media] MatchDownloadKBps).
wum.media.cancelInstall() Stops a running download; returns true.
wum.media.classify(text[, opts]) Checks a link the user typed or pasted. Returns {kind = "youtube", id, playlist, live, url} or {kind = "magnet", infohash, name, url}, or nil, "unsupported-url". url is the canonical form, the only one to store or send to other players. Accepted: https:// links to youtube.com, www., m. or music.youtube.com (/watch?v=, /playlist?list=, /shorts/, /live/) and youtu.be, and magnet: links with a btih (40 hex or 32 base32 characters) or btmh infohash. Everything else is refused. A magnet keeps only its infohash, its name (dn, at most 200 bytes) and up to 8 udp, http or https trackers, and is at most 1024 bytes. Text is trimmed; more than 4096 bytes is refused. A second argument that is not a table is ignored, as in 0.17. Audio kinds (Melange 0.18.0, media protocol 2): with opts.audio == true these are accepted too (without it each of them is nil, "unsupported-url", exactly as in 0.17, so an older mod never sees a kind it does not know). Each is an https:// link with no user info or port; its query and fragment are dropped. {kind = "soundcloud", url, list}: soundcloud.com, www. or m.soundcloud.com with /<user>/<track> or /<user>/sets/<set> (user and names [a-z0-9_-], at most 100, lowercased; list is true for a set). A user’s own pages (/likes, /reposts, …) and secret links are refused. A short link (on.soundcloud.com/...) returns nil, "short-link": ask for the full link. {kind = "bandcamp", url, list}: <artist>.bandcamp.com/track/<slug> or /album/<slug> (artist [a-z0-9-], at most 63; slug [a-z0-9-], at most 200; lowercased). Custom domains are refused. {kind = "archive", url, list}: archive.org/details/<identifier> (list = true) or archive.org/details/<identifier>/<file> (identifier [A-Za-z0-9._-], at most 100, case kept; the file is one path segment of at most 255 bytes once decoded, ending in .mp3, .ogg, .flac, .m4a or .opus, re-encoded in url). {kind = "jamendo", url, list}: www.jamendo.com/track/<n>[/<slug>] or /album/<n>[/<slug>] (url is https://www.jamendo.com/track/<n> or /album/<n>). {kind = "radio", url, uuid, live = true}: radio:<uuid>, a Radio Browser station UUID in lowercase (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx). Build it from a search result; Melange resolves the station’s stream itself, so other players only ever receive the UUID. YouTube and magnet links give the same answer with or without opts. Which of these kinds can be played depends on the installed media pack (wum.media.pack()).
wum.media.resolve(url, fn) Lists a YouTube playlist (or one video): calls fn({items = {{url, id, title, duration}, ...}, title}) or fn({error, message}) with error = "ytdlp", "network", "private" or "timeout" (30 s). Returns a request id, or nil, reason. At most 4 in flight per mod and 200 items per result. Melange 0.18.0 (media protocol 2): also lists a SoundCloud set, a Bandcamp or Jamendo album or an archive.org item (or one track of them), any link classify(url, {audio = true}) accepts except radio:: its items are {url, title, duration, artist} with no id, each url a canonical track that open{audioOnly = true} plays, at most 50 per result (titles and durations can be empty or 0 for SoundCloud and Jamendo, whose lists name only the tracks). Every item may carry artist (uploader, channel or creator) and live = true. These links answer nil, "pack-update" while the installed media pack’s helper speaks protocol 1 (media pack v1).
wum.media.search(opts, fn) Melange 0.18.0. Searches for music and calls fn({source, items = {{url, kind, title, artist, durationMs, live, tags, country, codec, bitrate, licence}, ...}, next}) or fn({error, message}). Returns a request id, or nil, reason. opts.source is "youtube" (through the media helper’s yt-dlp), "radio" (the Radio Browser directory), "archive" (archive.org’s etree, netlabels and audio collections) or "jamendo" (needs [Media] JamendoClientId). opts.q is at most 100 bytes (it may be empty for a radio tag), opts.tag is a radio tag ([a-z0-9 &-], 1 to 32), opts.uuid looks up one radio station, opts.limit is 1 to 30 (default 20) and opts.offset pages radio, archive and Jamendo results (a whole number, at least 0). Every item’s url is one classify(url, {audio = true}) accepts (YouTube watch links, radio:<uuid>, archive.org details pages and Jamendo track pages); only url, kind and title are always set, and a radio item always has live = true. Results are cached for 10 minutes. next says another page exists. error is "network", "timeout" ([Media] SearchTimeoutMs, 15 s), "rate" (the service asked for a pause), "ytdlp", "no-key", "disabled" or "unavailable". Refusals (nil, reason): "invalid" (a bad source, query, tag, uuid, limit or offset), "disabled" ([Media] AllowSearch=0, or [Media] off), "busy" (2 searches in flight for the mod), "rate" (one per second per source per mod), "pack" (a YouTube search needs a protocol 2 media helper: the pack is missing or media pack v1), "no-key" (Jamendo without a client id) and "unavailable". A wrong argument type raises. Radio, archive and Jamendo search work without the media pack: Melange fetches them itself (see wum.net, whose limits, user agent and cache they share), so a mod declares nothing. A reload cancels the mod’s searches.
wum.media.torrent(magnet[, fn]) Starts a torrent from a magnet link (every file paused until one is played) and returns a torrent handle, or nil, reason: "unsupported-url", "pack", "busy" (4 open per mod), "first-use-in-match" (the first torrent of a session must start in the menus or the lobby, because Windows may ask to allow network access). fn({files, name}) runs when the file list arrives, or fn({error}) ("helper" when the media helper could not start).
wum.media.open(opts) Opens one of this mod’s players and returns it, or nil, reason: "busy" (the mod’s limit: one player before 0.18.0; since 0.18.0 two players, at most one of them with a picture, so a video and an audioOnly player can play at once), "pack" (the media pack is not installed), "unsupported-url" (not a link classify accepts), "cache-cap" (the file would not fit [Media] TorrentCacheMB or the disk), "helper" (the helper died and was restarted less than a minute ago; try again later), "closed" (the torrent was closed), or available()’s reasons. opts: exactly one source, url (a YouTube video) or torrent + file (a file index); start (seconds), paused (default true), volume 0..100 (default 70), mute, quality = 360, 480, 720 or 1080 (default 720, capped by [Media] MaxHeight), speed 0.25..4, audioLang and subLang (language codes such as "en" or "pt-BR"). Melange 0.18.0 (media protocol 2): audioOnly = true opens a player with no picture: no frame section, no texture and no video track (about 11 MB less of the game’s address space), the best AAC or MP3 audio. With it, url may also be one track of SoundCloud, Bandcamp, Jamendo or archive.org (a set, an album or a whole archive.org item is listed with resolve first) or radio:<uuid>, whose stream Melange looks up itself. New reasons: "pack-update" (the installed media pack’s helper speaks protocol 1: audioOnly needs the updated pack) and "radio" (this build cannot look stations up). A station that cannot be found later, or whose stream address is not a public http/https one ([Media] AllowHttpRadio=0 refuses plain http), sends an error event with code = "radio"; a player that meets a protocol 1 helper anyway sends code = "pack-update".

A torrent handle t:

Name Description
t:files() {{index, path, size, video}, ...} once the file list arrived, else nil. video is true for mkv, mp4, m4v, webm, avi, mov, ts and ogv files; playlists and other reference files are never playable.
t:status() {down, up, peers, progress, have, metadata}: bytes per second, peers, the played file’s progress 0..1 and its bytes on disk.
t:close() Stops the torrent and deletes its downloaded data. Torrents are also closed when the mod unloads or reloads. The data lives in a cache folder ([Media] TorrentCacheMB, 8 GB by default, under AppData\LocalLow\Melange\media-cache) that is swept at the next start if the game exits early. While a torrent is open it uploads to other peers ([Media] TorrentUploadKBps), and the swarm sees this machine’s IP address.

A player p (its methods return nil, "closed" after p:close()):

Name Description
p:play(), p:pause()
p:seek(t[, mode]) Seeks to t seconds. mode: "exact" (default), "keyframes" (fast, while scrubbing) or "relative".
p:speed(x) Playback rate 0.25..4, pitch kept.
p:volume(v), p:mute(b) Volume 0..100 (already a perceptual curve), mute.
p:track(kind, id) Selects an audio (kind = "audio") or subtitle ("sub") track by its id from p:state().tracks; false turns subtitles off.
p:quality(h) Reopens the item at the current time with another height cap (360, 480, 720, 1080), keeping pause and speed. An audio-only player keeps the value for p:video(true) and does not reopen.
p:video(on) (Melange 0.18.0) Switches the picture on (true) or off (false) by reopening the item at its current time, keeping pause, speed, volume, the height cap and p:follow. Off frees the frame section and the texture (about 11 MB of the game’s address space), as open{audioOnly = true} would have. Returns true (also when the player already is that way), or nil, reason: "busy" (another player of this mod has the picture: one per mod), "unsupported-url" (true on SoundCloud, Bandcamp, Jamendo, archive.org or radio, which have no picture: only YouTube videos and torrent files do), "pack-update" (false while the media helper speaks protocol 1), "helper" (the frame section could not be created) or "closed".
p:id() (Melange 0.18.0) This player’s number, which each of its melange.media events carries as player. A mod with two players tells their events apart with it.
p:size(w, h) Tells the decoder how large the picture is drawn, so it renders no more pixels than needed (at most 1280x720). An audio-only player keeps the size for p:video(true).
p:follow(st, hostId) Keeps this player in step with another machine’s: st = {e, i, s, p, r, a} (epoch, item id, "play" or "pause", position in seconds, rate, and the host’s wum.peer.now() in ms at which p holds), hostId the host’s SteamID string. Melange corrects the drift with the peer bus’s clock: under 0.1 s nothing, up to 1.5 s a 5 % speed nudge, beyond that a seek slightly ahead (a seek that misses by 0.35 s or more is redone once, with the lead corrected); it never pauses the host. An older epoch or timestamp is ignored. p:follow(nil) stops following. Melange 0.18.0: hostId may be left out, or be the caller’s own SteamID: then a is this machine’s own wum.peer.now() and the clock offset is 0, so the host (or a solo listener) runs its own player from the same st it sends to the others. Earlier versions need a hostId and answer nil, "invalid" without one.
p:state() {time, duration, paused, buffering, cacheAhead, speed, title, eof, w, h, aspect, tracks, following, drift, syncAction, helper}: tracks = {audio = {{id, lang, title, selected}, ...}, sub = {...}}; drift is this player’s position minus the followed target in seconds (nil if not following); syncAction is "none", "nudge" or "seek"; since 0.18.0 also audioOnly, kind ("youtube", "magnet", "soundcloud", "bandcamp", "archive", "jamendo" or "radio") and icyTitle (a radio station’s now-playing line, at most 512 bytes, nil when the stream sends none); helper is "starting", "ready", "restarting" or "dead". Read it every frame; it is not pushed as events.
p:close() Closes the player. Players are also closed when the mod unloads or reloads.

Draw a player with wum.draw.media (an audio-only player has no frame: it returns nil). Events come as melange.media to the mod they concern only. Since 0.18.0 each event about one player (loaded, ended, error, buffering and tracks) also carries player, that player’s p:id(). With type: "loaded" {title, duration}, "ended" {reason} ("eof", "error" or "stop"), "error" {code, message}, "buffering" {on}, "tracks", "helper" {state} (the helper restarts by itself at most once a minute, reopening the item where it was), "pack" {state, progress} (at most 4 times a second) and "torrent" {infohash, files}. Errors are raised only for a wrong argument type; everything else returns nil, reason.

Melange 0.13 lets client mods play music from the user’s own Spotify account. The Holo plugin uses it for party music. Melange 0.14.1 adds the sign-in setup inside the game, transfer to any Spotify Connect device and the error "not-allowlisted".

Everything runs on this machine for presentation only:

  • sim scripts cannot use it;
  • it is not part of the content handshake;
  • nothing about it reaches the match or Wormsign.

Detect it with if wum.spotify then ... end. A mod that needs it declares "melange": {"range": ">=0.13.0"}. Detect the 0.14.1 surface with if wum.spotify.setup then ... end: setup, setClientId, pasteClientId, copy, openDashboard, cancel and transfer always ship together, so test setup once. A mod that needs them declares "melange": {"range": ">=0.14.1"}.

Setup. Signing in needs a Spotify app’s Client ID. Melange uses the first valid one (32 letters and digits) of:

  1. "user": the one set in the game through setClientId() (Melange keeps it in %LOCALAPPDATA%\Melange\spotify\client.json, never in Melange.ini);
  2. "ini": [Spotify] ClientId in Melange.ini, an optional override (re-read at most every 2 seconds and at every connect());
  3. "builtin": the app built into the release. Spotify lets an app in Development mode have only a few users, which its owner adds by hand, so the built-in app signs in with one click only for those accounts. Builds without one (developer builds, forks) skip it.

An invalid value at any level is ignored and the next one is used. When none gives an ID, available() is false, "no-client-id". Everyone else sets up their own free Spotify app from the mod’s UI, with no ini editing: openDashboard() opens Spotify’s “create app” page, copy("redirectUri") puts the Redirect URI to register on the clipboard, and pasteClientId() with setClientId() saves the new app’s Client ID. A sign-in belongs to the Client ID it was made with: setClientId() that changes the Client ID in use signs out (the stored sign-in is deleted, an open sign-in ends); an ini edit that changes it only stops using the stored sign-in, which comes back if the old ID returns. The user’s own app ("user" or "ini") redirects to http://127.0.0.1:<[Spotify] RedirectPort>/callback (default 8780); the built-in app uses the first free port of 8780, 8781 and 8782.

The click. A click is a melange.input.mouse press and release that Melange delivered inside one of this mod’s regions, where the region covers at most a quarter of the window and had existed for half a second before the press, within the last 2 seconds. Another mod’s click does not count.

  • connect() (starting or re-opening a sign-in) and openDashboard() need a click and use it up.
  • setClientId(), pasteClientId() and copy() need a click but leave it, so one click can run pasteClientId(), then setClientId(), then connect(), in that order.
  • Nothing else needs a click. A missing click returns nil, "gesture"; it never raises.

Consent and privacy. The user signs in on Spotify’s own page in their browser. Melange opens that page only when wum.spotify.connect() runs after a click (above). Once the sign-in finished, the browser shows a page that says whether it worked, and the game comes back to the front ([Spotify] ReturnToGame); mods need do nothing.

  • A mod only sees the account after the user clicked that mod’s own button once. Melange remembers this per mod; another mod’s button does not count.
  • The refresh token is stored encrypted with Windows DPAPI for the current user, in %LOCALAPPDATA%\Melange\spotify\token.bin.
  • %LOCALAPPDATA%\Melange\spotify\client.json holds only the Client ID set in the game. A Client ID is not a secret.
  • No token ever reaches Lua, and neither does the whole Client ID in use (setup().appHint is its last 4 characters).
  • The clipboard is written only by copy(), with a fixed Melange string, after a click. It is read only by pasteClientId(), after a click, and Lua receives only a 32-character Client ID found there, never the rest of the clipboard.
  • openDashboard() opens one fixed URL in the user’s browser.
  • Melange itself talks only to accounts.spotify.com and api.spotify.com.

Playback. Playback happens in the user’s Spotify app (desktop, phone, web player, speaker, console, TV) through Spotify Connect. It needs Spotify Premium and an open device. devices() lists every device and transfer() moves the playback to one.

Melange never pauses music by itself. Unloading or reloading a mod, closing its UI and disconnect() all leave the music playing.

Not allowlisted (a heuristic). An app in Spotify’s Development mode works only for the accounts under its User Management. For any other account Spotify answers HTTP 403 with a text such as “Check settings on developer.spotify.com/dashboard, the user may not be registered.” or “User not registered in the Developer Dashboard” (plain text, or inside the JSON error.message). There is no documented reason code, so Melange classifies an answer as "not-allowlisted" when its status is 403 and the first 1024 bytes of its body, lowercased, contain “may not be registered”, or both “not registered” and “developer”. PREMIUM_REQUIRED and every other 403 keep their meaning. Melange checks the account right after the sign-in (the sign-in is not kept, status() is "error" with error = "not-allowlisted", and the browser page says “This Spotify app is not open to your account”), and every later Web API answer (the callback gets {error = "not-allowlisted"}, Melange signs out, queued requests fail with "auth", and status() becomes the same error). What to tell the user: with app == "builtin", the shared app is not open to this account, so they should set up their own app (the setClientId() flow); with "user" or "ini", they should add the account under User Management of their app.

Name Description
wum.spotify.available() true, or false, reason: "disabled" ([Spotify] Enabled=0), "unavailable" (the module did not start), "no-client-id" (none of the game’s Client ID, [Spotify] ClientId and a built-in app gives a valid one; a release with a built-in app always has one).
wum.spotify.setup() Melange 0.14. The sign-in setup, for a setup screen. Always returns a table, never raises, works in the console: {app, appHint, builtin, ini, redirectUri, dashboardUrl}. app is "user", "ini", "builtin" or nil (no Client ID). appHint is the last 4 characters of the Client ID in use (nil when app is). builtin is true when this build has a built-in app. ini is true when Melange.ini holds a valid ClientId. redirectUri is "http://127.0.0.1:<RedirectPort>/callback", the Redirect URI to register in the user’s own app. dashboardUrl is "https://developer.spotify.com/dashboard/create". When the module did not start: app is nil, ini is false, and redirectUri uses port 8780. The full Client ID is never returned.
wum.spotify.setClientId(id) Melange 0.14. Saves (or clears) the Client ID set in the game. id is a string or nil; any other type raises. Needs a mod context (it raises in the console, like connect()) and a click, which it does not use up. Surrounding ASCII whitespace is trimmed; "" or nil clears it; otherwise it must be exactly 32 letters and digits. If the Client ID in use changes, Melange cancels an open sign-in and signs every mod out (the stored sign-in is deleted). An "error" state is cleared either way, also when the value was already saved (then nothing else happens). Returns true, or nil, reason: "gesture", "invalid" (not a Client ID, or longer than 1024 bytes), "io" (the file could not be written), "unavailable" or "disabled".
wum.spotify.pasteClientId() Melange 0.14. Reads the Windows clipboard’s text (at most 4096 characters) and returns the Spotify Client ID found there, without saving it: the trimmed text when it is exactly 32 letters and digits, or else the one run of exactly 32 letters and digits in it (two or none: nothing found). Needs a mod context and a click, which it does not use up. Returns the 32-character string, or nil, reason: "gesture", "clipboard" (nothing usable, or the clipboard is busy or empty), "unavailable" or "disabled". Lua never sees any other clipboard content.
wum.spotify.copy(what) Melange 0.14. Puts a fixed Melange string on the clipboard. what must be a string (else it raises); the only accepted value is "redirectUri", which writes setup().redirectUri exactly. Needs a mod context and a click, which it does not use up. Returns true, or nil, reason: "invalid" (another what), "gesture", "clipboard", "unavailable" or "disabled".
wum.spotify.openDashboard() Melange 0.14. Opens https://developer.spotify.com/dashboard/create (fixed; no argument) in the default browser, where the user creates their own Spotify app. Needs a mod context and a click, which it uses up. Returns true, or nil, reason: "gesture", "browser", "unavailable" or "disabled".
wum.spotify.status() {state, user, premium, linked, error, app}. state is one of: "disconnected", "connecting" (the browser sign-in is open), "connected" (linked and granted to this mod) or "error". user is the Spotify display name, present when connected. premium is true for a Premium account, false for a Free one, and nil while Melange does not know: Spotify no longer tells Development-mode apps the account’s plan at sign-in, so Melange learns it from the first play, pause, resume, seek, volume or transfer answer (one that works means Premium, "premium" means Free) and sends a melange.spotify event when it changes. A learned Premium plan is kept with the sign-in; a learned Free one is unknown again after Melange restarts, so an upgrade is noticed. Treat nil as unknown, not as Free. linked is true when Melange holds a signed-in account, even one this mod was not granted yet. In that case connect() grants it at once without opening the browser. error is set when state is "error": "denied" (the user refused), "timeout" (no answer within 3 minutes), "network", "invalid-client" (the Client ID or redirect URI is not the registered one), "exchange" (any other sign-in failure), "revoked" (Spotify no longer accepts the stored sign-in) or "not-allowlisted" (Melange 0.14.1: Spotify refused the account because it is not registered on the app, see below; linked is false, the sign-in was not kept or was removed). Like every "error", it ends at the next connect(), at cancel(), or when setClientId() changes the Client ID in use. app (Melange 0.14.1) is the Client ID in use, the same as setup().app: "user", "ini" or "builtin"; absent when there is none.
wum.spotify.connect() Links Spotify for this mod. It needs a click (see above), which it uses up. If no account is linked yet, it opens Spotify’s sign-in page in the browser; the redirect goes to http://127.0.0.1:<port>/callback, which Melange serves only during the sign-in (the user’s own app: [Spotify] RedirectPort; the built-in app: the first free one of 8780, 8781 and 8782). While a sign-in this mod started is open, a click opens the same page again and returns true (the 3-minute limit is not extended). Returns true when the sign-in started or was re-opened, the account was granted, or it already was. Otherwise it returns nil, reason: "gesture" (no click in the last 2 seconds), "busy" (another mod’s sign-in is open), "port-busy" (the redirect port is in use; for the built-in app all of 8780..8782), "browser" (the browser could not be opened) or one of available()’s reasons. The result arrives as a melange.spotify event.
wum.spotify.cancel() Melange 0.14. Ends an open browser sign-in without signing anyone out, and clears an "error" state. No click needed; works in the console. Returns true when a sign-in was open (state goes from "connecting" to "disconnected", or stays "connected" when linked), false otherwise. If the user’s browser was already returning to Melange, its page says “Sign-in cancelled”.
wum.spotify.disconnect() Signs Melange out of Spotify for every mod. It deletes the stored sign-in, cancels queued requests (their callbacks get {error = "auth"}) and returns true. It does not stop the music.
wum.spotify.library(opts, fn) Lists the user’s library. opts.kind is one of: "tracks" (saved songs), "playlists" (the user’s playlists) or "playlist" (the songs of playlist opts.id, a 22-character Spotify id). opts.offset is an integer ≥ 0 (default 0). opts.limit is 1..50 (default 50). fn receives {kind, items, offset, limit, total, next, skipped}. For songs, items = {{uri, name, artists, album, durationMs, playable}, ...}: uri is a spotify:track: URI and artists is the names joined with ", ". Local files and podcast episodes are left out and counted in skipped. For playlists, items = {{id, uri, name, owner, tracks}, ...}. next is true when more items follow. Spotify gives apps the songs only of playlists the user owns or collaborates on; for any other playlist (such as Spotify’s own mixes) the request fails with "restricted" or "not-found", or gives no items. Returns a request id, or nil, reason.
wum.spotify.devices(fn) fn({items = {{id, name, type, active, restricted, private, volume, supportsVolume}, ...}}): the user’s Spotify Connect devices (desktop app, phone, speaker, console, TV, web player, …). type is Spotify’s string as sent ("Computer", "Smartphone", "Tablet", "Speaker", "TV", "AVR", "STB", "AudioDongle", "GameConsole", "CastVideo", "CastAudio", "Automobile", "Unknown", …), at most 32 bytes. private (Melange 0.14.1) is true for a device in a private session. volume is present when Spotify sends it; supportsVolume (Melange 0.14.1) only when Spotify says whether the device takes volume(). A device without an id is left out. Returns a request id, or nil, reason.
wum.spotify.transfer(opts[, fn]) Melange 0.14. Moves the user’s playback to a Spotify Connect device (PUT /v1/me/player). opts is a table (else it raises). opts.deviceId is a string from devices() (another non-nil type raises; missing or not 1..128 letters, digits, _ or -: nil, "invalid"). opts.play is a boolean or nil (another type raises): true starts playback there; false or nil keeps the current state (playing stays playing, paused stays paused). No click needed. A playback control, like play: fn({ok = true}) or fn({error, message}), for example "premium" (a Free account), "not-found" (the device is gone), "restricted" or "no-device". Returns a request id, or nil, reason.
wum.spotify.play(opts[, fn]) Starts playback. opts takes exactly one of: uri (a spotify:track: URI), uris (1..50 of them, played in order), or context (a spotify:playlist: URI) with an optional offset (a 0-based index, or a track URI in it). It also takes positionMs (integer ≥ 0) and deviceId (from devices; default the active device). fn({ok = true}) or fn({error, message}). Returns a request id, or nil, reason.
wum.spotify.pause([fn]), wum.spotify.resume([fn]) Pauses or resumes the active device. Returns a request id, or nil, reason.
wum.spotify.seek(ms[, fn]) Seeks the current track to ms (integer ≥ 0). Returns a request id, or nil, reason.
wum.spotify.volume(pct[, fn]) Sets the active device’s volume, 0..100 (an integer). Some devices, such as phones, refuse it with "restricted". Returns a request id, or nil, reason.
wum.spotify.playback(fn) Reads the user’s current playback. With nothing playing, or no device, it is fn({active = false}). Otherwise fn({active = true, playing, uri, name, artists, durationMs, positionMs, at, device = {id, name, type, volume}, context, linkedFrom}). at is the wum.peer.now() time in ms at which positionMs held: the midpoint of the request. uri, name, artists and durationMs are present only when a song plays (not an episode or an ad). linkedFrom is a spotify:track: URI, present only when Spotify relinked the song for the listener’s market: it is the URI that was asked for (in play or a playlist), while uri is the one playing. Returns a request id, or nil, reason.

Return values. Every request function (library, devices, play, pause, resume, seek, volume, playback and, from 0.14, transfer) returns an integer request id, or nil, reason:

  • "auth": Spotify is not connected for this mod.
  • "busy": this mod has 8 requests waiting.
  • "invalid": a malformed URI or id, more than one source in play, a number out of range, NaN, or a non-integer.
  • One of available()’s reasons.
  • A wrong argument type raises.

The other functions return true, a string (pasteClientId) or a table (setup, status), or nil, reason with one of "gesture", "invalid", "io", "clipboard", "browser", "busy", "port-busy", "unavailable", "disabled" or "no-client-id" (available() returns false, reason; cancel() returns a boolean). Only wrong argument types raise.

Callbacks. Callbacks run on the main thread, once per request. A request without fn reports nothing. A failed request passes {error, message} to fn. error is one of:

  • "auth": signed out, or the sign-in was revoked.
  • "premium": the account is not Premium (Spotify refused the call).
  • "no-device": no active Spotify device; pass deviceId from devices.
  • "restricted": the device or the account refused.
  • "not-found": for example a playlist id that does not exist, or a device that is gone.
  • "not-allowlisted" (Melange 0.14.1): Spotify refused because the account is not registered on the (Development-mode) app; Melange also signs out (see above).
  • "bad-request"
  • "rate": Spotify’s rate limit; retryAfter holds the seconds to wait.
  • "network"
  • "timeout": no answer within 15 seconds, counted from the call, including the time spent waiting behind other requests.
  • "server"
  • "bad-response"

Melange spaces the calls of all mods together ([Spotify] RequestsPerMinute, default 90) and honours Spotify’s Retry-After. Playback controls (play, pause, resume, seek, volume, transfer) go ahead of reads. A mod that polls playback should do so no more than every few seconds.

When a mod unloads or reloads, its waiting requests are dropped and their callbacks never run. The music keeps playing.

Event. melange.spotify goes to the mods that use wum.spotify. Its payload is {type = "status", state, user, premium, linked, error, app}, the same as status(). It is sent whenever the sign-in state, the account, its known plan (premium), this mod’s grant or (Melange 0.14.1) the Client ID in use (app: setClientId() by any mod, an ini edit, Melange’s start) changes.

Melange 0.18 lets a client-only mod fetch public data (rates, prices, headlines) from the reviewed sources of Melange’s registry. The mod lists the source ids it uses in spice.json network.sources and never names a host. Melange core does all the fetching; the player consents per mod first.

Everything is presentation only:

  • sim scripts cannot use it;
  • a mod with network must be client-only, so it is never part of the content handshake;
  • nothing about it reaches the match, Wormsign or other players.

Detect it with if wum.net then ... end; a mod that needs it declares "melange": {"range": ">=0.18.0"}.

Name Description
wum.net.available() true, or false, reason: "disabled" ([NetFeeds] Enabled=0), "unavailable" (the module did not start), "undeclared" (the mod has no network block, or none of its sources is in this Melange’s registry), "consent" (the player has not answered the consent modal yet, or the mod’s authors or source list changed since), "offline" (the player chose Keep offline). Never raises; the console sees false, "undeclared".
wum.net.sources() The calling mod’s declared sources, in declared order: {{id, name, host, state, needsKey, hasKey, needsContact, hasContact, attribution, tos, risk, allowed}, ...}. state is "ok", "needs-key", "needs-contact", "not-allowed" (a high-risk source the player has not turned on, or one turned off with [NetFeeds] Allow.<id>=0), "cooldown" (the host asked to wait: a 429, 503, 403 or 451) or "unknown". Never the key. {} for the console and a mod without network.
wum.net.fetch(source, req[, fn]) Queues a GET. req = {path, query = {k = v}, decode = "json" | "csv" | "rss" | "text", ttl = seconds, maxBytes, priority = "high" | "normal" | "low"}. The source must be declared and allowed, path must match one of its path patterns, every query key must be one it lists (values are strings, numbers or booleans, at most 600 bytes, matching the key’s pattern), decode (default: the source’s first) must be one it allows, and ttl below the source’s minimum is raised to it. Returns a request id, or nil, reason: "undeclared", "not-allowed", "path", "query", "decode", "busy" (16 requests of this mod already waiting), "needs-key", "needs-contact", "consent", "offline", "disabled", "unavailable". Raises only for wrong argument types.
wum.net.cancel(id) true if id was this mod’s waiting request; its callback then runs once with {ok = false, error = "cancelled"}.
wum.net.stats() {requests, hits, bytes, inFlight, queued, perSource = {[id] = {requests, hits, errors, lastError, nextAt}}}: totals for this machine, and the calling mod’s declared sources (nextAt: when the source may be asked again, unix seconds).
wum.net.pasteKey(source) Needs a click (the wum.media.install rule: a consent-grade click on one of the mod’s regions in the last 2 s; the click is not used up). Core reads the clipboard, takes the first run of letters, digits, - and _ that has the shape of the source’s key (Twelve Data: 32 hex characters; FRED: 32 lower-case letters and digits), and stores it as [NetKeys] <source>=dpapi:... in Melange.ini (encrypted for the Windows user, shown as ******** by ini.get, never in a log or an export). Returns {hint = "...ab12"} (the last four characters), or nil, reason: "gesture", "undeclared" (the mod did not declare the source, or it has no key), "clipboard" (nothing readable on it), "invalid" (no key of that shape on it), "io", or available()’s reasons. The key never reaches Lua: core appends it to the request when it sends it.
wum.net.clearKey(source) Needs a click (not used up). Removes the stored key. true, or nil, reason.
wum.net.setContact("sec") Needs a click (not used up). Opens Melange’s own entry window, where the player types a name or an email address for the SEC’s User-Agent rule (the text never reaches Lua). It is stored encrypted as [NetFeeds] SecContact and sent only to *.sec.gov hosts. Until one is set, the sec-data, sec-files and rss-sec sources report "needs-contact". true once the window is open, or nil, reason ("gesture", "undeclared", "unavailable" when another entry window is open). The outcome arrives as melange.net {type = "contact", state = "set" | "cleared"}.
wum.net.openLink(linkId) Needs a click, which it uses up (one click, one page). Opens in the default browser an https link that Melange itself handed out this session in a decoded answer (linkIds, an RSS item’s linkId); at most 10000 are remembered. true, or nil, reason: "gesture", "unknown" (an id Melange did not hand out, or not a number), "browser" (Windows would not open it). A mod can never open a link it typed itself.

Answers. fn(res) runs once, on the main thread, never inside fetch(). A reload or an unload of the mod drops its waiting requests: their callbacks never run.

  • Success: {ok = true, status, data | body, fetchedAt, age, cached, stale, bytes, source, linkIds}. data is the decoded answer (body, the text, for "text"); fetchedAt is the copy’s os.time(), age its age in seconds; cached is true when no request was made (a copy younger than ttl); linkIds maps each https link Melange handed out in this answer to its id.
  • Failure: {ok = false, error, status, retryAfter, message}, error one of "network", "timeout", "status" (a non-2xx answer; redirects are never followed), "size", "decode", "rate" (the source’s shared rate, its daily quota, or a 429/503), "blocked" (a 403 or 451: the source rests 10 minutes), "cancelled".
  • When the source cannot answer (a network error, a timeout, a 5xx, "rate" or "blocked") and Melange holds a copy younger than 24 hours, the callback gets that copy instead: {ok = true, stale = true, cached = true, message, ...}.

Decoded shapes.

  • json: plain tables; JSON null is wum.json.null and an empty array is tagged like wum.json.decode’s.
  • csv: {header = {"Date", "1 Mo", ...}, rows = {{"11/25/2026", 4.27, ...}, ...}}; cells that are entirely a number become numbers; RFC 4180 quoting; at most 100000 cells.
  • rss (RSS 2.0, RSS 1.0 or Atom): {title, items = {{title, link, linkId, published, source, summary}, ...}}, at most 200 items. Tags and entities are stripped, summary is cut to 400 bytes, published is unix seconds (UTC) or nil. link is text for display; linkId is set for https links.

Every source has a rate shared by all mods on this machine, one request in flight per host, a size cap and a minimum ttl. Answers are cached in memory (16 MB) and on disk ([NetFeeds] CacheMB), so polling inside the ttl costs no request. In a match, requests are paced by [NetFeeds] MatchKBps, "low" priority ones wait while it is this machine’s turn, and [NetFeeds] AllowInMatch=0 holds them until the match ends (cached copies still answer).

Consent. When a mod with network is enabled, the overlay shows Melange’s consent modal (in a match it waits until the match is over). It lists every declared source with its host and says that those hosts see the player’s IP address and the queries the mod makes. Allow lets the mod fetch; Keep offline keeps it offline. High-risk sources (unofficial endpoints, such as yahoo-chart) are separate checkboxes, unchecked by default, and stay off for every mod until the player checks one ([NetFeeds] Allow.<id>=1). The overlay’s Thumper/Network panel shows the answers, with Review and Revoke.

Event. melange.net goes to the mods that declared network: {type = "consent", state = "allowed" | "offline" | "pending"} whenever the player answers, revokes, or the grant no longer matches the mod, and {type = "source", id, state = "cooldown" | "ok"} when one of its sources starts or ends a cooldown, {type = "key", source, state = "set" | "cleared"} when the player’s key for one of its sources is stored or removed, and {type = "contact", state = "set" | "cleared"} for the SEC contact.

The in-game AI prompt (Melange 0.18): a plugin sends the host’s request to Claude, which changes the game only through that plugin’s own MCP tools (wum.web.tool, docs/mcp.md). Detect it with if wum.ai then ... end; a mod that needs it declares "melange": {"range": ">=0.18.0"}. Only mods listed in [AI] ToolMods of Melange.ini (default landsraad) may use it: for every other mod each function returns nil, "not-allowed".

Backend. [AI] Backend=auto (the default) uses the player’s own Claude Code when it is installed: Melange looks for %USERPROFILE%\.local\bin\claude.exe, then claude.exe and claude.cmd in each folder of PATH, then [AI] ClaudePath (a file, or a folder holding one), and runs claude --version once per session. The job runs as claude -p with the player’s own Claude login or key; Melange passes none. Its only MCP server is Melange.exe --mcp --url-file <game>\Melange\oasis_url.txt, so its tools are this game’s MCP tools of [AI] ToolMods mods, and the Oasis token is on no command line (Melange.exe reads it from that file). The job’s working folder is the empty %LOCALAPPDATA%\Melange\ai\work, so no project instructions are read; built-in Claude Code tools (files, shell, web) are off; every tool call the job did not ask for is refused. Claude Code runs without a window in a Windows job object: cancelling, a timeout, the game exiting or the game crashing ends claude and its Melange.exe child. One job runs at a time on the PC, across all game instances. [AI] Backend=off turns it off.

When Claude Code is not found, auto uses the Messages API with the player’s own Anthropic API key ([AI] ApiKey, stored encrypted; api uses only this). Melange then runs the tool loop itself over HTTPS to api.anthropic.com (anthropic-version: 2026-10-21, server-side refusal fallbacks on), with the same tools, preamble and limits; the tools run in the game directly (no Oasis, no process). The key goes only into that request’s x-api-key header: never to Lua, a log, a peer or a file. The cost comes from the API’s reported usage at the model’s price, and the job stops at [AI] MaxBudgetUSD or [AI] MaxTurns. One request may wait up to 180 s for its answer. [AI] DevApiBase (http://127.0.0.1:<port>, a local replay server for tests) is read only by builds with the private test modules; a public build always talks to api.anthropic.com.

Settings ([AI], read at every ask): Model (default claude-opus-5-5; claude-sonnet-5-5 is faster and cheaper), Effort (low, medium (default), high, xhigh, max), MaxTurns (model turns per job, default 24, at most 100), MaxBudgetUSD (the job stops at this cost, default 1.00), TimeoutSec (default 240), ClaudePath, ToolMods, ApiKey (secret: written only by Melange’s own key entry; ini.get shows ********).

Name Description
wum.ai.status() {backend, reason, model, claude = {found, checking, version, path}, apiKey, busy, oasis}. backend is "claude-code", "api" or "none"; with "none", reason is "checking" (the search for Claude Code is still running: ask again in a second), "no-claude" (no Claude Code and no API key), "no-key" ([AI] Backend=api without a key), "off" or "unavailable" (the module did not start). The first call starts the search. model is [AI] Model. apiKey is "set" or "unset" and never the key. busy is true while a job runs on this PC (in this game or another). oasis is true while Oasis runs (a job starts it). Works in the console too.
wum.ai.ask(opts) Starts a job. opts.prompt (string, 1..4000 bytes): the player’s request. opts.system (string, at most 16 KB): the mod’s domain instructions, appended to Melange’s fixed preamble. opts.tools: a list of MCP tool names ("landsraad_get_rules") or prefixes ending in _ or * ("landsraad_") the job may call; default: this mod’s own tools. Tools of mods outside [AI] ToolMods are never allowed. opts.maxTurns: 1..100, never more than [AI] MaxTurns. Wrong types raise. It must be called within 2 seconds of a click Melange delivered to this mod (the same rule as wum.media.install), which it uses up. Returns the job id (an integer), or nil, reason: "invalid" (an empty prompt, a bad tool name or maxTurns), "too-long", "in-match" (a match, its loading or its results: never during play), "not-host" (in a lobby this PC does not own), "no-backend" ([AI] Backend=off, or neither Claude Code nor an API key), "no-key" ([AI] Backend=api without a key), "busy" (a job runs on this PC), "gesture" (no click in the last 2 seconds) or "unavailable". Allowed in the menus (local game setup) and in a lobby this PC hosts.
wum.ai.cancel(job) Stops this mod’s running job: claude and everything it started are ended (or the API request in flight is closed), and the job’s error event says "cancelled". Returns true, or false when that job is not running.
wum.ai.connectInfo() For a “Connect Claude Code” sheet: {command, melangeExe, claudeFound, checking, claudeVersion, registered}. command is the line that registers this game’s Melange.exe as an MCP server in the player’s Claude Code (claude mcp add --scope user melange -- "<game>\Melange.exe" --mcp; it holds no token). registered is true or false once claude mcp get melange answered (it runs once per session, in the background), nil before. melangeExe is nil when Melange.exe is not next to melange.asi.
wum.ai.registerClaude() Runs that claude mcp add line for the player. Needs a click, which it uses up. Returns true (the answer comes as a melange.ai event {type = "register", ok, message}), or nil, reason: "gesture", "no-claude", "no-exe", "busy" (one is running) or "unavailable".
wum.ai.requestKey() Opens Melange’s own modal (an overlay drawn by the game, not by Lua) where the player pastes an Anthropic API key, with Save, Clear and Cancel. The key is stored encrypted for this Windows account as [AI] ApiKey (dpapi:... in Melange.ini; ini.get and Oasis show ********) and is used only by the API backend when Claude Code is not found. The text never reaches Lua, the bus, the logs or an RPC reply: after it closes, status().apiKey is "set" or "unset", which is all a mod can learn. Needs a click, which it uses up. Returns true (the answer comes as a melange.ai event {type = "key", state = "set" | "cleared" | "cancelled"}), or nil, reason: "gesture", "not-allowed", "busy" (a modal is already open) or "unavailable".

Events. melange.ai goes only to the mod that asked. Payloads:

  • {type = "key", state}: the key modal closed (see requestKey); state is "set", "cleared" or "cancelled".
  • {type = "started", job, backend, model}: the job runs; backend is "claude-code" or "api".
  • {type = "step", job, kind, tool, summary} as the job goes: kind is "thinking", "text" (summary is the first 120 bytes of the model’s text), "tool" (tool is the MCP tool name, summary its arguments as compact JSON, at most 120 bytes: map them to friendly labels) or "tool-error" (the tool answered with an error; summary is its message).
  • {type = "done", job, text, usage = {inputTokens, outputTokens, cacheRead, costUSD}, turns}: the model’s final answer. inputTokens counts the uncached and newly cached input, cacheRead the input read from the cache, costUSD is what Claude Code reports for the job, or (api) the reported usage at the model’s price.
  • {type = "error", job, reason, message, category}: the job ended without an answer. reason: "mcp-unreachable" (Claude Code could not start Melange.exe or reach Oasis; the job stops before the model runs), "budget" ([AI] MaxBudgetUSD), "turns", "timeout" ([AI] TimeoutSec), "cancelled", "auth" (Claude Code is not logged in, or its key was refused), "rate-limit", "overloaded", "model" ([AI] Model is not a model this account can use, or the API refused the request), "refusal" (category is the API’s refusal category when it gave one), "network", "no-backend", "no-key" or "claude-exit" (any other failure; message has Claude Code’s own words). With the API backend, "auth" means the key was refused (it is kept: the player replaces it), "rate-limit" and "overloaded" come after one retry (a 429 waits for its retry-after), and the output limit (max_tokens) is retried once asking for a shorter answer before "turns".

Exactly one done or error ends each job. A tool the job calls sees ctx.caller == "lobby-prompt" and ctx.job (the job id as a string) in its handler (ctx.client is "mcp", or "ai" for the API backend’s in-process calls); an external Claude Code’s calls see "external".

The Steam lobby this machine is in, as client mods see it (Melange 0.12). Detect it with if wum.lobby then ... end.

Name Description
wum.lobby.state() nil outside a net session, else {lobby, me, owner, isHost, phase, members}: SteamIDs as strings; phase = "lobby", "loading", "match" or "results"; members = {{id, name, me, host, melange, peer}, ...} where melange is the member’s Melange version (nil without Melange) and peer is true when the member has the calling mod’s peer channel open.
wum.lobby.isHost() true when this machine owns the lobby; false outside a session.

Events (every listener): melange.lobby.enter {isHost}, melange.lobby.leave, melange.lobby.members (a member joined or left), melange.lobby.owner {owner, isHost} (the lobby changed hands), melange.lobby.phase {phase}.

Messages between copies of the same mod on the machines of one lobby (Melange 0.12), over Steam P2P channel 6, which the game never uses. A mod only ever talks to its own copies: a channel reaches only members that opened the same mod’s channel with the same version, and only once the game already has its own connection to that member, so Melange’s traffic is never the first between two machines. None of it touches the match, the game’s own channel or Wormsign.

Name Description
wum.peer.open{version = n} Opens this mod’s channel (one per mod) and advertises <mod id>@<version> to the lobby; returns a channel, or nil, reason.
wum.peer.now() A monotonic clock in milliseconds (a float), the clock of every timestamp below.

A channel ch:

Name Description
ch:send(id, tbl[, opts]) Sends a table (nil, booleans, numbers, strings up to 1024 bytes, tables up to 6 deep and 256 keys) to one member. opts.reliable (default true): reliable messages up to 8 KB, unreliable ones up to 900 bytes. Returns true, or false, reason: "size", "rate" (over 20 messages or 8 KB a second to that member), "no-peer" (the member has not opened this channel), "no-session" (no game connection to the member yet), "offline", "closed".
ch:broadcast(tbl[, opts]) Sends to every member that passes the same checks; returns how many.
ch:on(fn) fn(from, tbl, meta) for each message; meta = {reliable, at} with at the receive time in wum.peer.now() ms.
ch:onPeer(fn) fn(id, up) when a member becomes reachable on this channel (true) or stops being reachable (false).
ch:peers() The SteamIDs reachable now.
ch:clock(id) {offset, rtt, samples} for a member (offset = their clock minus mine, in ms), or nil before the first sample.
ch:setPresence(tbl) Publishes a small table (at most 256 bytes as JSON) as this machine’s lobby member data for the mod, visible to every member even before any connection exists; written at most every 2 s.
ch:presence(id) Another member’s presence table for this mod, or nil.
ch:close() Closes the channel (also on unload and reload).

Everything is reset when the lobby is left, when it changes hands and when a new lobby is joined. [PeerBus] Enabled=0 turns the channel off (wum.peer.open then returns nil, "unavailable").

The rules of a match (Melange 0.18): the host’s draft, what the lobby agreed on, what the match froze, and the registry of modes and match settings that all of it is checked against. The document format, validation codes and the lobby agreement are in rules.md; how a mod declares modes and match settings is in spice.md. A document is a table (or its JSON text); a result document is a table.

Reading is free. Writing needs permissions.rules = "edit" in spice.json (a call without it raises), and, while in an online lobby, only the lobby owner writes: a joiner gets false, "not-host". Failures are values, not errors: false, code[, detail] or nil, code[, detail]. The codes: conflict, not-host, invalid, not-ready (the registry is not built), io, not-in-lobby, not-found, exists, full, bad-name, undeclared. A list of problems is {{path, code, message, min?, max?, allowed?}, ...} with the codes of rules.md.

Name Description
wum.rules.registry() {modes, fields, mods}. modes: {id, title, blurb, scheme, mod, kind ("vanilla", "scheme" or "declared"), hasCard, card?, available, why?, featured = {{field, label?}}, lock = {field = value}, requires, settings, presets = {{id, label, values}}}. fields: the game style catalog, {name, type ("int", "bool", "enum", "strenum"), min, max, step, unit, group, label, help, earlyRead, editable, options?}. mods: {id, name, version, enabled, match, player} with the mod’s match settings and its (loaded) player settings. A setting is {key, type ("int", "bool", "enum"), default, min, max, step, unit?, options?, labels?, label, help?, group?, when?}. nil, "not-ready" before the registry exists.
wum.rules.draft() doc, rev: the host’s working document (nil when there is none) and its revision, which every accepted change raises by one.
wum.rules.setDraft(doc[, {baseRev = n}]) Validates doc and stores it as the draft: true, rev, hash16. With baseRev, the write is refused when the draft moved meanwhile: false, "conflict", {rev = current}; without it the last writer wins. false, "invalid", problems for a bad document, false, "not-host" for a joiner. In a lobby the owner’s draft is published to the other players while “use these rules” is on (wum.rules.active). Needs permissions.rules.
wum.rules.validate(doc) true, {}, resolved, hash16 or false, problems. No side effects.
wum.rules.resolve(doc) resolved, hash16, canonicalText, or nil, "invalid", problems. The resolved document holds every value (rules.md, “The resolved form”).
wum.rules.diff(a[, b]) changes, count, or nil, "invalid", problems. The values that differ going from a to b (without b: from a’s mode defaults to a), as {kind ("mode", "scheme", "weapon", "setting"), path, key, mod?, field?, from, to} in a fixed order (the mode, the game style fields, the weapons, then each mod’s settings); an absent value is nil.
wum.rules.explain(doc) A plain-text description, or nil, "invalid", problems: the mode, the number of changes from its defaults, and each change with its old value, in ASCII and a fixed order. The same document gives the same bytes on every machine, so a lobby can show it to everyone alike.
wum.rules.active([on]) The local “use these rules” switch (not saved; off at launch): offline a match freezes the draft while it is on, and in a lobby the owner publishes the draft while it is on. With an argument it sets the switch (needs permissions.rules); always returns the value.
wum.rules.isActive() The switch, read only.
wum.rules.lobby() The lobby’s agreement: {inLobby, owner, hash16, mode, modeTitle, changes?, doc?, ourAck, pending, holding, why, heldFrames, status, mismatches, members = {{id, name, self, owner, ack, applied}}}. ack is ok, err:<code>, none, vanilla, old or off. owner says whether this player is the lobby owner; holding and why say whether and why the owner’s start is held; status is the owner’s "", "drafting" or "proposed". Every player reads the owner’s document here, read only.
wum.rules.setStatus(status) The owner’s lobby status, "drafting", "proposed", or "" / nil to clear, which the other players’ lobby shows: true, false, "not-host", false, "not-in-lobby" or false, "invalid", message. Needs permissions.rules.
wum.rules.match() The frozen document of the match (read only), its hash16, and its source ("lobby", "draft" or "test"); nil when no rules are frozen.
wum.rules.setting(key) The calling mod’s match setting: the frozen value, else the declared default (an int is a Lua integer); nil, "undeclared" when the mod declares no such setting. For HUDs; the sim reads wum.sim.setting.
wum.rules.schema() The JSON Schema (draft 2020-12) of the authoring form for this machine’s registry, as text.
wum.rules.frontendScheme() The game style key the vanilla menu has picked (FE.Scheme.Standard), or nil.
wum.rules.weapons([modeId]) The 58 weapon entries of a game style, in the rules document’s order, and the mode id whose style gave base (the argument; else the draft’s mode; else vanilla/FE.Scheme.Standard; nil before the registry is built). A row: key ("Bazooka", the rules document’s name), id (the engine’s weapon number), kind ("weapon" | "utility" | "mystery"), cell (weapons panel cell row * 6 + col, 0..41; nil for an item only crates give), container ("kWeaponBazooka"), name (what the game shows now: an enabled mod’s weaponText rename, else the game’s text), vanillaName, help (the help lines joined with newlines), tags (a list of melee, airstrike, explosive, thrown, ballistic, fire, animal, utility, movement), hasIcon (it has a panel icon), clones (the clones that share this weapon’s values: {name, title, mod, cell, ownIcon}), base = {ammo, crate, delay} (the style’s values; absent when unknown), and when they apply renamedBy / iconBy (the mod whose weaponText / weaponIcons changes it) and takenBy (a clone that takes its panel cell). The text is read once per launch. Unknown modeId raises.
wum.rules.cardTexture(modeId) A texture id of the calling mod for a mode’s card (a PNG of at most 512x256 in the declaring mod’s folder), for wum.draw.hudImage and friends; or nil, reason (unknown mode, no card, missing or too large). Loaded once per mod generation and counted in its 256 textures.
wum.rules.presets.list() The presets in <[Rules] Dir>\presets, by slug: {slug, name, mode, changes?, modified, bytes, valid, errors?}. A file that fails validation here is listed with valid = false and its errors. At most 200.
wum.rules.presets.load(slug) doc, name, nil, "not-found", or nil, "invalid", problems.
wum.rules.presets.save(name, doc[, overwrite]) true, slug, or false, code[, problems] (exists without overwrite, full at 200 presets, bad-name, invalid, io). The slug is the name in lowercase letters and digits joined by -, at most 48 characters. Needs permissions.rules.
wum.rules.presets.delete(slug) true, or false, code. Needs permissions.rules.
wum.rules.presets.rename(slug, newName) true, newSlug, or false, code. Needs permissions.rules.

A preset is the authoring document in <slug>.json (canonical JSON, with its name in name); saving never leaves a temporary file behind.

The event melange.rules (wum.events.on): {type = "draft", rev} when the draft changed (by this mod, another mod or the Oasis RPC); {type = "external", source, rev} after an Oasis rules.set (the harness and the MCP; source says who); {type = "lobby", inLobby, hash16, status, ourAck} when the lobby’s document, a member’s ack or the status changed; {type = "hold", holding, why} when the owner’s start hold changed; {type = "applied", ok, hash16, mode, round} after each match VM got its rules; and {type = "mismatch", count} when the host found a machine that applied something else. The state is checked a few times a second while some mod listens; the first check only records it.

The match’s tick clock and state hash. A tick is one 20 ms step of the game’s simulation (50 per second); its hash covers the logic RNG, the turn, the worms, the scheduled tasks, projectiles and teams, so two machines (or a match and its replay) that agree on a tick’s hash agree on the game state at that tick.

Name Description
wum.wormsign.tick() {tick, engine, mods} for the last completed tick: tick is a number, engine and mods are 16-digit hex strings (mods is "0000000000000000" when no mod contributes). nil outside a match or before the first tick.
wum.wormsign.library() An array of the recorded matches (newest first): {path, bytes, ticks, land, online, complete, pinned, flagged} per entry. Empty when [Wormsign] Record=0 or nothing has been recorded yet.
wum.wormsign.onDivergence(fn) Calls fn(payload, name) when a tick’s hash differs from another player’s (or from a recording being replayed); returns a handle for wum.events.off. payload is {source, tick, serial, comps, contrib, peer}: source is "peer" or "replay", comps an array of the engine parts that differ ("time+rng", "turn", "worms", "tasks", "projectiles", "teams"), contrib the first differing mod contributor or "", peer the other player’s SteamID as a string. The same payload is the client event wormsign.divergence.

mods covers every sim mod of the match. Sim scripts are not covered by this page, but two things feed mods from them:

Name (sim VM) Description
automatic, mod.<id>.env A digest of the mod’s globals and wum.sim.storage, three tables deep and independent of key order. Numbers count by their stored bits, strings and booleans by value, functions, userdata and deeper tables by type only. [Wormsign] EnvDigest chooses when it runs: changed (default, after the mod’s code ran), always or off.
wum.sim.hash(v, ...), mod.<id>.hash Adds numbers (their stored bits), strings, booleans or nil to this tick’s hash; any other type raises an error. For state kept in locals, which the digest cannot see.

C++ modules add their own contributors with melange::wormsign::AddContributor (melange/wormsign.h). A contributor that takes over 20 µs at the 95th percentile over 500 ticks is logged once as slow and keeps being hashed every tick (a contributor hashed on some ticks only would make the mods hash depend on the machine’s speed; see wormsign.md, “For modules”).

C++ modules can add namespaces with melange::lua::AddLibrary("name", open) (melange/lua.h). They appear as wum.<name> in environments created afterwards. melange::lua::CurrentMod() tells a library function which mod is calling it.