` only works in the skin's `setup` and in its handlers during a play `` | The call is made at the top level or from an event outside a play. |
| `` `images` declares N images; the limit is 64 `` and `image "" must be a .png file` | A bad `images` list in `defineSkin`. |
| `the skin already uses the id …` | The `id` is also a mod's. |
| `` the skin has no `defineSkin` declaration `` | `skin.ts` never called `defineSkin`. |
A mistake the type checker catches before the game does, because `hitLightOn` has only two values:
```ts error=TS2322
playfield.set({ hitLightOn: "holds" });
```
## Managing skins {#managing}
The Skins page (Esc menu) lists skins with preview, name, version, author, the skin in use and its problems. Its buttons: Use, Export, Delete (to the recycle bin), Import, Open folder, Reload. Changing the skin restarts the mod host (outside a play) and applies from the next launch. The files of a skin are re-read at every map launch, so a change shows after the next launch without a reload; Reload only refreshes the list.
- The `skin` setting holds the folder name (`default` by default). An invalid name becomes `default`; a missing folder is reported and the first available skin is used. `prism.exe --skin ` picks any skin, for a benchmark or a smoke test.
- **Delete** removes a skin of the player's folder and its `skinConfig[]`. It never removes a skin shipped with the game, nor the skin in use, nor during a play.
- **Export** writes `.zip`, without hidden files. Every other file must be `.ts`, `.png`, `.ttf`, `.otf`, `.wav`, `.ogg`, `.flac` or `.mp3`.
- **Import** installs a `.zip` as a new folder and never replaces an existing skin: the folder name comes from the root folder of the archive, with `-2`, `-3`… added if needed. The whole archive is checked before anything is written; see the [skin package format](https://prism.am/dev/md/formats/skin-package.md).
- **Safe mode** plays `default` with no player configuration and no map script.
- The Actions menu also offers *Convert an osu! skin*, see [importing an osu! skin](https://prism.am/dev/md/guides/skin-import.md).
## Pitfalls {#pitfalls}
- Calling `playfield.set` at the top level, outside `setup`: it throws.
- A handler that names an image `setup` and `images` do not know.
- Moving things on every `game.tick`: 30 ms per call is a hard budget, and three overruns disable the script. Start a transition instead.
- Expecting a `holds` value for `hitLightOn`: there are `all` and `off` only.
- Giving the skin a different `id` and folder name: the player's configuration and the skin selection follow the folder name.
- Putting a `.zip` in the skins folder: it is not a skin until imported.
- Forgetting that the player's layer wins: if a value you set seems ignored, the player may have set it in the editor, within other bounds than yours.
## See also {#see-also}
- [Field reference](https://prism.am/dev/md/reference/skin-fields.md): every playfield field.
- [Map scripts](https://prism.am/dev/md/guides/map-scripts.md): the layer between the skin and the player.
- [HUD elements](https://prism.am/dev/md/guides/hud-element.md) and [element settings](https://prism.am/dev/md/guides/elements-settings-storage.md): the HUD part of a skin.
- [Native drawing](https://prism.am/dev/md/guides/stage-drawing.md): `stage.*`.
- [Importing an osu! skin](https://prism.am/dev/md/guides/skin-import.md).
- [The SDK reference](https://prism.am/dev/md/reference/sdk/game.md): `playfield.set`, `playfield.update`, `lanes.set` and the events.
=====
Page: Writing a map script
Address: https://prism.am/dev/guides/map-scripts/
Derived from: docs/map-scripts.md, crates/modding/src/chart.rs, crates/modding/src/play.rs, crates/modding/src/manifest.rs, crates/modding/src/api.rs, crates/skin/src/spec.rs, apps/desktop/src/app/playback.rs
# Writing a map script
A script that sits next to a chart and animates its playfield while it plays, like an ITG modchart, with the files, the declaration, transitions, images, budgets and errors.
A map script is a TypeScript file that belongs to one map. While the map plays, it moves the playfield, turns it, scales it, shifts its lanes and changes its colors and images to the rhythm of the song, like the modcharts of ITG. A map without a script keeps the playfield of the skin.
A map script is not a [mod](https://prism.am/dev/md/concepts.md), which the player installs for every play, and not a [skin](https://prism.am/dev/md/guides/skin.md), which describes the base look of the playfield. It is a third **layer** on top of the skin. Everything it does is visual: judging and score never depend on it, and a replay records only its fingerprint, see [replays](#replays).
## A complete script {#example}
`first-light` sways the playfield from one side to the other, leaning into each swing, one swing every two measures. The lanes glow on every beat, the downbeat brightest. Every move is a transition the game animates from the song clock; the script runs once per beat.
```ts
///
// First light, an example map script: the playfield sways from side to side, leaning
// into each swing, one swing every two measures, and the lanes glow on every beat, the
// downbeat brightest. Copy it next to a chart as `script.ts` (every difficulty of the
// folder) or as `.script.ts` (that difficulty only).
//
// Every move is a transition the game animates itself from the song clock: the script
// only runs once per beat.
/** Swing to each side, in fractions of the screen width. */
const SWAY = 0.1;
/** Lean at the end of a swing, in degrees clockwise. */
const LEAN = 7;
/** Measures one swing lasts. */
const SWING_MEASURES = 2;
/** Lane color between beats, and its glow on the downbeat and on the other beats. */
const LANE = "#454d61";
const DOWNBEAT = "#a67cff";
const BEAT = "#7486b8";
/** Meter of the timing point in effect at `timeUs`; 4 before the first one. */
function meterAt(timing: TimingPoint[], timeUs: number): number {
let meter = 4;
for (const point of timing) {
if (point.timeUs > timeUs) break;
meter = point.meter;
}
return meter;
}
export default defineChart({
apiVersion: 2,
setup(play: PlayContext) {
playfield.set({ laneColor: LANE });
let side = 1;
let downbeats = 0;
ctx.on("game.beat", (beat: Beat) => {
const beatMs = 60000 / beat.bpm;
const downbeat = beat.meterBeat === 0;
if (downbeat && downbeats++ % SWING_MEASURES === 0) {
side = -side;
const swingMs = SWING_MEASURES * meterAt(play.song.timing, beat.timeUs) * beatMs;
playfield.update({
patch: { x: 0.5 + side * SWAY, rotation: side * LEAN },
transitionMs: Math.min(10000, swingMs),
easing: "easeInOut",
});
}
// A glow at once, then back by the next beat: two paces, two transitions.
playfield.update({ patch: { laneColor: downbeat ? DOWNBEAT : BEAT } });
playfield.update({ patch: { laneColor: LANE }, transitionMs: 0.9 * beatMs, easing: "easeIn" });
});
},
});
```
A second script, `lane-wave`, bobs the lanes in opposite directions on every beat and flashes an image behind them on every downbeat. It ships with its image, next to it:
```ts
///
// Lane wave, an example map script: on every beat the lanes bob up and down, neighbours in
// opposite directions, and a soft light (`flash.png`, a PNG next to the script) rises behind the
// lanes on each downbeat and fades over two beats. Copy this folder next to a chart (the PNG
// goes with the script).
//
// `flash.png` is named in `setup`, so it is loaded before the play; a handler could only use
// an image that `images` declares as well.
/** How far a lane moves, in screen heights. */
const BOB = 0.02;
const LIGHT = "#ffffff70";
const DARK = "#ffffff00";
export default defineChart({
apiVersion: 2,
images: ["flash.png"],
setup(play: PlayContext) {
playfield.set({ backgroundImage: "flash.png", backgroundColor: DARK });
ctx.on("game.beat", (beat: Beat) => {
const beatMs = 60000 / beat.bpm;
for (let column = 0; column < play.columns; column++) {
const up = (beat.index + column) % 2 === 0;
lanes.set({ column, lane: { offsetY: up ? -BOB : BOB }, transitionMs: 0.9 * beatMs, easing: "easeInOut" });
}
if (beat.meterBeat === 0) {
playfield.update({ patch: { backgroundColor: LIGHT } });
playfield.update({ patch: { backgroundColor: DARK }, transitionMs: 2 * beatMs, easing: "easeOut" });
}
});
},
});
```
To try either, copy the script into the folder of a map, named `script.ts`, and play. No restart and no build: the file is read at every launch.
## Files {#files}
In the folder of a map, next to its charts and its audio:
| File | Used for |
| --- | --- |
| `script.ts` | Every difficulty of the folder. |
| `.script.ts` | That difficulty only. It wins over `script.ts`: `Artist - Title [Hard].script.ts` next to `Artist - Title [Hard].osu`. |
The file is read again at every map launch. It must be UTF-8 text of at most 1 MiB; otherwise the launch reports ` exceeds 1048576 bytes` or ` is not UTF-8 text`. Its images are the PNG files of the same folder.
The player can turn every map script off: Settings, Game, *Allow map scripts* (`allowMapScripts`, on by default, enforced in Rust). When it is off, no script is read and the map plays with the skin alone. **Safe mode** also never runs a map script.
## defineChart {#define-chart}
```dts
declare function defineChart(input: ChartDefinition): ChartManifest;
```
| Field | Rule |
| --- | --- |
| `apiVersion` | Required. Must be the game's, `2`: `the map script requires modding API version X; this game provides version 2`. |
| `permissions` | Optional. `["stage"]` for [native drawing](https://prism.am/dev/md/guides/stage-drawing.md). |
| `images` | Optional. PNG files of the map folder that handlers put on the playfield during the play, at most 64, besides those `setup` names. |
| `setup` | Optional. `setup(play: PlayContext)`. |
A map script has no `id`: it is the map's. Call `defineChart` exactly once, at the top level of the file, as the default export. Calling it twice, or inside a function, throws `defineChart must be called exactly once` or `defineChart can only be called at the top level of the map script`, and a file that never calls it fails with ``the map script must declare itself with `export default defineChart({ … })` at its top level``.
`setup` receives the same `PlayContext` as the `setup` of a skin: mode, layout, number of columns, window size, the song, the judgement tiers. Name its parameter `play`, not `ctx`, which would hide `ctx.on`.
The script runs in the same engine as the skin and the mods, on the `mods` thread, loaded fresh at every launch, **after** the skin. It can use:
- `playfield.set`, `playfield.update` and `lanes.set`: the calls of skins, with the same fields, bounds and transitions (see the [skin guide](https://prism.am/dev/md/guides/skin.md#during-play) and the [field reference](https://prism.am/dev/md/reference/skin-fields.md));
- `game.song()` (with `timing`, the tempo points), `game.notes(…)`, `game.player()`, `game.judgements()`, `game.playfield()`, `game.settings()`, and `log.info` / `log.warn`;
- the game events, with `ctx.on`: `game.songStart`, `game.beat`, `game.tick`, `game.judgement`, `game.pause`, `game.resume`, `game.songEnd`, `game.playfieldChange`, `game.settingsChange` (the [events reference](https://prism.am/dev/md/reference/sdk/events.md) lists them all).
It has no HUD and no storage: `hud.*` and `storage.*` throw `` `` is not available to map scripts: they only change the playfield ``. It has no network and no file but the images of its folder, decoded before the play. Calling `playfield.set` from a mod throws `` `playfield.set` is only available to skins and map scripts ``.
With `permissions: ["stage"]` the script also draws in the native renderer with `stage.*` (see [native drawing](https://prism.am/dev/md/guides/stage-drawing.md)): the elements placed on the playfield follow its moves, rotations and zooms. Its sprites and emitters can only name images declared in `defineChart({ images })`. Without the permission every `stage.*` call throws. Turning *Allow map scripts* off also removes this drawing, since the script is not read.
## What the script changes {#layer}
The script describes one **layer** of the playfield, drawn over the skin's. Every value it gives wins over the skin's for as long as it gives it; the others stay the skin's. For one lane, the chain is: the lane of the script (`lanes[i]`), the script's common values, the lane of the skin, the skin's common values, then the engine's default. A `laneWidth` given by the script wins over the skin's total `width`.
Above both sits the player's own configuration, which can override the script too. The three layers, their order and their different bounds are in the [skin guide](https://prism.am/dev/md/guides/skin.md#layers).
Every playfield field is available. Three serve effects best:
| Field | Bounds | Default | Does |
| --- | --- | --- | --- |
| `rotation` | −3600 to 3600 | 0 | Rotates the whole playfield around the centre of the lanes box, in degrees clockwise. The notes follow their lanes. |
| `zoom` | 0 to 4 | 1 | Scales the whole playfield around the same centre. |
| `lanes[i].offsetX` | −2 to 2 | 0 | Shifts one lane (background, receptor, notes, holds) sideways, in screen heights, to the right when positive. `offsetY` does the same vertically. |
The renderer applies them in the shader: each quad turns around its own centre, placed where the rotation and scale of the playfield put it. The `game.playfield()` entity that mods read stays the layout of the launch: lane shifts included, rotation and zoom not.
## Transitions {#transitions}
`playfield.update({ patch, transitionMs, easing })` and `lanes.set({ column, lane, transitionMs, easing })` change values at once or over time: `transitionMs` is 0 to 10000 and `easing` is `linear`, `easeIn`, `easeOut` or `easeInOut`. A value outside 0 to 10000 throws `transitionMs: is outside [0, 10000]`.
The render thread animates **each value separately**, from the song clock: a 100 ms flash of color does not cut off a 2 s sway started before, whether the two come from the script or from the skin. A pause freezes the transitions.
Changes of one handler (one step of the `mods` thread) with the same transition are merged; those with different transitions stay apart and apply in order. So you can light a color and bring it back in the same handler:
```ts fragment
playfield.update({ patch: { laneColor: "#8a5cf6" } });
playfield.update({ patch: { laneColor: "#454d61" }, transitionMs: 200, easing: "easeOut" });
```
Colors and numbers animate. Images, the anchor and the scroll direction change at once.
## Tempo and time {#tempo}
- `play.song.timing` (and `game.song()?.timing`): the chart's tempo points, sorted, `{ timeUs, bpm, beatUs, meter }`, at most 1024.
- `game.beat`: `{ index, timeUs, bpm, meterBeat }` on every beat, at its exact time on the song clock, not rounded to ticks. `index` counts beats from the first tempo point, `meterBeat` is 0 on the first beat of a measure. Beats only arrive while the clock advances; after a pause, the next one resumes.
- `game.tick`: the song time, at the tick rate of the `mods` thread (30 Hz).
A good script starts transitions on beats and lets the renderer animate them, so that it runs only a few times per second. Times are in microseconds (`timeUs`) except where a field says milliseconds.
## Images {#images}
The images of a script are PNG files of **its** folder: those `setup` names (`backgroundImage: "flash.png"`) and those `defineChart({ images })` declares. All are decoded before the play, with the limits of skins: 4 MiB, 2048 px per side, reduced to 640 px, at most 256 images for the layer. A declared image that is missing or not a PNG makes the script fail. During the play, a change that names an image that was not loaded throws. An image of the script that does not fit in the atlas leaves the skin's image in its place.
## Budgets and errors {#errors}
A map script is treated like a downloaded mod: 30 ms of execution per call (loading, `setup`, each handler), 16 MiB of QuickJS memory, and it is disabled after 3 overruns or 3 errors in a row.
| What happens | Result |
| --- | --- |
| Unreadable file, `defineChart` missing or invalid, `apiVersion` different, declared image missing, `setup` throws or is over budget | The error is reported (launch banner, mods log) and the map plays with the skin alone. |
| The script is disabled during the play | Its layer disappears and the skin's playfield stays. |
| Value out of bounds or invalid in `setup` | Brought into the bounds or replaced by the skin's value, and reported, as for a skin. |
| The same mistake in a handler during the play | The call throws in your script (`: is outside [min, max]`, `lane N does not exist: there are at most 32 lanes`, and the others listed in the [skin guide](https://prism.am/dev/md/guides/skin.md#errors)). |
| No answer from the `mods` thread in 1 s | The map starts with the engine's default look and no script. |
To see a script run as in a real play, use `prism.exe --bench-gameplay 10 --map `: it prints `PRISM_BENCH map script: …` with the path, the state, the fingerprint and the problems. `prism.exe --smoke-test` does the same, as `PRISM_SMOKE map script: …`, for the map selected at startup.
## Replays {#replays}
A replay records `mapScript`: the BLAKE3 fingerprint (hexadecimal) of the source of the script that drew the play, `null` when there was none or it could not start. Judging does not depend on the script, so a replay plays back identically with or without it.
## Loading without slowing the game {#loading}
```text
map launch (main thread)
└─ context of the play; chart allowed if the setting permits
└─ helper thread
the map script: .script.ts, else script.ts
two queues of changes: skin and script (skin::patch_channel)
prepare_play ──> mod thread: skin.ts loaded fresh, setup(play),
then the script loaded fresh, setup(play);
reply: the two PlayfieldSpec
skin::prepare(skin layer, script layer, mods' stage images):
validation, PNG decoding, one atlas
└─ main thread: the prepared playfield, then the start
render thread: one texture upload before the first frame;
each frame: changes from both layers, transitions, drawing
```
Nothing is allocated for a frame that has no change.
## Pitfalls {#pitfalls}
- Naming the `setup` parameter `ctx`: it hides the global `ctx.on`.
- Moving the playfield on every `game.tick`: each call costs against the 30 ms budget. Start a transition on a beat instead.
- Using an image in a handler without declaring it in `images`: it was not loaded.
- Using `hud.*` or `storage.*`: they throw in a map script.
- Expecting your values to be the last word: the player's configuration wins, and a player who set `rotation` in the editor keeps it.
- Relying on the script for anything but looks: it can be switched off, and then judging and score are the same.
## See also {#see-also}
- [Writing a skin](https://prism.am/dev/md/guides/skin.md): the layer below, and the shared calls.
- [Field reference](https://prism.am/dev/md/reference/skin-fields.md): every value a script can set.
- [The SDK, game and playfield](https://prism.am/dev/md/reference/sdk/game.md) and [events](https://prism.am/dev/md/reference/sdk/events.md).
- [Your first map script](https://prism.am/dev/md/first-map-script.md).
=====
Page: Importing an osu! skin
Address: https://prism.am/dev/guides/skin-import/
Derived from: docs/convertisseur-skin-osu.md, crates/skin_import/src/lib.rs, crates/skin_import/src/source.rs, crates/skin_import/src/stage.rs, crates/skin_import/src/images.rs, crates/modding/src/importers.rs, crates/modding/src/api.rs, content/mods/skin-converter/main.ts, content/mods/skin-converter/convert.ts
# Importing an osu! skin
How the osu!mania skin converter works, the skinImport API that mods use to build an importer, the permission it needs and the limits the game enforces.
Prism converts an osu!mania skin into an ordinary Prism skin. The player picks a skin folder or an `.osk` file on the Skins page, a card shows what will be converted and what Prism cannot do, and *Create the skin* writes a normal folder under the player's skins, ready to use, edit by hand, customize in the [skin editor](https://prism.am/dev/md/guides/skin.md#player-config) and export.
The converter is a mod, `content/mods/skin-converter` (`pvng.skin-converter`). It is a plain folder written in TypeScript; deleting it removes the feature, and the skins it made stay. The game gives mods the `skinImport` API so that anyone can write another importer. This page explains both.
## Who does what {#roles}
The work is split on purpose:
- **The mod** decides the *meaning*: which `skin.ini` key feeds which Prism value, which picture goes in which slot for each number of keys, which warnings to show. It writes the texts of its card in the languages of the interface (`en`, `fr`, `zh`, `ko`).
- **The game**, natively and outside the mod thread, does what a script cannot: read the folder or the archive, parse `skin.ini`, decode and transform pictures, write the skin folder. The script never receives a byte: only typed, bounded values.
The mod does not supply code either: it describes a skin (`SkinDescription`, values only), and the game validates it with the rules of every skin, then generates a readable `skin.ts` of the same shape as `content/skins/default/skin.ts`. A `skin.ts` written by a mod would be code run later with a skin's rights.
## The permission {#permission}
The API needs `permissions: ["skinImport"]` in `defineMod`. The permission is shown on the Mods page and goes away when the mod is disabled. It is for mods only: a skin or a map script cannot use it (`only mods convert skins, not a skin`). Without it, every call throws:
```text
`skinImport` needs the `skinImport` permission: declare `permissions: ["skinImport"]`
```
## The API {#api}
| Call | Does |
| --- | --- |
| `skinImport.register(declaration)` | Declares an importer: one button in the Actions menu of the Skins page. Only in the mod's `setup` (`` `skinImport.register` is only available in a mod's setup ``), at most 4 per mod. |
| `skinImport.panel(panel)` | Shows or updates the card of the Skins page (declarative, see [the panel](#panel)). |
| `skinImport.stage({ sourceId, skin, images })` | Asks the game to prepare the pictures of the skin, in memory. Returns a request number, or `null` when the game is busy. The answer is `skinImport.staged`. |
| `skinImport.create({ stageId })` | Asks the game to write the prepared skin as a new folder. Returns a request number or `null`. The answer is `skinImport.created`. |
| `skinImport.close()` | Removes the card and frees the source and the preparation. |
And four events:
| Event | Payload | When |
| --- | --- | --- |
| `skinImport.opened` | `{ importerId, locale, source?, error? }` | The player picked a source and the game read it. `source` is a `SkinSource`; `locale` is the interface language. |
| `skinImport.staged` | `{ requestId, stageId?, report?, error? }` | The pictures were prepared. `report` lists the files and sizes. |
| `skinImport.created` | `{ requestId, id?, error? }` | The folder was written. `id` is its name, which may differ from the wanted one (`-2`, `-3`). |
| `skinImport.action` | `{ id }` | The player pressed a button of the card. The id `dismiss` means the card was closed. |
Types and the exact signatures are in the [SDK reference](https://prism.am/dev/md/reference/sdk/downloads.md#skinimport-register) and in [modding.d.ts](https://prism.am/dev/sdk/modding.d.ts).
The game makes the decisions that matter for safety:
1. **The player picks the source, never the mod.** A click on the importer's button sends the pick to the game, which opens the native file dialog, reads the source and sends `skinImport.opened`. The mod sees no path and no file name but the label of the source.
2. **Read-only and bounded.** See [the limits](#limits).
3. **`skin.ini` is parsed natively** into a typed structure (`SkinIni`: `[General]`, the `[Mania]` sections merged by `Keys`, columns by index, colors as `#rrggbbaa`, unknown keys listed without their values). Values out of bounds are rejected with a message, never passed on.
4. **The inventory of pictures** (`SourceImage`, at most 4096) gives the normalized name (no extension, no `@2x`, no `-N`), size, scale (1 or 2), number of animation frames, byte size, whether it is blank, the box of its visible pixels and its peak color. No pixel.
5. **Picture operations are declarative** (`ImageOp`) and run by the game: `source` (an element name resolved like osu! does: animation, `@2x`, `.png` or `.jpg`), `dest` (a relative `.png` path, with `{n}` for a sequence), `animation`, `frame`, `crop`, then `fit` (fits in a box without enlarging) or `stretch` (exact size). The output is PNG. There is no pixel script and no network.
6. **A skin is described, the game writes it.** The description holds the common `PlayfieldSpec`, a layout per number of keys (`keys`, a `PlayfieldSpec` and a `LaneSpec` per column) and the vertical positions of the HUD. The game checks it with the rules of skins (bounds, paths, images present).
7. **Safe writing.** Only in the player's skins folder (`PRISM_SKINS_DIR` respected, never the shipped folder), through a hidden preparation folder then a rename, under a free id (`-2`, `-3`), so an existing skin is never overwritten. Before the rename, the generated `skin.ts` is loaded in a throwaway engine, as the skin list does.
8. **One job at a time**, on a dedicated native thread (`skin-import`), never during a play. Results come back as events, on the mod's usual budget.
## A minimal importer {#example}
This mod converts the 4K layout only: it keeps the width of the first column and the first note picture. The converter in the game does the same work for 4K to 9K with many more values.
```ts
///
// Mini skin importer, an example mod: the smallest converter of an osu!mania skin. The player
// picks a folder or an `.osk` file on the Skins page; the game reads it and hands this mod its
// `skin.ini` and its list of pictures as plain values; the mod describes the Prism skin it wants
// (a 4K layout with the width of the first column and its note picture), asks the game to prepare
// it, then to write it. The mod never sees a file or a pixel, and never writes code: the game
// generates the `skin.ts` from the description.
//
// Needs the `skinImport` permission, shown on the Mods page.
/** osu! measures in points of a screen 480 high; Prism in fractions of the screen height. */
const OSU_HEIGHT = 480;
const KEYS = 4;
let requestId: number | null = null;
let stageId: number | null = null;
function show(status: PanelStatus, title: string, detail: string, actions: PanelAction[] = []) {
skinImport.panel({ title, status, detail, actions });
}
/** The skin to build and the pictures to prepare, or why there is nothing to convert. */
function describe(source: SkinSource): StageRequest | string {
const section = source.ini?.mania.find((candidate) => candidate.keys === KEYS);
if (!section) return `The skin has no [Mania] section for ${KEYS} keys.`;
const reference = section.columns[0]?.noteImage ?? "mania-note1";
const picture = source.images.find((image) => image.name === reference);
const laneWidth = (section.columnWidth[0] ?? 30) / OSU_HEIGHT;
const playfield: PlayfieldSpec = { laneWidth, laneGap: 0 };
const images: ImageOp[] = [];
if (picture) {
playfield.note = "note.png";
playfield.noteSize = { width: laneWidth, height: laneWidth };
images.push({ source: reference, dest: "note.png", fit: { maxWidth: 256, maxHeight: 256 } });
}
return {
sourceId: source.sourceId,
skin: {
id: "mini-import",
name: (source.ini?.general.name || source.label || "Imported skin").slice(0, 64),
author: source.ini?.general.author,
layouts: [{ keys: KEYS, playfield, lanes: [] }],
},
images,
};
}
export default defineMod({
id: "example.skin-importer",
name: "Mini skin importer",
version: "1.0.0",
apiVersion: 2,
permissions: ["skinImport"],
setup() {
// Only in `setup`: one button of the Skins page, in the Actions menu.
skinImport.register({
id: "mini",
name: "Convert an osu! skin (mini)",
description: "Keeps the 4K column width and the first note picture.",
sources: ["folder", "archive"],
});
// The player picked a source and the game read it.
ctx.on("skinImport.opened", (event: SkinImportOpened) => {
requestId = null;
stageId = null;
if (!event.source) {
show("error", "Could not read the skin", event.error ?? "Unknown error");
return;
}
const request = describe(event.source);
if (typeof request === "string") {
show("error", "Nothing to convert", request);
return;
}
requestId = skinImport.stage(request);
if (requestId === null) show("error", "The game is busy", "Try again in a moment.");
else show("working", "Preparing", "Preparing the pictures…");
});
// The pictures were prepared: report what will be written and ask the player.
ctx.on("skinImport.staged", (event: SkinImportStaged) => {
if (event.requestId !== requestId) return;
if (event.stageId == null || !event.report) {
show("error", "Could not prepare the skin", event.error ?? "Unknown error");
return;
}
stageId = event.stageId;
const kib = Math.round(event.report.totalBytes / 1024);
show("ready", "Ready", `${event.report.files.length} files, ${kib} KiB.`, [{ id: "create", label: "Create the skin", primary: true }]);
});
// A button of the panel (`dismiss` when the player closes it).
ctx.on("skinImport.action", (event: SkinImportAction) => {
if (event.id === "dismiss") {
requestId = null;
stageId = null;
} else if (event.id === "create" && stageId !== null) {
requestId = skinImport.create({ stageId });
show("working", "Creating", "Writing the skin folder…");
}
});
// The folder was written under its own free name, never over another skin.
ctx.on("skinImport.created", (event: SkinImportCreated) => {
if (event.requestId !== requestId) return;
if (event.id == null) show("error", "Could not create the skin", event.error ?? "Unknown error");
else show("done", "Done", `The skin ${event.id} is in your skins folder.`, [{ id: "edit", label: "Open in the skin editor", primary: true, editSkin: event.id }]);
});
},
});
```
The flow is always the same: `register` in `setup`, `opened` gives you the source, you describe the skin and call `stage`, `staged` tells you the sizes, you show a card with a *create* button, `action` brings the click, you call `create`, and `created` gives the name of the new skin. A request number tells your handlers which answer belongs to which call.
## The card {#panel}
`skinImport.panel` takes a declarative description, shown in a modal of the Skins page. The page invents no text, no icon and no color: everything comes from the card, as text (never as HTML). The visual fields are optional and checked in Rust.
| Field | Content |
| --- | --- |
| `title`, `status` | The title and `working`, `ready`, `done` or `error`. `detail` and `icon` are optional. |
| `badges` | Colored pills under the title: `{ text, tone, icon? }`, at most 16. `tone` is `ok`, `warn`, `bad` or `info`. |
| `tiles` | Big figures: `{ label, value, icon?, tone?, meter?, hint? }`, at most 6. `meter { value, max }` adds a gauge, green up to three quarters, amber after, red at the limit unless `tone` is set. |
| `sections` | `{ heading, rows[{ label, value, icon?, tone?, parts? }] }`, at most 6 sections of at most 24 rows. `parts` (at most 8 chips of `{ text, icon? }`) shows the row as chips; `value` stays the full sentence for screen readers. |
| `notes` | `{ level, text, icon? }`, at most 48. `error` and `warning` stay visible with their icon; `info` is folded in a closed *Details* area. |
| `actions` | Buttons: `{ id, label, primary?, editSkin? }`, at most 4. `editSkin: ""` makes the page open the skin editor on that skin. |
An `icon` is a name from the closed list of the game (`PANEL_ICONS`: lucide icons such as `check`, `image-off`, `scaling`, `gauge`, `circle-x`), and another name refuses the card. The *pick a folder*, *pick an .osk file* and *Close* buttons belong to the page and are translated by the interface; the importer's declaration takes `name` (1 to 64 characters) and `description` (0 to 256) and an optional `localized` table for `en`, `fr`, `zh` and `ko`; its `id` is 1 to 32 characters among `a-z`, `0-9`, `-`, `_`, starting with a letter or digit.
## Limits {#limits}
Reading the source (`crates/skin_import`):
| Limit | Value |
| --- | --- |
| `.osk` archive | 512 MiB |
| Entries of an archive, or files visited in a folder | 8192 |
| One file read (a picture or `skin.ini`) | 64 MiB |
| Uncompressed total of the pictures and `skin.ini` | 1 GiB |
| Folder depth | 6 levels (links and junctions are ignored) |
| Path | 8 levels, 200 characters |
| `skin.ini` | 2 MiB, UTF-8 or UTF-16, `//` comments; at most 64 `[Mania]` blocks |
| Pictures listed | 4096 |
| Animation frames looked for | 64 |
| Size of a picture read | 40 megapixels, 65 535 px per side |
Writing the skin:
| Limit | Value |
| --- | --- |
| Layouts of a description | 8 |
| Pictures of a converted skin | 256 |
| Bytes of pictures of a converted skin | 16 MiB |
| One output picture | 4 MiB, 2048 px per side |
| Frames of one animation | 32 |
| Budget of a shipped skin | 900 KiB: **reported** (`budgetBytes`, `overBudget`) but not enforced; the mod decides whether to reduce |
| Name, author of a skin | 64 characters each; description 1024 |
A mod's calls keep the usual budget of 30 ms. At most 8 jobs wait in the queue; past that a request is refused as busy and the call returns `null`.
## The converter mod {#converter}
`pvng.skin-converter` converts every `Keys: 4` to `Keys: 9` section it finds into the layouts 4K to 9K of the game, with their own columns, widths and pictures. A key count with no section is not invented: the generated `skin.ts` uses the closest converted layout (the lowest on a tie) and repeats its columns. Sections 1K to 3K and 10K and above are not converted, and the card counts them. Without a usable `[Mania]` section the mod uses osu!'s documented default values and the card says so.
The rules are those of `content/skins/default/skin.ts`, which was converted by hand:
| osu! | Prism |
| --- | --- |
| Unit: a screen 480 points high | Sizes are points ÷ 480 (screen heights); `x` is 0.5. |
| `ColumnWidth` | `laneWidth` (and a `width` per lane when widths differ). |
| `ColumnSpacing` | `laneGap`: the gap moves lanes, it never narrows one. |
| `HitPosition` | `receptorY`: the bottom of the notes sits on the line. |
| `NoteImage{N}` | `note` of lane N; `noteSize` from the lane width and the picture's ratio. |
| `NoteImage{N}L`, `NoteImage{N}T` | `holdBody`, `holdEnd`, with `holdMatchNoteWidth: true`. |
| `KeyImage{N}`, `KeyImage{N}D` | `receptor`, `receptorPressed`, cropped to their visible part and centered on the receptor line. |
| `Colour{N}`, `ColourLight{N}` | `laneColor`, `stageLightColor`. |
| `StageLight` | `stageLight`, its edge on the hit position. |
| `LightingN`, `LightingL`, `LightFramePerSecond` | `hitLight`, `holdLight` (`{n}`, frames, fps) at `LightPosition`. |
| `JudgementLine`, `ColourBarline` | `judgementLine`, `measureLines`. |
| `ScorePosition`, `ComboPosition` | The `y` of the `judgement` and `combo` elements. |
| `@2x` images, `name-0…` animations | `@2x` is preferred; an animation becomes a `{n}` sequence (lights) or its middle picture (hold body). |
What Prism cannot do is listed on the card: a hold head different from the note (`NoteImage{N}H`), a `NoteBodyStyle` other than 0, animated notes and keys (one picture is kept), `StageLeft`, `StageRight` (left out, no border), `StageBottom` and `StageHint`, column lines, `SpecialStyle`, `SplitStages`, `SeparateScore`, `ColumnRight`, `WarningArrow`, judgement, combo and score pictures, fonts, sounds, the cursor and menu images. `UpsideDown` converts the positions and the scroll direction but no picture is flipped. `ColumnStart` is dropped. Uneven column widths are converted.
Over budget, the mod prepares the pictures again at 80 %, 60 % and 45 % of their size until the skin fits in 900 KiB, never changing a placement value, and the card says *pictures reduced*. Some values are not verified against osu! itself and are marked so in the mod: the defaults without `skin.ini`, the `UpsideDown` behavior and the placement of the hold end (`holdEndOffset` stays 0, adjust it in the skin editor).
The result is a folder like any other: `skin.ts`, PNG files and a preview. *Open in the skin editor* ends the card.
## Pitfalls {#pitfalls}
- Calling `skinImport.register` outside `setup`.
- Forgetting the request number: a late `staged` of an older source would build the wrong skin. Compare `event.requestId` with the one `stage` returned.
- Using a skin id that is not valid: the description is refused with the rules of every skin. The game finds a free folder name, not a valid id.
- Expecting a skin to be overwritten: it never is.
- Writing a converter that takes the source itself: the mod never gets a path, only `SkinSource`.
## See also {#see-also}
- [Writing a skin](https://prism.am/dev/md/guides/skin.md): what the generated skin is and how to edit it.
- [Field reference](https://prism.am/dev/md/reference/skin-fields.md): the values a description can set.
- [Skin package format](https://prism.am/dev/md/formats/skin-package.md): the shape of a skin folder and its archive.
- [Writing a mod](https://prism.am/dev/md/concepts.md): permissions and the mod folder.
=====
Page: Write a judgement set
Address: https://prism.am/dev/guides/judgement-set/
Derived from: crates/modding/src/judgement.rs, crates/modding/src/runtime.rs, crates/core/src/judgement/mod.rs, crates/core/src/rating.rs, content/mods/prism/main.ts, content/mods/osu/main.ts, content/mods/etterna/main.ts, content/examples/mods/judgement-pack/main.ts, content/examples/mods/judgement-colors/main.ts, docs/judgement.md
# Write a judgement set
Register judgement sets with judgements.register: tiers, asymmetric windows in ms, weights, combo breaks, colours and gradients, parameters, the rules the game validates, the built-in sets and how the player picks one.
A judgement set decides how a press is graded: which tiers exist (Perfect, Great, Miss…), how wide each window is, how much a tier is worth and whether it breaks the combo. The game ships three sets and every one of them is an ordinary mod. A mod that only registers sets is a **judgement pack**: installed, its sets appear in the game's pickers without a restart.
A set only **describes** its tiers. The game judges natively: the accuracy formula and the hold rules are chosen by name (`accuracy`, `holds`) among the rules built into the game, and Rust validates everything your script returns. You never grade a press in TypeScript. This page assumes you have made [a first mod](https://prism.am/dev/md/first-mod.md).
## A first set {#first-set}
This mod registers two sets. "Tight" has a parameter, `width`, that scales every window, and asymmetric windows. "Smooth" has no parameter, uses the native `continuous` accuracy and gives its first tier a gradient.
```ts
///
// A judgement pack: two sets for the game's pickers (Settings → Game → Judgement, and the
// switch beside Play). A mod that only registers sets is shareable as is.
//
// "Tight" has one parameter, `width`, which scales every window, and asymmetric windows
// (`earlyMs` before the note, `lateMs` after it). "Smooth" has no parameter; its accuracy
// is the native `continuous` curve and its holds are judged head and tail separately.
export default defineMod({
id: "judgement-pack",
name: "Judgement Pack",
version: "1.0.0",
apiVersion: 2,
author: "You",
description: "Two judgement sets: a parametric one with asymmetric windows and a continuous one.",
setup() {
judgements.register({
id: "tight",
name: "Tight",
// The picker shows one slider per parameter. `short` prefixes the value where room
// is short ("W2"); without it the game writes the label and the value ("Width 2").
params: { width: { label: "Width", short: "W", min: 1, max: 3, step: 1, default: 2 } },
accuracy: "weights",
holds: "head",
// Called once per combination of parameters (here width = 1, 2, 3) right after
// `setup`: hit tiers from the tightest to the widest, then the miss.
tiers: ({ width }) => [
{ id: "perfect", name: "Perfect", color: "#7fffd4", earlyMs: 6 * width, lateMs: 8 * width, weight: 1 },
{ id: "good", name: "Good", color: "#ffe38a", earlyMs: 14 * width, lateMs: 18 * width, weight: 0.6 },
{ id: "bad", name: "Bad", color: "#ff9f6e", earlyMs: 24 * width, lateMs: 30 * width, weight: 0.2, breaksCombo: true },
// The miss window is the farthest press that still takes (and misses) a note.
{ id: "miss", name: "Miss", color: "#ff5a5a", windowMs: 30 * width, weight: 0 },
],
});
judgements.register({
id: "smooth",
name: "Smooth",
accuracy: "continuous",
holds: "separate",
tiers: () => [
{
id: "prism",
name: "Prism",
color: "#f3f0ff",
// 2 to 8 colours the text shows at once; `color` stays the plain fallback.
gradient: ["#ff8fcb", "#ffca80", "#91efad", "#8cddff"],
windowMs: 8,
weight: 1,
},
{ id: "great", name: "Great", color: "#93e69b", windowMs: 40, weight: 0.7 },
{ id: "ok", name: "Ok", color: "#89afff", windowMs: 90, weight: 0.2, breaksCombo: true },
{ id: "miss", name: "Miss", color: "#ff7185", windowMs: 130, weight: -1, breaksCombo: true },
],
});
},
});
```
Copy the folder `judgement-pack` into your mods folder (Mods page, *Open folder*). Then open **Settings → Game → Judgement**: both sets are listed under the mod's name, "Tight" with a slider for `Width`. The rest of this page explains each part.
## The declaration {#declaration}
`judgements.register` is called from `setup`, and nowhere else: registering closes once the mods have loaded (the call then throws `judgements.register is only available in a mod's setup, while the mods load`). Only mods register sets, not skins or map scripts. A mod registers at most 8 sets.
| Field | Type | Rule |
|---|---|---|
| `id` | string | 1 to 32 characters among `a-z`, `0-9` and `-`, unique in the mod. The set's key is `/`. |
| `name` | string | 1 to 64 characters, no control characters. Shown in the pickers. |
| `params` | object | Optional. At most 8 parameters, by name. |
| `accuracy` | string | `osuScoreV1`, `wife3`, `weights` or `continuous`: [the native rule](#accuracy). |
| `holds` | string | `osuCombined`, `etterna`, `head` or `separate`: [the native rule](#holds). |
| `tiers` | function | `(params) => JudgementTier[]`: [the tiers](#tiers). Synchronous. |
An unknown field makes the call throw (`unknown field `x`, expected one of id, name, params, accuracy, holds, tiers`). A `tiers` that is not a function throws `tiers must be a function`.
### Parameters {#params}
A parameter is a number the player sets with a slider. Its name is the key in `params`, and your `tiers` function receives the values under the same names.
| Field | Rule |
|---|---|
| name (the key) | 1 to 32 ASCII letters and digits, starting with a letter (`od`, `judge`, `width`). |
| `label` | 1 to 32 characters. Shown next to the slider. |
| `min`, `max`, `step`, `default` | Finite numbers with `min < max`, `0 < step <= max - min` and `min <= default <= max`. Values are `min` plus a whole number of steps. |
| `short` | Optional, 1 to 8 characters, written right before the value where room is short: `J` gives `J4`. Without it the game writes the label, a space and the value (`OD 8`). |
The game normalizes the values before it calls `tiers`: every declared parameter is present, taken from the player's value when it is finite and from `default` otherwise, clamped to `[min, max]` and snapped to the step (`od` 8.34 becomes 8.3). Values for names you did not declare are dropped.
## Tiers {#tiers}
`tiers(params)` returns the tiers from the tightest to the widest window, **then the miss tier last**. Between 2 and 33 tiers: at most 32 hit tiers plus the miss.
| Field | Type | Rule |
|---|---|---|
| `id` | string | 1 to 32 characters among `a-z`, `0-9` and `-`, unique in the set. Stable: replays and the player's symbols refer to it. |
| `name` | string | 1 to 32 characters. |
| `color` | string | `#rgb`, `#rrggbb` or `#rrggbbaa`, at most 9 characters. |
| `gradient` | string[] | Optional, 2 to 8 colours in the same hex forms. See [colours](#colors). |
| `windowMs`, `earlyMs`, `lateMs` | number | Windows in milliseconds: see [windows](#windows). |
| `weight` | number | Accuracy weight. Required for every tier unless `accuracy` is `wife3`, which takes none. |
| `breaksCombo` | boolean | Default `false`. The miss tier always breaks the combo, whatever you write. |
### Windows {#windows}
A window has two sides. `earlyMs` is the largest distance **before** the note that earns the tier (an early press has a negative offset), and `lateMs` the largest distance **after** it. A press is graded against the windows of its own side: an offset of −`earlyMs` or +`lateMs` still earns the tier (bounds are inclusive).
`windowMs` is the symmetric shorthand: it sets both sides. You can give `windowMs` and replace one side only, as in `{ windowMs: 20, lateMs: 25 }`. A side with neither its own field nor `windowMs` is an error (`tier `a` needs windowMs, or earlyMs and lateMs`).
Each side must grow strictly from one hit tier to the next, independently of the other side. All windows are finite, above 0 and at most 1000 ms. The miss tier has no window of its own in the sense of a grade: its windows are the farthest presses, early and late, that still take a note and miss it. They must be at least as wide as the widest hit tier's window on the same side.
### Weights, combo and the miss {#weights}
Under `osuScoreV1`, `weights` and `continuous`, every tier, miss included, has a finite `weight` between −1000 and 1000. At least one hit tier has a positive weight, and the miss weight is at most the best hit weight. Under `osuScoreV1` and `weights`, accuracy is the sum of the weights earned over the best weight times the number of notes judged. Under `wife3` no tier has a weight: the curve is native.
`continuous` adds two rules: the first weight is positive and the weights never increase from one tier to the next, miss included.
`breaksCombo: true` on a tier means a press graded there resets the combo. Put it on the tiers you want to hurt; the miss does it by itself.
## Accuracy rules {#accuracy}
| `accuracy` | What the game does |
|---|---|
| `osuScoreV1` | osu!mania ScoreV1. Offsets are rounded to the millisecond (a window W takes errors up to W + 0.499 ms), a late press counts up to the second widest tier, an early press takes the note up to the early window of the miss tier. Accuracy by weight. |
| `wife3` | Etterna's Wife3 points per note. The curve is scaled by the mean of the first tier's early and late windows over 22.5 ms. Tiers take no weight. A press counts up to the miss window, on each side. |
| `weights` | Accuracy by weight. An early press counts up to the miss tier's early window, a late press up to the widest hit tier's late window. |
| `continuous` | Linear interpolation between the windows and weights you declare, separately on each side: a plateau at the first tier's weight inside its window, the miss penalty for a missed note. |
## Hold rules {#holds}
| `holds` | What the game does |
|---|---|
| `osuCombined` | One judgement from the head's and the release's errors together. Needs exactly 5 hit tiers. |
| `etterna` | The head's tier. The tail may be released up to 250 ms before its end. |
| `head` | The head's tier. The tail may be released up to the widest early window before its end; earlier is a miss. |
| `separate` | The head is judged at once and the release when the key is let go, as two score objects of equal weight. A tail held past the late limit expires as a miss; a missed head leaves no valid tail. |
## Mines {#mines}
A mine is not a note: it has no tier, never counts as a miss and never breaks the combo. It goes off when its lane's key is down as it crosses the receptors, or when a press that judges no note lands close to it; a mine left alone changes nothing. Your set decides two numbers with the optional `mine` field, for example `mine: { weight: -2, windowMs: 60 }`:
| Field | Meaning | Without it | Bounds |
|---|---|---|---|
| `weight` | Accuracy points a mine that goes off **adds**: zero or negative. | Five times your best tier weight, taken away; `-7` under `wife3`. | `-5000` to `0` |
| `windowMs` | How far from the mine a press that judges no note sets it off. | `75` | `10` to `1000` |
The Prism set declares `mine: { weight: -5 }`: one mine costs five perfect notes. A value outside the bounds refuses the registration.
## Colours, gradients and symbols {#colors}
`color` is the tier's plain colour: graphs and simple markers use it. `gradient` lists 2 to 8 colours that text shows **at the same time**, without any animation (the PRISM tier of the Prism set does this). Each colour is `#rgb`, `#rrggbb` or `#rrggbbaa`; anything else, a wrong count or a name like `red` is refused (`tier `prism`: gradient needs 2 to 8 hex colors`). The gradient is kept in the resolved tables, in custom presets and in replays.
A **symbol** is not something a mod declares. The player can show a short text or an image instead of a tier's name in **Settings → Game**; the choice is stored under the key `/` (`pvng.osu/osu-mania/perfect`, or `custom//t2` for a custom preset). That is why your tier ids must stay stable. A HUD mod reads the text symbol in `TierInfo.symbol`; it is `null` when there is none.
## The combination cache {#combinations}
Right after your `setup`, the mods thread runs `tiers(params)` **once for every combination** of your parameters: each parameter takes the values from `min` to `max` by `step`. osu!mania has 101 (OD 0 to 10 by 0.1), Etterna 9, a set without parameters 1. Rust checks each result and keeps it in compact tables that the game's play and the settings preview read directly, without calling your mod again. So `tiers` has no need to cache anything, and it must be a pure function of its argument.
| Limit | Value |
|---|---|
| Combinations resolved while loading | at most 4096 per set, and 1 s for all sets together |
| Beyond that | each remaining combination is resolved on first use (the player's choice, or the start of a map), once, then kept |
A combination whose `tiers` throws, returns something that is not tiers or fails the validation is **unavailable**: the pickers skip it and a play never uses it. Your mod receives one warning per set, for example `judgement set `judges/tight`: 1 of 4 parameter combinations are unavailable (first: width=4: tiers failed: too wide)`. A set without any valid combination is not offered. A throwing `tiers` does not count towards the errors that disable a mod; exceeding the execution budget does.
## What the game validates {#validation}
Your tiers go through two checks. The mods thread checks the size and shape (`resolve_tiers`), then the game checks the resolved set (`validate_set`), the same check it applies to the set stored in a replay. The message names the tier by its position: "Tier 3" is the third tier, and the last one is the miss.
| Message | Cause |
|---|---|
| `tiers must return 2 to 33 tiers (hit tiers, then the miss), got 1` | Fewer than 2 or more than 33 tiers. |
| `tier id must be 1 to 32 characters among a-z, 0-9 and `-`, got "A"` | An id outside the rule. |
| `Tier 2: the id "good" is used twice` | Two tiers share an id. |
| `tier `a` needs windowMs, or earlyMs and lateMs` | A side has no window. |
| `tier `a`: color "#ffffffffff" is too long` | A colour longer than 9 characters. |
| `Tier 2: "red" is not a #rgb, #rrggbb or #rrggbbaa color` | An unreadable colour. |
| `Tier 2: the early window must be above 0 and at most 1000 ms` | A window that is not finite, not positive or above 1000 ms. |
| `Tier 3: the late window must be above the previous one (18 ms)` | A hit window that does not grow. |
| `Miss tier: the early window must be at least the widest hit early window (24 ms)` | A miss window narrower than the widest hit window. |
| `Tier 2: this accuracy needs a weight on every tier` | A missing `weight` under `osuScoreV1`, `weights` or `continuous`. |
| `Tier 2: the weight must be between -1000 and 1000` | A weight out of range. |
| `At least one tier needs a positive accuracy weight` | No positive hit weight. |
| `Miss tier: the weight must not exceed the best tier weight (1)` | A miss worth more than the best hit. |
| `Continuous accuracy weights must not increase, including the miss tier` | A weight that rises under `continuous`. |
| `Wife3 tiers take no weight` | A `weight` under `wife3`. |
| `osu!mania holds need exactly 5 hit tiers, not 4` | `osuCombined` with another number of hit tiers. |
A mistake in the declaration itself fails the mod's `setup`:
| Message | Cause |
|---|---|
| `judgement set id must be 1 to 32 characters among a-z, 0-9 and `-`, got "Osu"` | An invalid set id. |
| `judgement set name must have 1 to 64 characters, got " "` | An empty or too long name. |
| `judgement set `x` declares 9 params; the limit is 8` | Too many parameters. |
| `param names are 1 to 32 ASCII letters and digits starting with a letter, got "2od"` | An invalid parameter name. |
| `param `od` needs finite min < max, 0 < step <= max - min and min <= default <= max` | An impossible range. |
| `param `judge` short must have 1 to 8 characters, got "Judgement"` | A `short` that is too long (the same shape for `label`, up to 32). |
| `judgement set `tight` is registered twice` | Two sets with the same id in the mod. |
| `a mod registers at most 8 judgement sets` | The ninth set. |
The TypeScript SDK catches the typos before the game does. A value that is not one of the four rules is a type error:
```ts error=TS2820
judgements.register({
id: "tight",
name: "Tight",
accuracy: "weights",
holds: "heads",
tiers: () => [
{ id: "hit", name: "Hit", color: "#ffffff", windowMs: 20, weight: 1 },
{ id: "miss", name: "Miss", color: "#ff0000", windowMs: 40, weight: 0 },
],
});
```
## The built-in sets {#built-in}
Prism, osu!mania and Etterna are mods in the game's `mods` folder, loaded like yours. They are the best examples to read: `content/mods/prism/main.ts`, `content/mods/osu/main.ts` and `content/mods/etterna/main.ts`.
| Set (key) | Mod, `loadOrder` | Parameter | Tiers | `accuracy` | `holds` |
|---|---|---|---|---|---|
| Prism (`pvng.prism/prism`) | `pvng.prism`, 5 | none | PRISM, MARVELOUS, PERFECT, GREAT, GOOD, BAD, POOR, MISS | `continuous` | `separate` |
| osu!mania (`pvng.osu/osu-mania`) | `pvng.osu`, 10 | `od`, 0 to 10 by 0.1 (default 5) | 300g, 300, 200, 100, 50, 0 | `osuScoreV1` | `osuCombined` |
| Etterna (`pvng.etterna/etterna`) | `pvng.etterna`, 20 | `judge`, 1 to 9, short `J` (default 4) | Marvelous, Perfect, Great, Good, Bad, Miss | `wife3` | `etterna` |
Prism's windows are ±7, 18, 36, 64, 92, 120 and 145 ms, with weights 1, 0.98, 0.93, 0.65, 0.28, −0.10 and −0.75, and −1.5 for a miss. osu!mania's windows follow `300g` 16 ms and `64 − 3 × OD`, `97 − 3 × OD`, `127 − 3 × OD`, `151 − 3 × OD`, `188 − 3 × OD`, truncated to the millisecond. Etterna's J4 windows are 22.5, 45, 90, 135 and 180 ms; the other judges scale them (J5 to J9 by 0.84, 0.66, 0.5, 0.33, 0.2) and the Bad and Miss windows stay at 180 ms.
Players can also build a **custom preset** in the settings, without any mod: 1 to 32 tiers with their own early and late windows, colours, weights and combo rule, plus a miss tier. It is shared as a `pvng-judgement-1:` string or a `.json` file. A preset is not a set: it is stored in the player's settings, not registered by a mod.
## How the player picks one {#picking}
- **Settings → Game → Judgement** lists the sets grouped by mod name, in the host's order (`loadOrder`, then mod `id`), then the custom presets. The chosen set shows a slider and a field per parameter, a preview of the windows, and the buttons to start a preset from a model or to duplicate any set as a preset.
- **The song selection** has a button beside Play that shows the judgement of the next play (`osu!mania · OD 8`, `Etterna · J4`: the `short` prefix of a parameter gives `J4`) and opens a small picker with the same sets.
A fresh install, and a settings file that never chose a judgement, start on **Prism**. A choice the player made is never changed: osu!mania OD 8, Etterna J4 or a preset stays. If the chosen set disappears (its mod disabled, failing or uninstalled), the choice moves to the first set left in the host's order, Prism when it is installed, and the player is told. A play whose set cannot be resolved (a removed mod, an unavailable combination) is played with the first set that resolves, the default first, and the player sees why (`Judgement set x: …. Playing with y instead.`). With no set left, a play with a set chosen cannot start; custom presets keep working.
## Replays, the local board and online {#replays-online}
- **Replays** store the **resolved** set: the tiers with both windows, the weights, `accuracy` and `holds`. A replay is rejudged without your mod, and later changes to your set never alter it.
- **The local leaderboard** rejudges every replay of a chart with the player's **current** judgement, so changing the judgement changes the ranking of the same plays. Mods read it with [`leaderboard.*`](https://prism.am/dev/md/guides/tabs-leaderboard.md#leaderboard).
- **Online**, the game server rejudges every play under the Prism judgement (`pvng.prism/prism`). The judgement a player picks locally changes their local play and board, never the online result.
## Reacting to tiers in a HUD {#hud}
A judgement pack often ships a HUD that follows the tiers. `game.judgements()` and the `judgements` field of `game.songStart` hold the active configuration: the preset name and every tier (`index`, `id`, `name`, `color`, `gradient`, `earlyMs`, `lateMs`, `weight`, `breaksCombo`), the miss last. Judgement events carry the tier index and `counts` per tier in the same order. The example `judgement-colors` registers a 15-tier set and draws a bar split by tier:
```ts
///
// A shareable judgement pack: registers "Spectrum 15", a 15-tier judgement set, for
// the game's picker, and shows at the bottom of the screen a bar split into the
// tiers of whatever judgement the chart plays with, each segment as wide as its
// share of the judgements, in the tier's color.
const BAR_WIDTH = 0.8; // screen heights
const BAR_HEIGHT = 0.012;
// 15 windows from ±4 ms to ±150 ms, colors from cyan to red, weights from 1 to 0.
const WINDOWS = [4, 8, 12, 17, 23, 30, 38, 47, 57, 68, 80, 94, 110, 128, 150];
const SPECTRUM = WINDOWS.map((windowMs, index) => {
const hue = 190 - (190 * index) / (WINDOWS.length - 1);
return {
id: `j${index + 1}`,
name: `J${index + 1}`,
windowMs,
color: hsl(hue),
weight: Math.round((1 - index / (WINDOWS.length - 1)) * 100) / 100,
breaksCombo: index >= WINDOWS.length - 2,
};
});
// `#rrggbb` of a fully saturated, half-light hue in degrees.
function hsl(hue: number): string {
const channel = (n: number) => {
const k = (n + hue / 30) % 12;
const value = 0.5 - 0.5 * Math.max(-1, Math.min(k - 3, 9 - k, 1));
return Math.round(value * 255).toString(16).padStart(2, "0");
};
return `#${channel(0)}${channel(8)}${channel(4)}`;
}
let tiers: TierInfo[] = [];
function build(config: JudgementConfig) {
tiers = config.tiers;
hud.clear();
hud.text({
id: "preset",
text: config.preset,
layout: { x: 0.5, y: 0.955, anchor: "bottom" },
style: { size: 0.02, color: "#ffffffaa" },
});
hud.group({
id: "bar",
flow: { direction: "row" },
layout: { x: 0.5, y: 0.975, width: BAR_WIDTH, height: BAR_HEIGHT, anchor: "bottom" },
style: { background: "#ffffff1a", radius: BAR_HEIGHT / 2 },
});
for (const tier of tiers) {
hud.box({
id: `segment-${tier.index}`,
parent: "bar",
layout: { width: 0, height: BAR_HEIGHT },
style: { background: tier.color, transitionMs: 120 },
});
}
}
export default defineMod({
id: "judgement-colors",
name: "Judgement Colors",
version: "1.1.0",
apiVersion: 2,
author: "PVNG",
description: "Spectrum 15 judgement set and a colored per-tier judgement bar.",
setup() {
// No parameters: `tiers` always returns the same 15 tiers, then the miss, whose
// window is the widest tier's.
judgements.register({
id: "spectrum-15",
name: "Spectrum 15",
accuracy: "weights",
holds: "head",
tiers: () => [
...SPECTRUM,
{ id: "miss", name: "Miss", color: "#ff2050", windowMs: 150, weight: 0, breaksCombo: true },
],
});
ctx.on("game.songStart", (start) => build(start.judgements));
ctx.on("game.judgement", (judgement) => {
const judged = judgement.counts.reduce((sum, count) => sum + count, 0);
for (const tier of tiers) {
const share = judged === 0 ? 0 : (judgement.counts[tier.index] ?? 0) / judged;
hud.update({ id: `segment-${tier.index}`, layout: { width: BAR_WIDTH * share } });
}
});
ctx.on("game.songEnd", () => hud.clear());
},
});
```
## Pitfalls {#pitfalls}
- Return the **miss last**, with windows at least as wide as the widest hit tier's. An unsorted list fails the validation.
- Give every tier a weight under `weights`, `osuScoreV1` and `continuous`, none under `wife3`.
- Keep tier ids stable between versions of your mod: symbols, the HUD and your own code key on them.
- A `tiers` that depends on anything but its argument (a clock, a random number, a global) is run once per combination: the game keeps the first result and never calls it again.
- Many parameters multiply: two parameters of 101 values are 10 201 combinations, more than the 4096 resolved while loading.
## See also {#see-also}
- [`judgements.register`](https://prism.am/dev/md/reference/sdk/gameplay.md#judgements-register) and the types `JudgementSetDefinition`, `JudgementTier` and `JudgementParam` in the [SDK reference](https://prism.am/dev/md/reference/sdk.md), or [modding.d.ts](https://prism.am/dev/sdk/modding.d.ts).
- [Rate charts with a calculator](https://prism.am/dev/md/guides/rating.md): the performance calculator that goes with each accuracy rule.
- [The local leaderboard and tabs](https://prism.am/dev/md/guides/tabs-leaderboard.md).
=====
Page: Add a difficulty rating
Address: https://prism.am/dev/guides/rating/
Derived from: crates/modding/src/ratings.rs, crates/modding/src/api.rs, crates/modding/src/library.rs, crates/core/src/rating.rs, crates/db/src/mod_tables.rs, crates/library/src/ratings.rs, content/mods/metron/main.ts, content/examples/mods/rating-pack/main.ts, content/examples/mods/skillset-filters/main.ts, docs/modding.md
# Add a difficulty rating
Declare a library rating with tables.register and ratings.register: the ten Metron calculators, panels, colour scales, pattern chips, backfill, metron.difficulty and metron.performance, and how the library shows them.
A rating is a number the library shows for every chart: the difficulty. A mod never calculates it. A **native calculator** (Metron) does, on background workers, and the result is stored in a table that belongs to your mod. Your mod declares three things: where the numbers are stored (`tables.register`), how a calculator's result is presented (`ratings.register`), and when to calculate (`ratings.backfill`). The game's own ratings come from one such mod, `pvng.ratings` (`content/mods/metron/main.ts`), which is the best larger example.
This page assumes you have made [a first mod](https://prism.am/dev/md/first-mod.md).
## A complete rating {#complete-example}
This mod adds Quaver stars to the library: a table with one column, a rating with a colour scale and two panels, a filter, and the calls that fill the table. It also writes the stored stars of the chart being played on screen.
```ts
///
// A difficulty rating for the library: Quaver stars, with a colour scale, two analysis
// panels and a library filter. The calculator is native (Metron); the mod only declares
// where the values are stored and how they are shown.
export default defineMod({
id: "rating-pack",
name: "Rating Pack",
version: "1.0.0",
apiVersion: 2,
author: "You",
description: "Quaver stars as a library rating, with panels, colours and a filter.",
setup() {
// The calculator's version is part of the declaration: read it, never copy it.
const calculator = metron.catalog().calculators.find((entry) => entry.id === "quaver-2025");
if (!calculator) return;
// 1. A table of this mod. The native calculation writes `stars` into it, one row per chart.
tables.register({
id: "quaver_rating",
columns: [{ name: "stars", kind: "number", indexed: true }],
});
// 2. The view the player picks in the library's rating menu.
ratings.register({
id: "quaver",
name: "Quaver · stars",
calculator: calculator.id,
unit: "★",
table: "quaver_rating",
column: "stars",
version: calculator.version,
// Data, never code: blue at 1 star, green at 3, red at 5 and beyond, mixed in sRGB.
colors: {
stops: [
{ at: 1, color: "#4fc0ff" },
{ at: 3, color: "#7cff4f" },
{ at: 5, color: "#ff4e6f" },
],
},
panels: [
{
kind: "metrics",
title: "Chart profile",
fields: [
{ label: "Stars", source: { kind: "column", column: "stars" }, unit: "★", decimals: 2 },
{ label: "Long notes", source: { kind: "chart", metric: "holdPercent" }, unit: "%" },
{ label: "Peak density", source: { kind: "chart", metric: "peakNps" }, unit: "NPS" },
],
},
{
kind: "timeline",
title: "Timeline",
series: [{ label: "Density", source: "density", unit: "NPS" }],
},
],
});
// 3. A filter on the same column: "Quaver · stars" in the library's search.
library.filters.register({
id: "quaver",
name: "Quaver · stars",
table: "quaver_rating",
column: "stars",
version: calculator.version,
unit: "★",
});
// 4. Nothing is calculated until the mod asks. `null` means the workers are busy: the
// next check catches up, since a backfill only looks at charts without a current row.
const rateAll = () => {
if (ratings.backfill({ id: "quaver" }) === null) log.warn("Rating workers are busy; the next check calculates it");
};
ctx.on("library.ready", rateAll);
ctx.on("library.chartsAdded", ({ chartIds, truncated }) => {
if (truncated) rateAll();
else ratings.backfill({ id: "quaver", charts: chartIds });
});
ctx.on("ratings.progress", (progress) => {
if (progress.finished && progress.error) log.warn(`${progress.id}: ${progress.error}`);
});
// 5. The stored value of the chart being played, for any HUD. `null` until it is rated.
ctx.on("game.songStart", () => {
const stars = metron.difficulty({ calculator: calculator.id });
hud.text({
id: "stars",
text: stars === null ? "" : `${stars.toFixed(2)} ★`,
layout: { x: 0.02, y: 0.04, anchor: "topLeft" },
style: { size: 0.025, color: "#ffffff" },
});
});
ctx.on("game.songEnd", () => hud.clear());
},
});
```
Copy the folder `rating-pack` into your mods folder (Mods page, *Open folder*). The library's rating menu now lists **Quaver · stars**. Pick it: the processing window shows a *Calculating difficulty* row, then the maps carry their stars. The rest of this page explains each part.
## Tables {#tables}
`chartset` and `chart` hold folders and difficulties; they have no star or MSD column. Your values go in a table of your own, declared with `tables.register`. There is one row per chart, removed with its chart, plus the columns you name.
```ts fragment
tables.register({
id: "quaver_rating",
columns: [{ name: "stars", kind: "number", indexed: true }],
});
```
| Field | Rule |
|---|---|
| `id` | `^[a-z][a-z0-9_]{0,31}$`: lowercase letters, digits and underscores, starting with a letter. Unique in your mod. |
| `columns` | 1 to 32 columns. |
| column `name` | The same pattern as `id`. `chart_id`, `calc_version`, `chart_stamp`, `chart_size` and `error` are reserved. |
| column `kind` | `number` or `text`. |
| column `indexed` | Optional. `true` lets the database index the column: set it on every column a filter or the difficulty sort reads. |
A mod registers at most 16 tables. Tables are isolated by mod: a rating, a filter or a tab cannot read another mod's table. A later version of your mod may add columns; an existing column never changes its type. A table is only filled by the native calculation of a rating that targets it, and only **number** columns are filled: a `text` column stays empty, so declare numbers.
`tables.register` is called from `setup`. Only mods register tables.
## The rating declaration {#declaration}
`ratings.register` ties a calculator to a column of one of your tables and says how to show it.
| Field | Rule |
|---|---|
| `id` | 1 to 32 characters among `a-z`, `0-9` and `-`, unique in your mod. The player's key is `/` (`rating-pack/quaver`). |
| `name` | 1 to 64 characters, shown in the library's rating menu. |
| `calculator` | A calculator id from `metron.catalog()`. |
| `unit` | 1 to 16 characters after the value: `★`, `MSD`. |
| `table`, `column` | A table of your mod and a **number** column of it. The calculator's main value goes there. |
| `version` | Must be the calculator's `version` (see [calculators](#calculators)). |
| `panels` | Optional, at most 4: [panels](#panels). |
| `colors` | Optional: a [colour scale](#colors). |
| `patterns` | Optional, at most 12: [pattern chips](#patterns). |
A mod registers at most 16 ratings. `ratings.register` is called from `setup`, after the `tables.register` of its table.
## Calculators {#calculators}
`metron.catalog()` returns the calculators the game offers: `{ calculators: [{ id, performance, version }] }`. There are ten.
| `id` | Its difficulty | `performance` |
|---|---|---|
| `osu-2016` | osu!mania stars, the 2016 version (the same values as `osu-2018`) | no |
| `osu-2018` | osu!mania stars, the 2018 version | pp |
| `osu-current` | osu!mania stars, the current version | no |
| `etterna-515` | MinaCalc 527 MSD, with the seven skillsets | SSR |
| `quaver-2025` | Quaver stars | no |
| `interlude-2025` | Interlude stars | no |
| `daniel-2026` | Daniel stars | no |
| `sunnyxxy-2024` | SunnyXXY stars | no |
| `prism` | PrismCalc MSD converted to osu!mania stars: the stars Prism's pp are computed from | Prism pp |
| `prismcalc-1` | PrismCalc: MinaCalc 527 with Prism's chordjack rework, MSD with the seven skillsets. The game's default rating | no |
`version` increases when a calculator's behaviour changes. A stored row from an older version is stale and is calculated again. Read it from the catalog, as the example does, and never copy a number: a rating whose `version` differs from the calculator's is refused (`rating version must match the native calculator version`). The shipped `pvng.ratings` registers eight of these (not `osu-2018`, whose difficulty `osu-2016` already shows, and not `prism`).
Only the calculators that return seven skillsets (`etterna-515` and `prismcalc-1`) fill more than the main column: see [patterns](#patterns).
## Panels {#panels}
`panels` is an ordered list of up to four analysis panels, shown in the library's Infos for the selected chart. A panel is data: the theme draws it, and a mod never supplies HTML, CSS or code. A value that is not available shows `—`, never a zero.
| `kind` | Shows | Fields |
|---|---|---|
| `metrics` | Values side by side | `title`, `fields`: 1 to 16 |
| `bars` | Values with comparison bars | `title`, `fields`: 1 to 16, optional `max` |
| `radar` | Named axes with filled bars | `title`, `fields`: 3 to 12, optional `max` |
| `timeline` | Series of the chart over time | `title`, `series`: 1 or 2 with different sources |
A `title` and a field `label` are 1 to 64 characters. A field has a `source`, a `unit` (0 to 16 characters, empty by default) and `decimals` (0 to 3, 1 by default). The source is one of:
- `{ kind: "column", column }`: a number column of the rating's table, its main column included;
- `{ kind: "chart", metric }`: a real statistic of the chart, one of `notes`, `holds`, `holdPercent` (holds over notes, ×100; 0 for an empty chart), `averageNps`, `peakNps`, `bpmMin`, `bpmMax` or `duration` (seconds). An analysis that is missing stays unavailable.
A timeline series is `{ label, source, unit }` with `source` `density` or `bpm`; the values come from the chart analysis already made, so nothing is calculated on the interface.
`max` on `bars` and `radar` is a fixed scale, finite and in `(0, 1000000]`. Without it (or with `null`) the scale is automatic, with a maximum of at least 1. With `max: 40`, a value of 10 fills 25 % and any value of 40 or more fills 100 %. The number shown is never changed by the scale.
## Colours {#colors}
The colour of a difficulty is written nowhere in the interface: your rating declares it, as data. A rating without `colors` stays neutral, and an unavailable value is never coloured.
```ts fragment
ratings.register({
id: "stars",
name: "Stars",
calculator: "quaver-2025",
unit: "★",
table: "quaver_rating",
column: "stars",
version: 1,
colors: {
scale: 1, // optional: the value is divided by `scale` before the stops are read
stops: [
{ at: 0, color: "#4290fb" },
{ at: 5, color: "warn" }, // a colour role of the active theme
{ at: 8, color: "#ffffff" },
],
},
});
```
- `stops`: 1 to 16 points `{ at, color }`. `at` is finite, at most 1 000 000 in absolute value and **strictly increasing**. Between two stops the colour is mixed channel by channel in sRGB; beyond the ends, the nearest stop's colour applies.
- `color`: `#rgb` or `#rrggbb` (no transparency), or the name of a colour role of the active theme (`accent`, `ok`, `warn`…, the `--pv-` tokens whose type is `color`). A role follows the theme when the player changes it. Anything else (`red`, `rgb(…)`, `var(--x)`) is refused.
- `scale`: optional, finite, in `(0, 1000000]`. Values are divided by it, so the stops are written in that unit. The shipped MinaCalc ratings use `scale: 4.5`: a ramp written in osu! stars reads MSD ÷ 4.5.
A scale that is not valid (no stop, more than 16, a bad `at`, an order that does not increase, a refused colour, a bad `scale`) is dropped **by itself**: the rating registers, stays neutral, and your mod gets a warning that names the stop (`rating `stars`: its colour scale was ignored, the rating stays neutral: stop 1: `at` must be greater than the previous stop's`). An unknown property, in contrast, fails the whole declaration.
The colours apply to the map rows, the set markers, the selected map and every value, bar or radar point of the Infos panels.
## Pattern chips {#patterns}
`patterns` lets the library name a chart's **main pattern**. Each entry points at a number column of the rating's table that scores one pattern:
| Field | Rule |
|---|---|
| `column` | A number column of the rating's table. Once per pattern. |
| `label` | The full name, 1 to 32 characters (`Jumpstream`). |
| `short` | The chip's text, 1 to 5 characters (`js`). |
| `color` | Optional: `#rgb`, `#rrggbb` or a colour role. Without it, the chip takes the difficulty's colour. |
The host takes the highest value above 0, and the second one when it is within 10 % of it, and shows the chips on the difficulty in the map list. Nothing is recalculated.
The values come from the calculator. For `etterna-515` and `prismcalc-1`, the native calculation fills the main column and, in the **same table**, every number column whose name is one of these seven: `stream`, `jumpstream`, `handstream`, `stamina`, `jackspeed`, `chordjack`, `technical`. The other calculators fill the main column only.
```ts fragment
const skills = ["stream", "jumpstream", "handstream", "stamina", "jackspeed", "chordjack", "technical"];
const calculator = metron.catalog().calculators.find((entry) => entry.id === "prismcalc-1");
if (calculator) {
tables.register({
id: "skills_rating",
columns: [{ name: "overall", kind: "number" }, ...skills.map((name) => ({ name, kind: "number" as const }))],
});
ratings.register({
id: "msd",
name: "PrismCalc · MSD",
calculator: calculator.id,
unit: "MSD",
table: "skills_rating",
column: "overall",
version: calculator.version,
patterns: [{ column: "jumpstream", label: "Jumpstream", short: "js", color: "#ff9f40" }],
panels: [
{
kind: "radar",
title: "Skillsets",
max: 40,
fields: skills.map((column) => ({ label: column, source: { kind: "column" as const, column }, unit: "MSD" })),
},
],
});
}
```
The complete mod, with the seven patterns and the filters, is the example of the [library filters guide](https://prism.am/dev/md/guides/library-filters.md#complete-example).
## Calculating: `ratings.backfill` {#backfill}
Nothing is calculated until your mod asks. `ratings.backfill({ id })` looks for the charts that have **no current row** (no row, another calculator `version`, or a chart file that changed) and queues them on the library's workers. With `charts: number[]` it looks at those charts only.
```ts fragment
ctx.on("library.ready", () => {
ratings.backfill({ id: "quaver" });
});
ctx.on("library.chartsAdded", ({ chartIds, truncated }) => {
ratings.backfill(truncated ? { id: "quaver" } : { id: "quaver", charts: chartIds });
});
```
| Event | When | What to do |
|---|---|---|
| `library.ready` | After the interface and the mods have loaded; also on an explicit rescan and on the player's *Recalculate ratings*. | The global check: backfill every rating of the mod. |
| `library.chartAdd` | One per chart a scan added, with `chartId`. | Rare: prefer the next event. |
| `library.chartsAdded` | A scan added charts (a pack was installed): `chartIds` (at most 8192) and `truncated` beyond. | Backfill with `charts: chartIds`; the rest of the library is not looked at. When `truncated`, backfill everything. |
| `ratings.progress` | The requests of **your** mod only: `requestId`, `id`, `done`, `total`, `failed`, `finished`, `error`, `ahead`. | React to the end of a request (`finished`). |
`ratings.backfill` returns a request number, or `null` when requests pile up (16 waiting per mod, 64 in all) or the workers refuse it. `null` is not a failure: the next check calculates what is missing. Asking for more than 8192 charts, an invalid chart id or an unknown rating `id` throws.
Do not draw a progress bar. The host publishes the last report of each request and the library's processing window shows it as a *Calculating difficulty* row, one line per rating, with the name you gave it, the time left, `Waiting · n before` (that is `ahead`), a pause while the player is in a play and, when a request fails, its message and a *Retry* button. `ratings.progress` is for your own logic.
Requests share the work. In each round the coordinator takes charts in turn from every queue, reads and decodes each chart **once** for all the ratings that wait for it, and writes each request's results in one batch. The calculation runs on a low-priority pool and never blocks the mods thread. A calculation that fails for one chart is stored as an error for it, shown `—`, and the others go on: no artificial value is made up.
## Reading values during a play {#reading}
```ts fragment
const stars = metron.difficulty({ calculator: "quaver-2025" }); // number | null
const stored = game.song()?.ratings; // by calculator id
const chosen = game.settings()?.ratingSystem; // "/" of the player's rating
```
`metron.difficulty({ calculator })` returns the stored value of the chart being played, or `null`. It comes from the library, not from a new calculation, and it exists only for a calculator that some installed mod **registers a rating for**, once that chart has been rated. `game.song()?.ratings` holds all the values the library has for the chart, by calculator id. An unknown calculator id throws (`unknown Metron calculator "x"`).
## Performance: `metron.performance` {#performance}
A performance is a score's value for a given accuracy: pp or SSR. Only three calculators have one: `osu-2018` (pp), `etterna-515` (SSR) and `prism` (Prism's pp). Nothing is derived from stars.
```ts fragment
// `accuracy` is a fraction from 0 to 1, in the calculator's own score system.
const requestId = metron.performance({ calculator: "osu-2018", accuracy: 0.95 }); // number | null
ctx.on("metron.performanceResult", (result) => {
if (result.error) {
log.warn(result.error);
return;
}
hud.text({ id: "performance", text: `${(result.value ?? 0).toFixed(2)} ${result.unit}` });
});
```
The result arrives, to the requesting mod only, as `metron.performanceResult`: `requestId`, `calculator`, `value`, `unit` (`pp` or `SSR`) and `error`. A mod has 2 requests waiting at most (64 in all): beyond that the call returns `null`. A new chart invalidates the answers still on their way. The game thread and the mods thread never wait for the calculation.
The host does not convert the accuracy of the active judgement into an osu! or Etterna score: your mod gives the accuracy that fits the calculator.
When **the game** rates a score (the local leaderboard, the replay page), its *Auto* performance choice follows the judgement's accuracy rule: `osuScoreV1` gives `osu-2018` (pp), `wife3` gives `etterna-515` (SSR), the Prism set gives `prism` (pp), and every other set or custom preset has none. The player can pick any of the three for any judgement; a combination that does not use the calculator's own conventions is flagged `nonstandard` in the board. The online board is not affected: it always reads Prism plays.
## In the library {#library}
- **The rating menu** lists every registered rating by `name`, in registration order. The player's choice is the setting `ratingSystem`, the key `/`. The default is `pvng.ratings/prismcalc-1`. The player can hide a rating from the menu without disabling its mod.
- **Difficulty** is shown for the chosen rating: the value and its unit on every difficulty, coloured by its `colors`, with the pattern chips. The library's *sort by difficulty* and *group by difficulty* use the chosen rating's column.
- **Infos** shows the chosen rating's `panels` for the selected chart, at the playback rate the player picked.
- **Search**: a [library filter](https://prism.am/dev/md/guides/library-filters.md) on the same column.
- **Lifecycle**: disabling or uninstalling a mod withdraws its ratings at once. If the chosen rating goes, the choice moves to PrismCalc (or the first rating left) and the player is told.
- *Maps to play* and the rate advice use the PrismCalc rating that declares patterns. Without a mod that declares it, they report no rating.
## What you will see {#errors}
A mistake in `tables.register` or `ratings.register` throws in `setup` and fails the mod's load. The messages are in English:
| Message | Cause |
|---|---|
| `table and column ids must use lowercase ASCII letters, digits and underscores (1–32 characters)` | An invalid table or column id. |
| `a mod table has 1–32 columns` | No column, or more than 32. |
| `duplicate or reserved mod column` | A repeated column, or `chart_id`, `calc_version`, `chart_stamp`, `chart_size`, `error`. |
| `a mod registers at most 16 uniquely named tables` | A seventeenth table, or the same `id` twice. |
| `tables.register is only available in a mod's setup` | Called later, or by a skin or a map script. |
| `rating table is not registered` | `ratings.register` before the `tables.register` of its table. |
| `rating must reference a registered numeric column of its mod` | A `column` that is missing, not a number, or in another table. |
| `unknown Metron calculator "x"` | A `calculator` that is not in the catalog. |
| `rating version must match the native calculator version` | A copied or stale `version`. |
| `rating id must be 1 to 32 characters among a-z, 0-9 and `-`, got "X"` | An invalid rating id. |
| `rating name must have 1 to 64 characters, got ""` | An empty or long name. |
| `rating unit must have 1 to 16 characters, got ""` | An empty or long unit. |
| `a rating has at most 4 panels` | A fifth panel. |
| `panel must have 3 to 12 fields` | The wrong number of fields (1 to 16 for `metrics` and `bars`). |
| `panel fields must reference registered numeric columns of the rating's table` | A `column` source that is not a number column of the table. |
| `panel field decimals must be between 0 and 3` | `decimals` out of range. |
| `panel max must be finite and greater than 0, at most 1000000` | A bad `max`. |
| `timeline must have 1 to 2 series` / `timeline series sources must be unique` | A timeline with 0 or 3 series, or twice the same source. |
| `a rating declares at most 12 patterns` | A thirteenth pattern. |
| `rating patterns must reference registered numeric columns of the rating's table` | A pattern on a missing or text column. |
| `rating pattern column `x` is declared twice` | Two patterns on one column. |
| `rating `quaver` is registered twice` / `a mod registers at most 16 ratings` | A repeated id, or a seventeenth rating. |
| `ratings.register is only available in a mod's setup` | Called later. |
And at run time:
| Message | Cause |
|---|---|
| `unknown registered rating` | `ratings.backfill` with an `id` that is not registered by this mod. |
| `too many charts in one scoped backfill` / `invalid chart id` | More than 8192 charts, or an id below 1. |
| `library workers are unavailable` | No library behind the host (a test, for instance). |
| `Metron has no performance calculator for quaver-2025` | `metron.performance` with a calculator that has none. |
| `accuracy must be a fraction from 0 to 1` | A percentage instead of a fraction. |
| `no decoded chart is playing` | `metron.performance` outside a play. |
## Pitfalls {#pitfalls}
- Copying a calculator `version` instead of reading it from `metron.catalog()`: the declaration is refused as soon as the calculator changes.
- Registering a rating in an event handler: the registries close once the mods have loaded.
- Declaring a `text` column and expecting values: only number columns are filled.
- Expecting a skillset in a column with another name: only the seven names above are filled.
- Calling `ratings.backfill` for every chart of the library in a loop: one call per rating, and `charts` for a scoped check, is enough.
- Asking `metron.difficulty` for a calculator no mod registers: it returns `null`.
- Treating a percentage as the `accuracy` of `metron.performance`: it is a fraction.
## See also {#see-also}
- [`ratings.register`, `tables.register`, `ratings.backfill`, `metron.*`](https://prism.am/dev/md/reference/sdk/ratings.md) in the SDK reference.
- [Library filters](https://prism.am/dev/md/guides/library-filters.md): search on your table's columns.
- [Tabs and the local leaderboard](https://prism.am/dev/md/guides/tabs-leaderboard.md): show your rating in a tab of the chart panel.
- [Judgement sets](https://prism.am/dev/md/guides/judgement-set.md): the accuracy rules behind the *Auto* performance.
=====
Page: Add library filters
Address: https://prism.am/dev/guides/library-filters/
Derived from: crates/modding/src/filters.rs, crates/modding/src/api.rs, crates/db/src/search.rs, crates/db/src/mod_tables.rs, crates/db/src/pagination.rs, content/mods/metron/main.ts, content/examples/mods/skillset-filters/main.ts, docs/modding.md
# Add library filters
Register library search criteria with library.filters.register: the table and rating behind a filter, the typed query the library sends, the host's own criteria, the limits and the errors.
A library filter is a search criterion the player adds in the library's **+ Filter** window: "MinaCalc · Stream between 18 and 25". Your mod declares which **column of one of its tables** the criterion reads, and the game does the search. A script never sends SQL, an expression or a function to run on each chart: it names a column, and the database does the rest on indexed rows.
This page assumes you know [tables and ratings](https://prism.am/dev/md/guides/rating.md), because a filter reads a table of your mod, and only a rating's native calculation fills a table.
## A complete example {#complete-example}
This mod rates charts with MinaCalc 527 and makes the overall rating and each of the seven skillsets searchable. It also declares a radar and the pattern chips: the rating is what fills the table, and the filters read it.
```ts
///
// MinaCalc's rating and its seven skillsets, searchable in the library. A filter reads a
// column of a table of this mod, and only a rating's native calculation fills a table: the
// rating below is what makes the filters work. Its `overall` column gets the rating, and
// the columns named after a skillset get that skillset (see the guide for the closed list).
const SKILLS = ["stream", "jumpstream", "handstream", "stamina", "jackspeed", "chordjack", "technical"];
const NAMES = ["Stream", "Jumpstream", "Handstream", "Stamina", "Jackspeed", "Chordjack", "Technical"];
const SHORTS = ["str", "js", "hs", "stam", "sj", "cj", "tech"];
export default defineMod({
id: "skillset-filters",
name: "Skillset Filters",
version: "1.0.0",
apiVersion: 2,
author: "You",
description: "MinaCalc 527 ratings and skillsets, with a radar, pattern chips and library filters.",
setup() {
const calculator = metron.catalog().calculators.find((entry) => entry.id === "etterna-515");
if (!calculator) return;
tables.register({
id: "skills_rating",
columns: [
{ name: "overall", kind: "number", indexed: true },
...SKILLS.map((name) => ({ name, kind: "number" as const, indexed: true })),
],
});
ratings.register({
id: "msd",
name: "MinaCalc · MSD",
calculator: calculator.id,
unit: "MSD",
table: "skills_rating",
column: "overall",
version: calculator.version,
// The values are divided by `scale` before the stops are read: 4.5 reads MSD on a
// ramp written in stars (blue at 1 star = 4.5 MSD, red at 5 stars = 22.5 MSD).
colors: {
scale: 4.5,
stops: [
{ at: 1, color: "#4fc0ff" },
{ at: 3, color: "#7cff4f" },
{ at: 5, color: "#ff4e6f" },
],
},
// The chart's main pattern is its highest skillset (and the second one, within 10 %).
patterns: SKILLS.map((column, index) => ({ column, label: NAMES[index], short: SHORTS[index] })),
panels: [
{
kind: "radar",
title: "Skillsets",
max: 40,
fields: SKILLS.map((column, index) => ({
label: NAMES[index],
source: { kind: "column" as const, column },
unit: "MSD",
})),
},
],
});
// One filter on the overall rating and one per skillset: `/` is the key.
library.filters.register({
id: "msd",
name: "MinaCalc · Overall",
table: "skills_rating",
column: "overall",
version: calculator.version,
unit: "MSD",
});
SKILLS.forEach((column, index) => {
library.filters.register({
id: `msd-${column}`,
name: `MinaCalc · ${NAMES[index]}`,
table: "skills_rating",
column,
version: calculator.version,
unit: "MSD",
});
});
ctx.on("library.ready", () => {
ratings.backfill({ id: "msd" });
});
ctx.on("library.chartsAdded", ({ chartIds, truncated }) => {
ratings.backfill(truncated ? { id: "msd" } : { id: "msd", charts: chartIds });
});
},
});
```
Copy the folder `skillset-filters` into your mods folder (Mods page, *Open folder*). The filter window now lists eight criteria named *MinaCalc · Overall*, *MinaCalc · Stream*, and so on; they match charts as the first calculation stores their rows. The rest of this page explains the declaration.
## The declaration {#declaration}
```ts fragment
library.filters.register({
id: "msd",
name: "MinaCalc · Overall",
table: "skills_rating",
column: "overall",
version: 2,
unit: "MSD",
});
```
| Field | Rule |
|---|---|
| `id` | 1 to 32 characters among `a-z`, `0-9` and `-`, unique in your mod. The filter's key is `/`. |
| `name` | 1 to 64 characters, shown in the filter window. |
| `table`, `column` | A table already registered by **this** mod and one of its columns. The column's type decides the kind of filter: `number` or `text`. |
| `version` | An integer of at least 1: the calculation version the rows must carry. For a table fed by a rating, use the calculator's `version` (read it from `metron.catalog()`). |
| `unit` | Optional, at most 16 characters, no control characters. Written after the numbers. |
A mod registers at most 32 filters. `library.filters.register` is called from `setup`, after the `tables.register` of its table; the registry closes once the mods have loaded. Only mods register filters. A mod whose id is `host` cannot: `host/` is the prefix of the game's own criteria.
The library publishes the whole catalogue, the host's criteria and the mods', after the mods have loaded, and withdraws a mod's filters when the mod stops, is disabled or is uninstalled.
## What a filter can read {#columns}
A table is filled only by a rating's native calculation. So a filter is useful on:
- the **main column** of a rating's table (stars, MSD);
- for `etterna-515` and `prismcalc-1`, the columns named after the seven skillsets in the same table: `stream`, `jumpstream`, `handstream`, `stamina`, `jackspeed`, `chordjack`, `technical`.
No calculation fills a `text` column, so a filter on one never matches anything. Use number columns, and set `indexed: true` on the columns you filter on so the database can use an index.
A row counts only if it is current. The search keeps a chart when its row has the filter's `version`, was calculated from the chart file as it is now (same stamp and size) and holds no error. A missing value, a failed calculation and a stale row **never match**, not even a bound of 0.
## The host's criteria {#host-criteria}
The catalogue also holds the game's neutral criteria, keyed `host/`. They are the same query language as yours.
| Key | Kind | Reads |
|---|---|---|
| `host/keys` | number | Key count |
| `host/bpmMin`, `host/bpmMax` | number | Minimum and maximum BPM |
| `host/duration` | number | Duration, in seconds |
| `host/averageNps`, `host/peakNps` | number | Average and peak density |
| `host/notes`, `host/holds` | number | Notes and holds |
| `host/title`, `host/artist` | text | Title and artist, original or romanised |
| `host/creator`, `host/difficulty` | text | Mapper and difficulty name |
| `host/tag`, `host/note` | text | The player's own tags and note on a map |
| `host/goals`, `host/goalsReached`, `host/goalsOpen` | number | Goals on a chart |
## The query the library sends {#language}
The interface sends a typed `LibraryQuery`; your filters never see it, but its rules explain what a filter does.
| Part | Rule |
|---|---|
| `text` | Free words, at most 512 characters. Each word is a literal substring of the title, artist, mapper, difficulty or the player's note. |
| `filters` | At most 16 clauses `{ key, value }`. A `key` has at most 256 bytes and no control character. |
| number clause | `{ kind: "number", min?, max? }`: at least one finite bound, both inclusive, `min <= max`. Signed decimals are accepted, with no rounding. |
| text clause | `{ kind: "text", value, exact }`: 1 to 256 characters once the outer spaces are removed. `exact` asks for equality (letter case ignored), otherwise for a literal substring. |
The free words and **all** the clauses combine with AND on **the same chart**, never across the difficulties of a folder. A page holds at most 80 sets and lists only the difficulties that match; the count, the page and the position of the open folder come from one snapshot. A filter that is not available (an unknown key, a mod that stopped) is an **error** (`unavailable library filter: pvng.ratings/etterna-515`), never a condition dropped in silence. Every value is bound as an SQLite parameter.
## What you will see {#errors}
A mistake in the declaration throws in `setup`:
| Message | Cause |
|---|---|
| `filter id must be 1 to 32 characters among a-z, 0-9 and `-`, got "../host"` | An invalid id. |
| `filter name must have 1 to 64 characters, got " "` | An empty or long name. |
| `filter unit must have at most 16 characters and no control characters` | A bad `unit`. |
| `filter version must be positive` | `version: 0`. |
| `filter table is not registered by this mod` | `table` is not one of your registered tables. |
| `filter must reference a registered column of its mod` | `column` is not a column of that table. |
| `filter id is registered twice` | The same `id` twice. |
| `a mod registers at most 32 library filters` | The thirty-third filter. |
| `host is reserved for neutral library filters` | A mod whose id is `host`. |
| `library.filters.register is only available in a mod's setup` | Called later. |
| `only mods register library filters` | Called by a skin or a map script. |
## Pitfalls {#pitfalls}
- A filter with no rating that fills its table: it registers, and matches nothing.
- A `version` that differs from the one the rating writes: every row is stale, and nothing matches.
- A filter on a column the calculator does not fill (a skillset column on `quaver-2025`): the rows hold no value.
- Forgetting `indexed: true` on a column you search: it works, more slowly on a large library.
- Registering a filter from an event handler: the registry is closed.
## See also {#see-also}
- [`library.filters.register`](https://prism.am/dev/md/reference/sdk/ratings.md#library-filters-register) in the SDK reference.
- [Add a difficulty rating](https://prism.am/dev/md/guides/rating.md): the tables, calculators and `ratings.backfill` a filter depends on.
=====
Page: Add chart tabs and read the local leaderboard
Address: https://prism.am/dev/guides/tabs-leaderboard/
Derived from: crates/modding/src/tabs.rs, crates/modding/src/leaderboard.rs, crates/modding/src/api.rs, crates/modding/src/runtime.rs, content/examples/mods/chart-tab/main.ts, content/examples/mods/best-plays/main.ts, docs/modding.md, docs/mods-leaderboard-et-onglets.md
# Add chart tabs and read the local leaderboard
Add a tab or extra sections to the song selection's chart panel with tabs.register and tabs.extend, with typed panels and a closed list of icons, and read a chart's local ranking with leaderboard.query and leaderboard.best.
The song selection shows a panel for the chart you pick, with tabs: Info, Leaderboard, Mods, Training and Editor. A mod can add **a tab of its own** and **sections to Info, Leaderboard and Mods**. A mod can also **read the local ranking** of a chart. Both are declarative and bounded: Rust validates what you name, resolves the numbers for the selected chart and draws it with the active theme's own classes. You never supply markup, a style, an icon file or code, and you never remove or rewrite what the host draws.
Neither feature needs a permission: the local ranking is the player's own data, read-only, and a script never sees a path, a file or the inputs of a replay. Only mods use them, not skins or map scripts. This page assumes you have made [a first mod](https://prism.am/dev/md/first-mod.md).
## A first tab {#first-tab}
This mod adds a **Skills** tab: a rating, chart facts and the plays count; two bars; the five best plays; a note. It also adds a line below the host's Info section.
```ts
///
// A tab in the song selection's chart panel, next to Info, Leaderboard and Mods, and one
// extra section in the host's Info tab. Everything is declared in `setup`: the game
// validates it, resolves the numbers for the selected chart and draws it.
export default defineMod({
id: "chart-tab",
name: "Chart Tab",
version: "1.0.0",
apiVersion: 2,
author: "You",
description: "A Skills tab with a rating, chart facts, the best plays and a note.",
setup() {
// A `column` field reads the table of a rating of THIS mod, so the rating comes first.
const calculator = metron.catalog().calculators.find((entry) => entry.id === "etterna-515");
if (!calculator) return;
tables.register({
id: "skills_rating",
columns: [
{ name: "overall", kind: "number" },
{ name: "stream", kind: "number" },
{ name: "technical", kind: "number" },
],
});
ratings.register({
id: "skills",
name: "Skills",
calculator: calculator.id,
unit: "MSD",
table: "skills_rating",
column: "overall",
version: calculator.version,
});
tabs.register({
id: "skills",
title: "Skills",
icon: "gauge", // one of the 16 icons of the closed list
order: 10,
panels: [
{
kind: "metrics",
title: "Overview",
fields: [
{ label: "Overall", source: { kind: "column", rating: "skills", column: "overall" }, unit: "MSD", decimals: 1 },
{ label: "Peak density", source: { kind: "chart", metric: "peakNps" }, unit: "NPS" },
{ label: "Plays", source: { kind: "leaderboard", stat: "plays" }, decimals: 0 },
],
},
{
kind: "bars",
title: "Balance",
max: 40,
fields: [
{ label: "Stream", source: { kind: "column", rating: "skills", column: "stream" }, unit: "MSD" },
{ label: "Technical", source: { kind: "column", rating: "skills", column: "technical" }, unit: "MSD" },
],
},
{ kind: "leaderboard", title: "Best plays", limit: 5 },
{ kind: "text", title: "Note", text: "Values are those of the base chart, at rate 1.0." },
],
});
// Sections are added before (`top`) or after (`bottom`) what the host draws; nothing of
// the host's content is removed or rewritten.
tabs.extend({
tab: "info",
slot: "bottom",
order: 10,
panels: [{ kind: "text", text: "Below the host's Info section." }],
});
},
});
```
Copy the folder `chart-tab` into your mods folder (Mods page, *Open folder*), select a chart and open the **Skills** tab, which comes after the host's tabs. The rest of this page explains each part.
## A tab: `tabs.register` {#tabs}
`tabs.register` adds one tab to the chart panel. It is called from `setup`, **after** the `ratings.register` of any rating its fields read.
| Field | Rule |
|---|---|
| `id` | 1 to 32 characters among `a-z`, `0-9` and `-`, unique in your mod. The tab's key is `/`. |
| `title` | 1 to 24 characters, no control character. The tab's label. |
| `icon` | Optional: one of the 16 icons below. `layers` when absent. |
| `order` | Optional, 0 to 1000, `0` by default. Orders only compare mods' tabs with each other: they all come after the host's tabs, sorted by `order`, then by key. |
| `panels` | 1 to 8 [panels](#panels). |
The closed list of icons (lucide icon names, drawn by the game): `layers`, `info`, `trophy`, `star`, `gauge`, `activity`, `chart-bar`, `list`, `flame`, `music`, `clock`, `target`, `sparkles`, `bookmark`, `heart`, `users`. Anything else, a path included, is refused (`tab icon "x" is not an allowed icon`).
A mod adds 4 tabs at most, and 12 are shown in all: the first ones by `order`, then by key. The others are left out.
## Sections in the host's tabs: `tabs.extend` {#extend}
`tabs.extend` adds panels to one of the host's tabs. It is called from `setup` too.
```ts fragment
tabs.extend({
tab: "leaderboard",
slot: "top",
order: 10,
panels: [{ kind: "text", title: "Tip", text: "Rates change the ranking." }],
});
```
| Field | Rule |
|---|---|
| `tab` | `info`, `leaderboard` or `mods`. Training and Editor are the host's own tools and stay closed. |
| `slot` | `top`: before what the host draws; `bottom`: after it. |
| `order` | Optional, 0 to 1000. Sections of the same tab and slot sort by `order`, then by mod id. |
| `panels` | 1 to 4 [panels](#panels). |
On Info and Mods, your panels are inserted in the scrolling region. On Leaderboard, two bounded bands surround the list: only the list scrolls. A mod extends 4 times at most, and 24 sections are published in all.
## Panels {#panels}
The four panels of a rating exist here with the same shapes and limits (`metrics` and `bars` take 1 to 16 fields, `radar` 3 to 12, `timeline` 1 or 2 series with different sources, `max` finite in `(0, 1000000]`), and two more.
| `kind` | Shows | Fields |
|---|---|---|
| `metrics` | Values side by side | `title`, `fields` |
| `bars` | Values with comparison bars | `title`, `fields`, optional `max` |
| `radar` | Named axes | `title`, `fields` (3 to 12), optional `max` |
| `timeline` | The chart's density or BPM over time | `title`, `series` |
| `leaderboard` | The best plays of the selected chart under the current judgement: the ranking the Leaderboard tab has already evaluated, no extra request | `title`, `limit` (1 to 10) |
| `text` | A static note | optional `title`, `text` (1 to 280 characters, no control character, no markup, no link) |
Panel titles and field labels are 1 to 64 characters. A field is `{ label, source, unit?, decimals? }`: `unit` is at most 16 characters, `decimals` is 0 to 3 (1 by default). The `source` of a field is one of:
| `source` | Reads |
|---|---|
| `{ kind: "column", rating, column }` | A number column of the table of a rating **of the same mod**, named by its `id` (`"skills"`, not the key). The host already reads these values for the chart: at the playback rate the player chose when that rating declares panels, otherwise the stored value of the base chart. |
| `{ kind: "chart", metric }` | A real statistic of the chart: `notes`, `holds`, `holdPercent`, `averageNps`, `peakNps`, `bpmMin`, `bpmMax` or `duration`. |
| `{ kind: "leaderboard", stat }` | A fact of the local ranking: `plays` (its size), `bestPerformance` (the rating of the first play, when a performance calculator ranks the board) or `bestAccuracy` (percent; known only when the ranking is ordered by accuracy or fits on its first page). The unit is the ranking's own. |
A value that is not available shows `—`. The values are never approximated.
## Limits {#limits}
| Limit | Value |
|---|---|
| Tabs per mod / in all | 4 / 12 |
| Extensions per mod / in all | 4 / 24 |
| Tab title | 1 to 24 characters |
| Panels per tab / per extension | 1 to 8 / 1 to 4 |
| Panel title, field label | 1 to 64 characters |
| Fields | `metrics`, `bars`: 1 to 16; `radar`: 3 to 12 |
| `leaderboard` panel | 1 to 10 plays |
| `text` panel | 1 to 280 characters |
| `order` | 0 to 1000 |
| Icons | 16, closed list |
## Tabs follow their mod {#lifecycle}
A tab and its sections leave with their mod: when it is disabled, fails or is uninstalled, they disappear live. If the displayed tab disappears, the panel goes back to Info. Registering after `setup` is refused, and so is registering from a skin or a map script.
## The local leaderboard {#leaderboard}
`leaderboard.query` asks for a page of the ranking of one chart, and `leaderboard.best` for its first entry. The answer arrives later as the event `leaderboard.result`, **only to the mod that asked**. The mods thread never waits.
This mod logs the best local play of the charts a scan adds.
```ts
///
// Logs the best local play of the charts a scan just added. A request is answered later by
// the event `leaderboard.result`, and only to the mod that asked; the mod thread never waits.
//
// A mod learns chart ids from `library.chartAdd` and `library.chartsAdded` (the `Song` it
// plays carries none), so this is where its requests start.
export default defineMod({
id: "best-plays",
name: "Best Plays",
version: "1.0.0",
apiVersion: 2,
author: "You",
description: "Logs the best local play of the newly added charts.",
setup() {
ctx.on("library.chartsAdded", ({ chartIds }) => {
for (const chartId of chartIds) {
// A mod has 2 requests in flight at most: `null` means the limit is reached, so stop.
if (leaderboard.best({ chartId }) === null) break;
}
});
ctx.on("leaderboard.result", (result) => {
if (result.error) {
// English text from the host: an unknown chart, a library that is not ready…
log.warn(`chart ${result.chartId}: ${result.error}`);
return;
}
const best = result.entries[0];
if (!best) return; // nobody has played this chart
// `playerName` is null for an old replay that recorded none; `performance` is null
// when the chosen calculator could not rate the play.
const who = best.playerName ?? "unknown";
const rating = typeof best.performance === "number" ? `${best.performance.toFixed(2)} ${result.performance?.unit ?? ""}` : "no rating";
log.info(`chart ${result.chartId}: #${best.rank} ${who}, ${best.accuracy.toFixed(2)} %, ${rating} (${result.judgement}, ${result.total} plays)`);
});
},
});
```
A mod learns chart ids from `library.chartAdd` and `library.chartsAdded`, as the example does; the `Song` of a play carries none.
### The calls {#leaderboard-calls}
```ts fragment
const requestId = leaderboard.query({ chartId: 42, limit: 20, offset: 40 }); // number | null
const best = leaderboard.best({ chartId: 42 }); // the same as limit 1
```
| Field | Rule |
|---|---|
| `chartId` | The library's chart id: a positive integer. |
| `limit` | 1 to **100**, 20 by default. |
| `offset` | 0 to 100 000, 0 by default. |
`leaderboard.best` takes an **object**, `{ chartId }`, not a bare number. A field out of range, of the wrong type or unknown throws.
**The return value** is a request number, or `null` when requests pile up: **2 waiting per mod and 16 for all the mods**. `null` is not a failure; ask again later, and handle it as in the example. The host's worker also answers `null` when it cannot take the job. A request is released when its result is delivered, so a handler of `leaderboard.result` may ask for the next page at once.
| Message | Cause |
|---|---|
| `chartId must be a library chart id (a positive integer)` | A `chartId` below 1. |
| `limit must be between 1 and 100` | A `limit` out of range. |
| `offset must be at most 100000` | An `offset` out of range. |
| `only mods read the local leaderboard` | Called by a skin or a map script. |
| `local scores are unavailable` | The host has no local scores. |
### The result {#leaderboard-result}
`leaderboard.result` carries:
| Field | Meaning |
|---|---|
| `requestId` | The number the call returned. |
| `chartId`, `offset` | What you asked for. |
| `total` | The size of the whole ranking (0 when it failed). |
| `entries` | The page, in rank order. |
| `judgement` | The name of the judgement the ranking was evaluated under. |
| `performance` | `{ calculator, unit }` of the rating calculator that ranked it, or `null`. |
| `unavailableReplays` | Plays whose replay could not be read or rejudged: they are not in `total`. |
| `error` | An English message when the ranking could not be evaluated (an unknown chart, a library or workers that are unavailable), else `null`. |
An entry:
| Field | Meaning |
|---|---|
| `rank` | The place in the whole ranking, from 1. |
| `replayId` | The replay's id. |
| `playerName` | The name recorded with the play, or `null` for an older replay that recorded none. It is never the current player's name. |
| `received` | `true` for a replay imported from a file: the name is whoever the file names. |
| `accuracy` | Percent from 0 to 100, under the current judgement. |
| `performance`, `performanceNonstandard` | The calculator's rating, or `null` when it cannot be calculated; `true` when the accuracy comes from another model than the calculator's own, so it is not an official pp or SSR. |
| `maxCombo`, `misses` | From the rejudgement. |
| `tiers` | `[{ name, count }]` in the current judgement's order, the miss listed once. |
| `rate` | The playback rate the play was recorded at. |
| `modified` | Played with chart modifiers. |
| `playedAtMs` | When it was recorded, in ms since the Unix epoch. |
### What the ranking is {#ranking}
It is the interface's own ranking: every replay of the chart is **rejudged with the player's current judgement** (see [judgement sets](https://prism.am/dev/md/guides/judgement-set.md#replays-online)), rated by the chosen performance calculator, and ranked by performance when there is one. Accuracy, combo, misses and date only break ties. Abandoned plays do not count. Imported replays do, with `received`. The board is not cached: each request rejudges the chart, which is why a page is limited to 100 entries and a mod to two requests at a time.
## What you will see {#errors}
The registration errors throw in `setup`:
| Message | Cause |
|---|---|
| `tab id must be 1 to 32 characters among a-z, 0-9 and `-`, got "Skills"` | An invalid id. |
| `tab title must have 1 to 24 characters, got ""` | An empty or long title. |
| `tab icon "x" is not an allowed icon` | An icon outside the list. |
| `order must be between 0 and 1000` | An `order` out of range. |
| `panels must hold 1 to 8 panels` | No panel, or too many (1 to 4 for an extension). |
| `panel must have 1 to 16 fields` | The wrong number of fields for the panel (3 to 12 for a radar). |
| `field `Overall` reads column `x` of rating `skills`: register that rating first (`ratings.register`, same mod) and name one of its numeric columns` | A `column` source that does not name a number column of a rating registered earlier by this mod. |
| `a leaderboard panel lists 1 to 10 plays` | A `limit` out of range. |
| `panel text must have 1 to 280 characters, got ""` | An empty or long text. |
| `panel text must not contain control characters` | A line break or another control character. |
| `tab `skills` is registered twice` | The same `id` twice. |
| `a mod registers at most 4 tabs` / `a mod extends the host's tabs at most 4 times` | The fifth tab or extension. |
| `tabs.register is only available in a mod's setup` / `tabs.extend is only available in a mod's setup` | Called later, or by a skin or a map script. |
An unknown `kind`, an unknown field (`style`, `html`) or a value like `tab: "training"` fails the call: the shapes are closed.
## Pitfalls {#pitfalls}
- Reading a rating column in a tab before registering that rating: register the table and the rating first.
- Naming the rating by its key (`mod/skills`) in a `column` source: use its `id`.
- Expecting the `Song` of a play to give a chart id for `leaderboard.query`: only the library events do.
- Calling `leaderboard.query` in a loop without testing for `null`: after two requests it returns `null`.
- Passing a number to `leaderboard.best`: it takes `{ chartId }`.
- Assuming the order of the ranking is stable: it follows the player's current judgement and performance calculator.
## See also {#see-also}
- [`tabs.register`, `tabs.extend`, `leaderboard.query`, `leaderboard.best`](https://prism.am/dev/md/reference/sdk/tabs.md) and the event `leaderboard.result` in the SDK reference.
- [Add a difficulty rating](https://prism.am/dev/md/guides/rating.md): the tables and ratings whose columns a tab reads.
- [Judgement sets](https://prism.am/dev/md/guides/judgement-set.md): the judgement the ranking is evaluated under.
=====
Page: Gameplay modifiers, scroll speeds and key actions
Address: https://prism.am/dev/guides/gameplay-modifiers/
Derived from: crates/modding/src/modifiers.rs, crates/modding/src/note_mask.rs, crates/modding/src/scroll_speed.rs, crates/modding/src/controls.rs, crates/modding/src/api.rs, crates/core/src/visual_mods.rs, crates/core/src/mode/key-codes.json, content/examples/mods/modifier-set/main.ts, content/mods/lift/main.ts, content/mods/no-pause/main.ts, content/mods/scroll-etterna/main.ts
# Gameplay modifiers, scroll speeds and key actions
Declare switches for the Mods tab, scroll speed systems and key actions of a mod, with every closed list and limit Rust applies.
Three registrations let a mod add to the game's own screens without building any interface of its own: a **gameplay modifier** (a switch on the *Mods* tab of the selected chart), a **scroll speed system** (a way to choose how fast the notes travel) and a **key action** (a key the player can rebind in *Settings → Controls*). All three are declared in `setup`, and Rust validates every declaration when it is made.
## A complete example {#example}
The example mod declares one of each. It is type-checked, and the repository's tests load it through the real engine.
```ts
///
// What a mod can declare for the Mods tab and the Controls page, in one file: a modifier whose script sets the playfield's cover (the
// game draws it), a scroll speed system, and a key action the player can rebind. Every declaration is made in `setup`, never
// later, and every one is checked by Rust when it is registered: a refused call throws, and the mod fails with the reason.
export default defineMod({
id: "example.modifiers",
name: "Example modifiers",
version: "1.0.0",
apiVersion: 2,
author: "PVNG",
description: "A cover modifier, a scroll speed in screens per second and a key that shows a hint.",
setup() {
// `kind: "noteMask"` is a modifier whose script sets how the playfield is drawn: when a play starts, the game delivers
// `playfield.noteMask` with the player's value of every slider declared in `params` (clamped to its bounds), and the handler answers
// with `playfield.setNoteMask`. Here a cover on the spawn side, as tall as the slider says, with a soft edge. The numbers are in
// percent of the box height and Rust validates them; nothing runs while the play is drawn. `group` and `icon` come from closed lists;
// leave them out for the kind's own.
gameplay.register({
id: "curtain",
name: "Curtain",
description: "A cover hides the notes until they are close. Drawn only: judging and the ranking are unchanged.",
kind: "noteMask",
group: "layout",
icon: "fold-vertical",
// Keys of other modifiers (`/`): the Mods tab switches them off when this one is switched on.
conflictsWith: ["pvng.hidden/hidden"],
params: [
{ id: "height", label: "Curtain height", description: "How much of the box the curtain covers, in percent of the box height.", section: "curtain", min: 10, max: 100, step: 5, default: 50, unit: "%" },
],
});
ctx.on("playfield.noteMask", (request) => {
if (request.id !== "curtain") return;
playfield.setNoteMask({ sudden: { size: request.params.height, feather: 10 } });
});
// A scroll speed system: the player picks a number, `toMs` says how many milliseconds a note takes to travel from where it appears
// to the receptors. `travel` is the distance in screen heights (0.8 in the native playfield), so the value here is a velocity.
scrollSpeed.register({
id: "screens",
name: "Screens per second",
param: { label: "Screens/s", short: "S", min: 0.2, max: 3, step: 0.05, default: 1.1 },
toMs: (value, { travel }) => (travel / value) * 1000,
});
// A key action: listed under the mod's name in the Controls page, with `KeyH` as its default key.
controls.register({ id: "toggle-hint", name: "Show the hint", defaultKey: "KeyH" });
let shown = false;
// The hint is drawn for the length of a play only: a mod's layer must be cleared at song end.
ctx.on("game.songStart", () => {
hud.text({
id: "hint",
text: "Hint: the curtain hides the notes until they are close",
visible: false,
layout: { x: 0.5, y: 0.08, anchor: "center" },
style: { color: "#ffffff", size: 0.025 },
});
shown = false;
});
ctx.on("game.songEnd", () => hud.clear());
ctx.on("controls.action", (action) => {
if (action.id !== "toggle-hint" || !action.pressed) return;
shown = !shown;
hud.update({ id: "hint", visible: shown });
});
},
});
```
Every registered key is `/`: here `example.modifiers/curtain`, `example.modifiers/screens` and `example.modifiers/toggle-hint`.
## Rules that apply to all three {#rules}
- Only a **mod** can register them, and only in `setup`. A call from an event handler, a skin or a map script is refused.
- An id is 1 to 32 characters among `a-z`, `0-9` and `-`. A name or a description is non-empty, has no control character and fits its limit (below).
- A refused call throws in the script with the reason. If `setup` does not catch it, the mod fails and its other declarations are withdrawn.
- A disabled, failed or uninstalled mod loses its declarations at once. A choice the player made for a key that no mod provides any more does nothing.
Typical refusals:
```text
modifier id must be 1 to 32 characters among a-z, 0-9 and `-`, got "Bad Id"
gameplay.register is only available in a mod's setup
a mod registers at most 8 gameplay modifiers
```
## Gameplay modifiers {#gameplay}
```ts fragment
gameplay.register({
id: "steady",
name: "Steady",
description: "The pause key and a lost window focus do nothing during the play.",
kind: "noPause",
});
```
| Field | Rule |
|---|---|
| `id` | 1 to 32 characters, `a-z0-9-`, unique in the mod |
| `name` | 1 to 32 characters |
| `description` | 1 to 200 characters, shown when the player hovers the switch |
| `kind` | one of the kinds below |
| `group` | optional, one of `assist`, `layout`, `longNotes`, `timing`, `difficulty`, `other`; the kind's own group when absent |
| `icon` | optional, one of the 28 icons below; the kind's own icon when absent |
| `conflictsWith` | optional, at most 8 keys `/`; never the modifier's own key |
A mod registers at most 8 modifiers. The key must be unique among all mods.
### The kinds {#kinds}
The kind is **what the game does** when the player switches the modifier on. A script cannot add behaviour to a native kind and cannot add parameters to it: the game declares them for the kind. Two kinds have a script behind them: `chartTransform` (it rewrites the notes) and `noteMask` (it sets how the playfield is drawn, and declares its own parameters).
| Kind | What it does | Default group, icon | Parameters |
|---|---|---|---|
| `auto` | The game plays the chart perfectly by itself: no score, no replay. | `assist`, `bot` | none |
| `ghost` | The best play of the map (or the one picked in the leaderboard) is replayed beside the player's own, and the HUD can compare its accuracy with the player's live. Scored and recorded as usual. | `assist`, `ghost` | none |
| `fullLn` | A tap with room before the next note of its column becomes a hold. It needs the timing points and the real-time constants of the rate, which a script is not given. The play is unranked as soon as a setting differs from its default: the ranked version, with fixed settings, is built into Prism. | `longNotes`, `unfold-vertical` | several: gap, minimum and maximum length, which columns and chords convert, end snapping… |
| `chartTransform` | Your script rewrites the notes at the start of a play: see [Transforming a chart](https://prism.am/dev/md/guides/chart-transform.md). A play whose notes changed is unranked. | `other`, `sliders-horizontal` | none |
| `noteMask` | Your script sets covers and a lift for the playfield at the start of a play: see [Drawing the playfield](#note-mask). Drawn only: the chart and the judging are untouched, the play stays ranked. | `layout`, `eye` | declared by your script, in `params` |
| `noPause` | The pause key and the window losing the focus do nothing during a play. Quit, restart and Skip intro still work. No note changes, so the play stays ranked and carries no badge. It applies to a normal play only: a watched replay, a training and the visualizer pause as usual. | `other`, `shield` | none |
`mirror`, `noLn`, `rankedFullLn` and `noMines` are in the SDK type but **a mod cannot declare them**: Mirror, No long notes, the ranked Full long notes (fixed settings, no parameter) and No mines (the chart's mines are left out) are built into Prism, keys `prism/mirror`, `prism/no-ln`, `prism/full-ln` and `prism/no-mines`, and are always published first, in that order. Their plays stay ranked. Declaring one fails with:
```text
Mirror is built into Prism: a mod cannot declare it
No long notes is built into Prism: a mod cannot declare it
Full long notes is built into Prism: a mod cannot declare it
```
The shipped mods are good models: `pvng.auto`, `pvng.ghost`, `pvng.full-ln` and `pvng.no-pause` contain nothing but this declaration, `pvng.random` is the shipped `chartTransform` mod, and `pvng.hidden`, `pvng.sudden` and `pvng.lift` are the shipped `noteMask` mods. The kinds `hidden`, `sudden` and `lift` of earlier versions are gone: those three modifiers are `noteMask` mods now, with the same keys, parameters and look.
### Drawing the playfield: `noteMask` {#note-mask}
A modifier of kind `noteMask` changes **how the playfield is drawn**: a cover over the region the notes travel through, or a lift of the receptor line. When a play is prepared, the game delivers the event `playfield.noteMask` to your script with the values the player chose for your sliders, and your script answers with `playfield.setNoteMask(…)`. Rust checks every number and the renderer draws the result. Nothing of your script runs while the play is drawn, and your script cannot press a key or change a judgement: a mask only draws, so the play stays ranked.
This is the shipped *Lift*, complete:
```ts
///
// Lift is a script mod: the receptor line and the judgement line are raised toward the spawn side, so the notes travel a
// shorter distance and the space behind the receptors grows. When a play is prepared the game delivers `playfield.noteMask`
// with the player's value of the slider declared below, and this script answers with `playfield.setNoteMask`: a lift, in percent
// of the box height. Rust validates the number (the lines never pass the spawn edge) and the renderer draws it; no script runs
// while the play is drawn. Judging stays on the song's time and the ranking is unchanged, and the replay records the number,
// so a watched replay looks the same without this mod.
export default defineMod({
id: "pvng.lift",
name: "Lift",
version: "2.0.0",
apiVersion: 2,
loadOrder: 394,
author: "PVNG",
description: "A Mods tab switch that raises the receptor line toward the spawn side.",
setup() {
gameplay.register({
id: "lift",
name: "Lift",
description: "The receptor and judgement lines are raised. Drawn only: judging and the ranking are unchanged.",
kind: "noteMask",
group: "layout",
icon: "move-vertical",
params: [
{ id: "liftHeight", label: "Lift height", description: "How far the receptor line is raised, in percent of the box height.", section: "lift", min: 0, max: 50, step: 1, default: 20, unit: "%" },
],
});
ctx.on("playfield.noteMask", (request) => {
if (request.id !== "lift") return;
playfield.setNoteMask({ lift: request.params.liftHeight });
});
},
});
```
Three things to see in it:
- `params` declares the sliders of the modifier. They appear on the Mods tab, and the player's values are kept in the setting `gameplayModParams` under the modifier's key. A modifier declares at most 8, and only a `noteMask` modifier may declare any.
- The event carries `{ id, params }`: the `id` of the modifier the player switched on (one handler serves every modifier of the mod, so test it) and the value of each slider by `id`. The game already clamped the player's saved value to your `min` and `max`, or used your `default`; an `id` you did not declare never arrives.
- `playfield.setNoteMask` only works inside that handler. A handler that never calls it changes nothing.
A declared slider is checked like everything else:
| Field | Rule |
|---|---|
| `id` | 1 to 32 letters and digits, the first a letter, unique in the modifier; the key of the saved value (the interface translates `chartparam..label` and `.description` when it has them, else it shows your English texts) |
| `label` | 1 to 32 characters |
| `description` | 1 to 200 characters |
| `section` | 1 to 32 characters, `a-z0-9-`; the sliders of one section are listed together |
| `min`, `max`, `step`, `default` | integers, `-1000000 <= min < max <= 1000000`, `1 <= step <= max - min`, `min <= default <= max` |
| `unit` | optional, `%` or `ms` |
What a mask can say. Every size is a **percent of the height of the lanes' box**, an absent part is drawn as the skin draws it, and a number is rounded to the nearest whole percent:
| Part | Values | What is drawn |
|---|---|---|
| `sudden: { size, feather }` | `size` 10 to 100, `feather` 0 to 50 | A cover on the spawn side: the notes appear from behind it. It never reaches the receptors and replaces the skin's lane cover. The last `feather` percent of its far edge fades out. |
| `hidden: { size, feather }` | same | The same cover hung from the receptors of each lane toward the spawn side: the notes fade out as they approach. |
| `lift` | 0 to 50 (0: not raised) | The receptor line and the judgement line are raised toward the spawn side, never past the spawn edge: the notes travel a shorter distance. Judging stays on the song's time. |
The colour and the opacity of a cover come from the skin (`laneCoverColor`, `laneCoverOpacity`); an opacity of 0 turns it off.
What Rust does with a mask:
- A number must be finite and inside its range. An out-of-range number, `NaN`, an infinity, an unknown field or a wrong type throws in your script with the reason. The first refusal drops the whole modification of your mod, even if your script catches the exception and calls again: the play is drawn without it and the player sees a notice. With several valid calls in one handler, the last one wins.
- A handler that is missing, throws, runs out of its execution budget or out of memory is dropped the same way. The other modifiers and the play are untouched.
- Two mods of one play cannot set the same part (`sudden`, `hidden`, `lift`): the one that loads later is dropped with a notice. A mod that sets another part is not in conflict.
- The result is copied **once**, when the play starts, into what the renderer draws and what the replay records (`chartMods.visual`). A mask is therefore the same for the whole play; it is not a function of time. A replay is drawn the same without your mod installed.
Typical refusals:
```text
playfield.setNoteMask refused the mask: sudden.size 101 is outside 10..100
playfield.setNoteMask refused the mask: lift is not a finite number
Curtain: sets `sudden`, which a mod before it already set; the play goes without it
only a `noteMask` modifier declares `params`: the game declares the parameters of the other kinds
```
### Groups and icons {#groups-icons}
`group` is where the Mods tab lists the modifier. `icon` is the name of a [Lucide](https://lucide.dev) icon from a closed list, because the interface draws these and nothing else:
```text
bot, ghost, flip-horizontal-2, shuffle, minus, unfold-vertical, fold-vertical, chevrons-down-up,
align-vertical-space-between, ruler, gauge, timer, zap, dices, repeat, eye, sliders-horizontal,
swords, feather, flame, shield, skull, audio-lines, rows-3, move-vertical, equal,
arrow-down-to-line, between-horizontal-start
```
A name outside the list is refused: `modifier icon "star" is not an allowed icon`. A group outside the list gives `modifier group "x" is not one of assist, layout, longNotes, timing, difficulty, other`.
### Conflicts {#conflicts}
`conflictsWith` lists keys of modifiers that cannot be combined with this one. The Mods tab switches the others off when the player switches this one on. If a selection holds both anyway, the game applies its own rule. Each entry must look like `/`; the other modifier does not have to exist. The built-in `prism/no-ln` and `prism/full-ln` name each other and `pvng.full-ln/full-ln`, and the reverse.
### What the game publishes {#published}
The `gameplayMods` data the interface reads has, for each modifier: `key`, `modId`, `name`, `description`, `kind`, `group`, `icon`, `conflictsWith` and `params`. The player's choice is the setting `gameplayMods` (the chosen keys); the values of the parameters are the setting `gameplayModParams`, checked (bounds, step, choices) when a play starts.
## Scroll speed systems {#scroll-speed}
A system is a named parameter, such as osu!mania's scroll speed or Etterna's C-mod, and the function that turns each of its values into the game's own **scroll time**: the milliseconds a note takes to go from where it appears to the receptors. The game plays with that time only.
```ts fragment
scrollSpeed.register({
id: "c-mod",
name: "Etterna",
param: { label: "C-mod", short: "C", min: 120, max: 1800, step: 5, default: 200 },
toMs: (cmod, { travel }) => ((travel * 480) / ((64 * cmod) / 60)) * 1000,
});
```
| Field | Rule |
|---|---|
| `id` | 1 to 32 characters, `a-z0-9-`, unique in the mod |
| `name` | 1 to 64 characters |
| `param.label` | 1 to 32 characters |
| `param.short` | optional, 1 to 8 characters written before the value (`C` gives `C700`); without it the game writes the label, a space and the value |
| `param.min`, `max`, `step`, `default` | finite, `min < max`, `0 < step <= max - min`, `min <= default <= max` |
| `toMs(value, context)` | a function; returns the scroll time in milliseconds |
- A mod registers at most 8 systems.
- The suggested slider grid is `min` to `max` by `step`, and it has at most 4096 values.
- `context.travel` is the distance a note covers during the scroll time, in screen heights: 0.8 in the native playfield. Everything else (pixels, the position of the receptors, the chart) cancels out, so a conversion only needs this number.
- After the mods load, the game calls `toMs` for every value of the grid. A value whose call throws, or returns something other than a positive finite number, is left out of the grid. If no value converts, the system is dropped and the mod's log says why.
- A value the player types by hand is converted on demand by the same function; it is not clamped to the grid.
## Key actions {#controls}
`controls.register` adds an action to *Settings → Controls*, listed under the name of your mod, with a default key. The `controls.action` event then tells the mod when the key goes down or up during a play.
| Field | Rule |
|---|---|
| `id` | 1 to 32 characters, `a-z0-9-`, unique in the mod |
| `name` | 1 to 64 characters, shown in Controls |
| `defaultKey` | a physical key `code` accepted by the game (`KeyA`, `Space`, `F5`…): the inventory in `crates/core/src/mode/key-codes.json` |
- A mod registers at most 32 actions.
- The event carries `{ id, pressed, timeUs }`. It is delivered **only to the mod that declared the action**, with the song time in microseconds.
- Events travel through a bounded queue to the `mods` thread. A full queue can lose events: do not use this to hold a scoring state or anything critical.
- The player's binding persists even if the mod is disabled, and only the actions of active mods are offered. A change takes effect at the next play. Game inputs and replays are never replaced by a mod action.
```text
action defaultKey must be an accepted physical key code, got "Hyper"
action id is registered twice
a mod registers at most 32 actions
```
## Pitfalls {#pitfalls}
- Choosing `kind` is not a way to run your own code in the game. For anything that is neither `chartTransform` nor `noteMask`, the declaration is all there is: look at `content/mods/no-pause/main.ts`.
- A `noteMask` handler runs once per play, before it starts: it cannot follow the song, the beat or the player. Compute the numbers from `request.params` and answer.
- Do not register in `ctx.on(...)` handlers: the registries are closed once the mods have loaded.
- A `group` or an `icon` that looks right but is not in the list fails the whole `setup`: copy the names from this page.
- A `toMs` that depends on anything but its two arguments (a global, the time) gives a grid that no longer matches what the game plays.
## Reference {#reference}
- [`gameplay.register`](https://prism.am/dev/md/reference/sdk/gameplay.md#gameplay-register), [`scrollSpeed.register`](https://prism.am/dev/md/reference/sdk/gameplay.md#scrollspeed-register), [`controls.register`](https://prism.am/dev/md/reference/sdk/game.md#controls-register), [`playfield.setNoteMask`](https://prism.am/dev/md/reference/sdk/game.md#playfield-setnotemask) and the events [`controls.action`](https://prism.am/dev/md/reference/sdk/events.md#event-controls-action) and [`playfield.noteMask`](https://prism.am/dev/md/reference/sdk/events.md#event-playfield-notemask).
- Next: [Transforming a chart](https://prism.am/dev/md/guides/chart-transform.md), the modifier kind that rewrites the notes.
=====
Page: Transforming a chart
Address: https://prism.am/dev/guides/chart-transform/
Derived from: crates/modding/src/transform.rs, crates/modding/src/modifiers.rs, crates/modding/src/runtime.rs, crates/modding/src/api.rs, crates/core/src/scripted_notes.rs, crates/core/src/chart_mods.rs, content/mods/random/main.ts, content/examples/mods/thin-chords/main.ts, crates/modding/tests/chart_transform.rs
# Transforming a chart
Write a modifier that rewrites the notes of a chart at the start of a play, with typed arrays, and see exactly what Rust accepts, refuses and records in the replay.
A modifier of kind `chartTransform` changes **which notes the player plays**: it can shuffle the columns, turn holds into taps, thin out chords, add notes. At the start of a play the game hands your script a copy of the notes, and your script hands back a complete replacement. Rust checks that replacement before anything is played: a replacement that is not a valid chart is **dropped**, and the map plays as it was.
Your script never sees the play in progress, never touches the inputs or the judgement, and never writes code into the replay. It exchanges a buffer of data, and only that.
## A complete example {#example}
*Thin chords* keeps at most two notes of every chord. It reads the notes, picks the ones to keep and builds four new arrays. Rust loads this exact file in a test, runs it on a chart with chords, and checks the notes that come out.
```ts
///
// Thin chords: a chart transformation that keeps at most two notes of every chord (the notes that start at the same instant): the first two
// in the order the game lists them. The game delivers `chart.transform` to the mod when a play starts; the mod reads the notes of the chart as four
// typed arrays and hands back a full replacement. Rust validates the replacement: a refused one is dropped and the map plays as it
// was. Removing notes can never overlap anything, so this one is always accepted. The play it changes is unranked and its replay
// stores the resulting notes, never this script.
const MAX_PER_CHORD = 2;
export default defineMod({
id: "example.thin-chords",
name: "Thin chords",
version: "1.0.0",
apiVersion: 2,
author: "PVNG",
description: "A Mods tab switch that keeps at most two notes of every chord.",
setup() {
gameplay.register({
id: "thin-chords",
name: "Thin chords",
description: "Chords of three notes or more keep only their first two notes.",
kind: "chartTransform",
group: "difficulty",
icon: "minus",
});
ctx.on("chart.transform", (request) => {
// One handler receives every modifier of the mod: answer only yours.
if (request.id !== "thin-chords") return;
const notes = chart.getNotes();
// The times are little-endian doubles. A view must start on a multiple of 8 bytes: take `byteOffset` into account.
const start = new Float64Array(notes.startUs.buffer, notes.startUs.byteOffset, notes.count);
const end = new Float64Array(notes.endUs.buffer, notes.endUs.byteOffset, notes.count);
// The notes come sorted by start time: a chord is a run of equal start times.
const kept: number[] = [];
let rank = 0;
for (let index = 0; index < notes.count; index++) {
rank = index > 0 && start[index] === start[index - 1] ? rank + 1 : 0;
if (rank < MAX_PER_CHORD) kept.push(index);
}
// Four new arrays, one entry per kept note. A tap or a mine keeps `endUs` at 0.
const startUs = new Float64Array(kept.length);
const endUs = new Float64Array(kept.length);
const column = new Uint8Array(kept.length);
const kind = new Uint8Array(kept.length);
kept.forEach((from, to) => {
startUs[to] = start[from];
endUs[to] = end[from];
column[to] = notes.column[from];
kind[to] = notes.kind[from];
});
chart.setNotes({ startUs: new Uint8Array(startUs.buffer), endUs: new Uint8Array(endUs.buffer), column, kind });
});
},
});
```
Three things to see in it:
- The mod registers a modifier with `gameplay.register({ kind: "chartTransform", … })` and listens to `chart.transform` with `ctx.on`. The event carries `{ id }`, the id of the modifier the player switched on: a mod with several modifiers has one handler and tests `request.id`.
- `chart.getNotes()` and `chart.setNotes()` only work **inside** that handler.
- The times are `Float64Array` data read from and written to bytes.
## How a play goes {#flow}
1. The player switches on one or more modifiers on the *Mods* tab and starts a play.
2. The game builds the chart of the play and, **before the play starts**, asks the `mods` thread to run the selected `chartTransform` modifiers. It waits for the answer the way it waits for a skin's `setup`.
3. The modifiers run **in load order** (the `loadOrder` of each mod), not in the order the player picked them. The first gets the original chart's notes; each next one gets the notes the previous one left.
4. For each one, the game offers the notes, delivers `chart.transform` to the mod, and validates what `chart.setNotes` received.
5. The result applies to the chart **at 1x, before the playback rate**. Times stay in microseconds of the 1x chart. The native modifiers (Mirror, No long notes, Full long notes…) apply after the rate.
If the final notes are the same as the original's, nothing is recorded and the play stays ranked. If they differ, the play is **unranked** and carries the notes (see [Replays](#replays)).
## Reading the notes: `chart.getNotes` {#get-notes}
`chart.getNotes()` returns:
| Field | Type | Meaning |
|---|---|---|
| `keys` | number | Number of columns. Every note's column is below it. |
| `count` | number | Number of notes in each array. |
| `seed` | number | An integer the game draws for this play and this mod (see [Determinism](#determinism)). |
| `durationUs` | number | Where the map ends, in microseconds. No note may end later. |
| `startUs` | `Uint8Array` | `count` little-endian `f64`: the start time of each note, in microseconds. |
| `endUs` | `Uint8Array` | `count` little-endian `f64`: the end time of a hold or a burst, `0` for a tap or a mine. |
| `column` | `Uint8Array` | `count` bytes: the 0-based column of each note. |
| `kind` | `Uint8Array` | `count` bytes: `0` tap, `1` hold, `2` burst, `3` mine. |
The notes come sorted by start time. They are a **copy**: changing the arrays changes nothing until you call `chart.setNotes`.
The two time arrays are bytes, not numbers. To read them, build a `Float64Array` view over the same memory, and use `byteOffset` because the view must start on a multiple of 8 bytes:
```ts fragment
const notes = chart.getNotes();
const start = new Float64Array(notes.startUs.buffer, notes.startUs.byteOffset, notes.count);
const firstNote = notes.count > 0 ? start[0] : null;
```
To change times, work on a copy (`Float64Array.from(view)`, or new arrays as the *Thin chords* example above does).
## Writing the notes: `chart.setNotes` {#set-notes}
`chart.setNotes({ startUs, endUs, column, kind })` takes the same four arrays as `Uint8Array`, with a count of your choice:
- The number of notes can change, up to **100 000** (a real marathon map has about 50 000).
- The notes can come in any order: the game sorts them by start time (a stable sort).
- Times are rounded to whole microseconds. Hitsound indices are dropped (the game plays none).
- You can call `chart.setNotes` several times in one handler: the last valid call wins, but see below what a refused call does.
- If your handler never calls it, nothing changes.
`startUs` and `endUs` are **bytes of doubles**. Build a `Float64Array` and pass `new Uint8Array(array.buffer)`. Passing the `Float64Array` itself is a type error:
```ts fragment error=TS2322
ctx.on("chart.transform", () => {
const notes = chart.getNotes();
const start = new Float64Array(notes.count);
chart.setNotes({ startUs: start, endUs: notes.endUs, column: notes.column, kind: notes.kind });
});
```
### What Rust validates {#validation}
The buffer is accepted only if every note is valid and the chart stays one the game's own loader would accept. Any of these refuses it, with a reason:
| Rule | Message (the part you will read) |
|---|---|
| at most 100 000 notes | `N notes exceed the limit of 100000` |
| `startUs` and `endUs` hold 8 bytes per note, `column` and `kind` one, counted against `kind.length` | `` `column` holds 3 bytes, 4 expected for 4 notes `` |
| times are finite and exact (at most 2^53) | `note 3: start NaN is not a finite time` |
| `kind` is 0, 1, 2 or 3 | `note 0: kind 9 is not 0 (tap), 1 (hold), 2 (burst) or 3 (mine)` |
| a tap or a mine ends at `0` | ``note 0: a tap or a mine has no end time, `endUs` must be 0 (got 5)`` |
| a hold or a burst ends after it starts | `note 1: the end 400000 comes before the start 500000` and `note 1: a hold or a burst must end after it starts (500000 us)` |
| the column is below `keys` | `note 2: column 4 is outside the 4 columns` |
| the note stays inside the map: from `min(0, first original note)` to `durationUs` | `note 3: 6000000..6000000 us is outside the map (0..5000000 us)` |
| no two notes start at the same instant in a column | `note 3: two notes at 1000000 us in column 2` |
| no note starts before the previous note of its column ends | `note 2: starts at 600000 us in column 1 before the note before it ends (900000 us)` |
### What happens to a refused buffer {#refused}
A refused call **throws in your script** with the reason, prefixed by `chart.setNotes refused the buffer:`. The game remembers the first refusal: even if your script catches the exception and submits another buffer, the whole modification is dropped. The play then goes on without it, the player sees a notice and the mod's log gets a warning with the reason:
```text
Thin chords: failed (… chart.setNotes refused the buffer: note 3: two notes at 1000000 us in column 2); the map plays without it
Thin chords: chart.setNotes refused the buffer: note 3: two notes at 1000000 us in column 2; the map plays without it
```
The first form is an exception your handler did not catch; the second is one it caught. The reason is the same.
A mod that throws, runs out of its execution budget (30 ms per handler call by default) or of memory (16 MiB), or that has no `chart.transform` handler at all, is dropped the same way. Only **that** modification is dropped: the other modifiers and the map are untouched, and the play never starts on a half-valid chart. A failure does not disable your mod at once; three failures in a row, or three timeouts, do disable it for the session.
Calls outside the handler fail at once: ``chart.getNotes is only available inside a `chart.transform` handler``, and the same for `chart.setNotes`. A mod only gets the notes of the delivery made to it.
## What stays native {#native}
Mirror, *No long notes* and the ranked *Full long notes* are built into Prism (`prism/mirror`, `prism/no-ln`, `prism/full-ln`): the game applies them itself after the rate, and a play with them stays ranked. A script that turns every hold into a tap leaves the same notes as *No long notes*, but they are recorded as `scripted`, and that play is unranked. Full long notes is native because it needs the timing points and the real-time constants of the rate, which `chart.getNotes()` does not give. The shipped `pvng.full-ln` mod is the same modifier with settings the player tunes (see [Gameplay modifiers](https://prism.am/dev/md/guides/gameplay-modifiers.md#conflicts)).
## Determinism and the seed {#determinism}
`notes.seed` is an integer the game draws for each play. It is mixed with the key of your modifier, so two mods in the same play never shuffle with the same numbers, and it is different at every launch. Use it to make a shuffle that is random for the player yet reproducible inside one run: the same seed must give the same notes.
The shipped *Random* does that with a small seeded generator (mulberry32) and a Fisher-Yates shuffle of the columns, never the identity:
```ts
/** A small seeded generator (mulberry32): the same seed always gives the same numbers. */
function generator(seed: number): () => number {
let state = seed >>> 0;
return () => {
state = (state + 0x6d2b79f5) >>> 0;
let t = state;
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
/** `result[c]` is where column `c` goes: a Fisher-Yates shuffle, never the identity when there are two columns or more. */
function permutation(keys: number, seed: number): number[] {
const random = generator(seed);
const columns = Array.from({ length: keys }, (_, column) => column);
if (keys < 2) return columns;
for (let attempt = 0; attempt < 64; attempt++) {
for (let index = keys - 1; index > 0; index--) {
const other = Math.floor(random() * (index + 1));
[columns[index], columns[other]] = [columns[other], columns[index]];
}
if (columns.some((column, index) => column !== index)) return columns;
}
columns.push(columns.shift() as number);
return columns;
}
```
In the handler, `const target = permutation(notes.keys, notes.seed);` gives where each column goes, and `notes.column.map((column) => target[column])` rewrites the column array.
Rules for a transformation that behaves:
- Make it a pure function of the notes and of `seed`. Do not use `Math.random()` or the clock: the replay would still be exact, but you could not reproduce a result to debug it.
- Do not keep state between plays. The handler runs for every play with the modifier on.
- Keep it linear. A map has up to 100 000 notes and the handler has a 30 ms budget by default: loop over typed arrays, allocate once, never create an object per note. Measured in an unoptimized test build, one transformation takes about 0.5 ms for 500 notes, 5 ms for 5 000 and 42 to 58 ms for 50 000; the release build was not measured.
## Replays {#replays}
The replay of a play whose notes changed records the **resulting notes**, not your script, not the seed: `chartMods.scripted` holds the mods that ran, in order (key, name, version, at most 8) and the final notes of the 1x chart, delta-coded and in base64. The replay plays back **without your mod installed**: the recording alone rebuilds the chart, with the same checks as a fresh submission. See [`.pvreplay`](https://prism.am/dev/md/formats/pvreplay.md).
That is also why your script cannot cheat the ranking: any change of the notes is recorded and unranks the play, and a script that returns the same notes leaves the play ranked. No script can make a ranked No long notes or Full long notes play: its notes are always recorded as its own.
## Pitfalls {#pitfalls}
- `notes.startUs.map(...)` maps **bytes**, not times. Always go through a `Float64Array`.
- `new Float64Array(notes.startUs.buffer, 0, count)` is wrong when `byteOffset` is not 0. Pass `notes.startUs.byteOffset`.
- Moving a note in time can overlap its column. After a shift, check the end of the previous note of the column, or the whole buffer is refused.
- A hold whose end passes `durationUs` is refused: clamp it.
- Mirror, No long notes and the ranked Full long notes cannot be scripts: they are native (`prism/mirror`, `prism/no-ln`, `prism/full-ln`) so the play stays ranked. Do not register a modifier of kind `mirror`, `noLn` or `rankedFullLn`.
- One handler serves every modifier of the mod: `if (request.id !== "yours") return;`.
## Reference {#reference}
- [`chart.getNotes`](https://prism.am/dev/md/reference/sdk/gameplay.md#chart-getnotes), [`chart.setNotes`](https://prism.am/dev/md/reference/sdk/gameplay.md#chart-setnotes) and the event [`chart.transform`](https://prism.am/dev/md/reference/sdk/events.md#event-chart-transform).
- [`gameplay.register`](https://prism.am/dev/md/reference/sdk/gameplay.md#gameplay-register) and the other kinds: [Gameplay modifiers](https://prism.am/dev/md/guides/gameplay-modifiers.md).
- [The `.pvmod` format](https://prism.am/dev/md/formats/pvmod.md) to share your mod.
=====
Page: Adding a download source or mirror
Address: https://prism.am/dev/guides/download-source/
Derived from: crates/downloader/src/declared.rs, crates/downloader/src/bridge.rs, crates/downloader/src/credentials.rs, crates/modding/src/downloads.rs, crates/modding/src/api.rs, content/examples/mods/download-sources/main.ts, content/examples/mods/download-bridge/main.ts, crates/modding/tests/downloads.rs, crates/modding/tests/bridge.rs
# Adding a download source or mirror
Let the Download page search a new site, either with a declaration (URL templates and JSON paths) or with a bridge (pure functions), without your mod ever touching the network.
A mod can add to the Download page a **mirror** for osu! beatmapsets, or a whole **source**: a tab that searches a site, lists its sets and downloads them. Your mod does not do the network I/O. It *describes* the site, and the game makes every request itself.
There are two ways to describe it:
| | `downloads.register` | `downloads.registerBridge` |
|---|---|---|
| You write | data: URL templates, JSON paths, hosts, a rate | three pure functions: `search`, `onResponse`, `action` |
| Requests | one GET per page of results, one GET per file | POST, forms, XML or HTML answers, several requests chained (search, then detail, then file) |
| Result | a mirror or a source | a source |
| Use it when | the site answers JSON to a GET | the declaration cannot say what the site needs |
Start with the declaration. Move to a bridge only for what it cannot describe.
## What the player sees and controls {#player}
Both need the `network` permission in `defineMod`: `permissions: ["network"]`. Without it, the registration is refused:
```text
`downloads.register` needs the `network` permission: declare `permissions: ["network"]`
```
- The **Mods** page shows a `network` badge, the **hosts** your mod will contact, and a switch ("Allow it to add download mirrors and sources"). The player can take the permission away mod by mod (the setting `networkDenied`): your declarations disappear at once, as if the mod was off.
- The **Download** page lists a mod source behind **More sources**, grouped by the mod, with a banner "Source provided by the mod … It contacts: …" and a button that turns the source off. The button is only there when some mod provides a source.
- **Settings → Library → Downloads** holds an ordered list of mirrors (the game's own and the mods'), a switch for each mirror or source, and the field where the player saves the token of a source that asks for one.
- Disabling, failing or uninstalling your mod removes its mirrors and sources at once.
- The three settings `networkDenied`, `downloadMirrorOrder` and `downloadDisabled` name what is installed on this machine, so they are left out of the settings export.
## A declared mirror and source {#example}
The example declares both. It uses `example.org`, a domain reserved for documentation: nothing is served there, so the repository's tests run these declarations against recorded answers, with no network.
```ts
///
// Adds two things to the Download page, described as data only: a mirror for osu! beatmapsets and a
// source of its own (a tab). The mod never touches the network: the game makes every request itself,
// only on the hosts listed below (HTTPS, no port, redirects re-checked), at the rate declared here,
// and shows these hosts to the player on the Mods page and in the Download tab. The player can take the
// `network` permission away or turn each mirror or source off.
//
// `example.org` is reserved for documentation: nothing is served there. Replace the hosts and the
// field paths with those of a real service you are allowed to use.
//
// The answers these declarations read are recorded in crates/downloader/tests/fixtures
// (mod_source_search.json, osu_direct_search.json): the tests of the repository run the declarations below against
// them with a fake transport, no network involved.
export default defineMod({
id: "example.download-sources",
name: "Example download sources",
version: "1.0.0",
apiVersion: 2,
author: "PVNG",
description: "A mirror for osu! sets and a source of its own, declared as data (fictional hosts).",
permissions: ["network"],
setup() {
// One more mirror for osu! beatmapsets. It answers like osu.direct or catboy.best (osu! API v2
// beatmapset objects), so `format: "osu"` reads it as it is. It joins the built-in mirrors after
// them, in the player's order (Settings > Library > Downloads).
downloads.register({
id: "mirror",
name: "Example mirror",
description: "A fictional osu! mirror.",
site: "https://mirror.example.org",
kind: "mirror",
target: "osu",
hosts: ["mirror.example.org"],
rateLimit: 30,
search: {
url: "https://mirror.example.org/api/search",
// `{query}` is the typed text (always encoded by the game); a group in brackets is written only
// when every variable inside has a value.
params: { query: "{query}[ cs>={keysMin}][ cs<={keysMax}]", amount: "{limit}", offset: "{offset}" },
paging: { kind: "offset", size: 20 },
response: { format: "osu" },
},
download: { url: "https://mirror.example.org/d/{id}" },
});
// A whole source: its own tab, a search, a list of sets, and a zip per set. The service's answer is
// mapped field by field with simple JSON paths; ids may be texts. `auth` makes the game ask the
// player for a token in the settings and send it, in `Authorization: Bearer`, on downloads only.
downloads.register({
id: "maps",
name: "Example maps",
description: "A fictional source of mania sets.",
site: "https://maps.example.org",
kind: "source",
hosts: ["api.example.org", "files.example.org"],
rateLimit: 60,
auth: { kind: "token", scope: "download" },
search: {
url: "https://api.example.org/v1/search",
params: {
q: "{query}",
min_keys: "{keysMin}",
max_keys: "{keysMax}",
order: "{sort}",
rank: "{status}",
offset: "{offset}",
limit: "{limit}",
},
sorts: { newest: "date", plays: "plays", stars: "difficulty" },
statuses: { ranked: "ranked", loved: "loved" },
paging: { kind: "offset", size: 20 },
response: {
format: "mapped",
results: "data.items",
total: "data.total",
item: {
id: "uuid",
title: "title",
artist: "artist",
creator: "mapper",
status: "state",
bpm: "bpm",
playCount: "plays",
cover: "images.card",
difficulties: { path: "charts", name: "name", keys: "keys", stars: "stars", length: "seconds", only: { path: "mode", equals: "mania" } },
},
},
},
// The address of the zip comes from each result (it must be on one of the hosts above).
download: { urlField: "files.zip" },
});
},
});
```
A mirror adds one more server for osu! beatmapsets: it joins the game's own mirrors after them, in the order the player sets. A source adds a tab.
## What a declaration contains {#declaration}
| Field | Rule |
|---|---|
| `id` | 1 to 32 characters, `a-z0-9-`; the published key is `/` |
| `name` | 1 to 32 characters; shown on the page and in Settings |
| `description` | optional, 1 to 200 characters |
| `site` | optional, an `https://` address (256 characters at most), shown so the player can read the site's terms |
| `kind` | `"mirror"` (a server for osu! beatmapsets) or `"source"` (a tab) |
| `target` | a mirror names what it serves: `"osu"`, the only value. A source has none. |
| `hosts` | the **allow-list**: 1 to 8 exact lowercase DNS names (see below) |
| `rateLimit` | requests per minute, 1 to 120, 30 by default |
| `auth` | optional, where the player's token goes (see below) |
| `search` | how to list sets. A source needs it; a mirror may leave it out and only serve files. |
| `download` | how to fetch a set: `url` (a template with `{id}`) **or** `urlField` (a path to the file's URL in the listed result) |
A mod registers at most **4** downloads (declarations and bridges together), and all mods together at most 64. The key must be unique.
### Hosts {#hosts}
`hosts` are bare names: no scheme, port, path or wildcard. Every one must be lowercase ASCII, have at least two labels, and not be an IP address or a local name (`local`, `localhost`, `internal`, `lan`, `intranet`, `home`, `corp`, `*.home.arpa`). Duplicates are refused. Every URL your declaration writes, every URL read from an answer and every cover picture is checked against this list before it is sent, and only `https` goes out. A name that resolves to a private, loopback or link-local address is refused when it resolves.
### The URL template {#template}
A template is text with `{variables}` and optional groups in brackets. The text of a variable is always percent-encoded by the game, and numbers are formatted by it. There is no other variable.
| Variable | Value |
|---|---|
| `{query}` | the typed text |
| `{status}`, `{sort}` | the value your `statuses` and `sorts` tables give for the player's choice |
| `{offset}`, `{page}`, `{cursor}`, `{limit}` | paging (see below) |
| `{keysMin}`, `{keysMax}`, `{starsMin}`, `{starsMax}`, `{bpmMin}`, `{bpmMax}`, `{lengthMin}`, `{lengthMax}`, `{genre}`, `{language}` | the Download page's filters |
| `{id}` | the set's id, **only** in `download.url` |
- A parameter whose variable has no value is left out.
- A group `[ …]` is written only when every variable inside has a value: `{query}[ cs>={keysMin}]`.
- `\[`, `\]`, `\{`, `\}` and `\\` write the character itself.
- A filter whose variables are in the request is sent to the server; the others only narrow the results already loaded, and the page says so.
- `search.url` is a plain address on a declared host: no query, no variable. Put the query in `params` (at most 16, each name 1 to 32 characters among letters, digits and `_-.[]`). Templates are at most 256 characters.
`sorts` maps the game's sort ids (`newest`, `updated`, `plays`, `favourites`, `title`, `artist`, `stars`; `relevance` needs no entry) to your service's own value, and `statuses` maps the status ids (`all`, `ranked`, `loved`, `qualified`, `pending`, `graveyard`) the same way. A table is non-empty if and only if some parameter names `{sort}` or `{status}`.
### Paging {#paging}
`paging: { kind, size, first? }` has `size` from 1 to 100 (also the value of `{limit}`), and a kind:
| Kind | Variable | Meaning |
|---|---|---|
| `offset` | `{offset}` | results already read |
| `page` | `{page}` | page number from `first` (0 or 1, 1 by default) |
| `cursor` | `{cursor}` | what the previous answer's `response.nextCursor` path held |
The matching variable must appear in a parameter. Without `paging` the listing is a single page. A mirror pages by `offset` or `page` only, because its listing is merged with the other mirrors' by position.
### Reading the answer {#response}
`response.format` is `"osu"` (an array of osu! API v2 beatmapset objects, which is what osu! mirrors answer; only the mania difficulties are kept) or `"mapped"` (field by field, with `item`).
For `mapped`: `results` is the path of the array (the answer itself when absent), `total` the path of the match count, and `item` maps every field with a **simple JSON path**: `a.b[0].c`. A path is 1 to 128 characters and at most 8 steps; a key is 1 to 48 characters among letters, digits, `_` and `-`; an index is below 10 000. There is no filter, wildcard or script, and a key that contains a dot or another character cannot be read.
| `item` field | Meaning |
|---|---|
| `id`, `title` | required. An id is a number or a text of at most 64 characters. |
| `artist`, `creator`, `status`, `bpm`, `playCount`, `favourites` | optional |
| `cover` | optional, the path of a cover URL, which must be on a declared host |
| `difficulties` | optional: `{ path, name?, keys, stars?, length?, only? }`; `keys` is an integer from 1 to 18, `length` is in seconds, and `only: { path, equals }` keeps the difficulties whose path equals the text (compared as text, ignoring case: `3` equals `"3"`) |
Every value is typed and bounded by Rust (texts cut, numbers finite, 1 to 18 keys). A result that cannot be read is skipped, never invented. A mirror needs a numeric id.
### The file {#file}
`download.url` is a template with `{id}` (and nothing else) for a mirror and for a source whose files live at a fixed pattern. `download.urlField` is a path read from the listed result, for a source whose answer gives each file's address; it needs the `mapped` format and a source. The answer must be a zip that starts with `PK`, holds at least one chart the game can read, and is at most 512 MiB; it is extracted safely (absolute paths, `..` and links refused) and installed like any other source, recorded as `mod:/`.
### The token {#auth}
`auth: { kind: "token", header?, scheme?, scope? }` makes the game ask the player for a token in Settings and send it for you.
| Field | Rule |
|---|---|
| `header` | `Authorization` (the default), `X-API-Key` or `X-Auth-Token` |
| `scheme` | up to 16 letters written before the token: `Bearer` by default for `Authorization`, none for the others; `""` sends the token alone |
| `scope` | `"all"` (the default): the listing and the downloads carry it. `"download"`: the listing is public and only the files carry it. |
The token is 8 to 4096 visible characters. It is kept by the game, in its own file for each source (encrypted with Windows DPAPI, with an entropy of its own), never in the settings the interface keeps. Your script never receives it, it never appears in an event, an error message or a log, and covers carry none. It is sent only in the declared header, only to your declared hosts, and the header is dropped as soon as a redirect changes the host. `auth.header`, `scheme` and `scope` are only for `kind: "token"`; with `kind: "none"` they are refused.
### What the game guarantees {#host-guarantees}
- HTTPS only, declared hosts only, no port. Redirects are followed by hand, **3 at most**, and each hop is checked again against the allow-list; a hop to an undeclared host is refused, and the token header is dropped as soon as the host changes.
- Sizes: 8 MiB of JSON, 512 MiB per set, 30 minutes per file, connection and answer timeouts.
- The rate is a sliding window per source. Past it, a search answers "rate limited" with the delay (``Example maps: the declared rate of 30 requests per minute is used up``), and a download waits up to 30 s and then fails.
- A mod that is turned off, fails or is removed takes its declarations with it.
## Messages you will read {#errors}
A refused registration throws with the reason, and the mod fails. These come from the Rust that validates the declaration:
```text
download id must be 1 to 32 characters among a-z, 0-9 and `-`, got "Maps"
a mod registers at most 4 downloads
hosts lists 1 to 8 hosts
host "10.0.0.1": an IP address is never allowed
host "Api.example.org": a lowercase ASCII name of at most 253 characters
rateLimit is 1 to 120 requests per minute
auth.header is one of Authorization, X-API-Key, X-Auth-Token
unknown variable {foo}: use one of query, status, sort, offset, page, limit, cursor, keysMin, keysMax, starsMin, starsMax, bpmMin, bpmMax, lengthMin, lengthMax, genre, language, id
search.params names {sort} but search.sorts is empty
Offset paging needs a parameter with {offset}
a mirror names the source it serves: target: "osu"
a source needs `search`: it lists the sets of its tab
download has `url` or `urlField`, not both
download id is registered twice
```
The `mapped` format needs `response.item` and `osu` refuses it; `cursor` paging needs `response.nextCursor`, and `nextCursor` is only for `cursor` paging.
## Bridges: your functions compute the next step {#bridge}
When the site is not a JSON GET, register a bridge. You give the declaration (`id`, `name`, `description?`, `site?`, `hosts`, `rateLimit?`, `auth?`, with the same rules as above) and three functions. They are **pure and synchronous**: they never do I/O. Each one returns the **next step**, and the game does what the step says:
| Function | When the game calls it | Arguments |
|---|---|---|
| `search(query, page, state)` | the player searches or asks for the next page | the text (trimmed, 200 characters at most), the page (`1` the first time, else the `nextPage` of the last `results`), the `state` of the last `results` (`null` the first time) |
| `onResponse(response, state)` | after every `request` step, with the answer to it | `{ status, headers, text }` and the `state` that step carried |
| `action(result, actionId, state)` | the player presses a result's button, to download | the result `{ id, title, artist, data }`, the id of the button, and `null` |
A step has **exactly one** of `request`, `results`, `download` and `error`, with an optional `state`:
| Step | The game then |
|---|---|
| `{ request, state? }` | makes the request and calls `onResponse(response, state)` |
| `{ results, nextPage?, state? }` | shows the results; `nextPage` (a string or a number of 128 characters at most) is what the next `search` call receives as `page` |
| `{ download, state? }` | downloads the file (only from `action`) |
| `{ error }` | stops with your message (200 characters at most) as the error |
`onResponse` is needed as soon as one of your functions returns a `request`.
The example adapts a fictional site whose search is a POST with a form, answered in XML, and whose file is found in a second, detail request. Rust runs this exact file against recorded answers:
```ts
///
// Adapts a FICTIONAL site whose API is nothing like the declarative shape (`downloads.register`): the search is a POST with a
// form body answered in XML, and a map's file is found on a second, detail request. The mod never does any I/O: its functions
// only compute the next step (a request to make, results to show, a file to download). The GAME makes every request, only on
// the hosts declared below (https, redirects re-checked), calls `onResponse` back with the answer as text (2 MiB at most), and
// injects the player's token itself: this script never sees it.
//
// `example.org` is reserved for documentation: nothing is served there. The tests of the repository run this very file against
// recorded answers (crates/modding/tests/bridge.rs), no network involved.
/** What the fictional site's XML says about one map. */
interface Row {
id: string;
title: string;
artist: string;
mapper: string;
keys: number;
mb: string;
}
const text = (xml: string, tag: string): string => {
const found = new RegExp(`<${tag}>([^<]*)${tag}>`).exec(xml);
return found ? found[1].replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">") : "";
};
/** `` blocks. XML and HTML arrive as TEXT: strings and regular expressions are the tools. */
const rows = (xml: string): Row[] =>
[...xml.matchAll(/